smiley3141
Board Regular
- Joined
- Aug 13, 2010
- Messages
- 77
Hello, everyone. I am trying to check have VBA check to see if a worksheet name already exists before adding a worksheet. If it does, I want to make an Adjustment to the name and then check the new name (The adjustment adds " - 2" and then " - 3" and so on to the original name each time through the loop). This seemed pretty simple but I cannot make it work. If the original name is not one of the sheet names, it works fine, but it does not add a worksheet with the adjusted names even if they are not already one of the named sheets. Can someone help me? I am using Excel 2010.
My code is the following:
Sub AddNewWorksheet()
Dim NewName As String
Dim NumSheets As Long
Dim i As Long
Dim WorksheetsExists As Boolean
NumSheets = Sheets.Count
For i = 1 To NumSheets + 1
NewName = Range("MyTabName")
For Each Sht In ThisWorkbook.Worksheets
'Following line ignores case in comparison
If UCase(Sht.Name) = UCase(NewName) Then
WorksheetExists = True
Exit For
End If
Next Sht
If WorksheetExists = False Then
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = NewName
i = NumSheets + 1
Else
Range("TabNameAdj").Value = Range("TabNameAdj").Value + 1
End If
Next i
End Sub
Thanks for any help you can give me.
My code is the following:
Sub AddNewWorksheet()
Dim NewName As String
Dim NumSheets As Long
Dim i As Long
Dim WorksheetsExists As Boolean
NumSheets = Sheets.Count
For i = 1 To NumSheets + 1
NewName = Range("MyTabName")
For Each Sht In ThisWorkbook.Worksheets
'Following line ignores case in comparison
If UCase(Sht.Name) = UCase(NewName) Then
WorksheetExists = True
Exit For
End If
Next Sht
If WorksheetExists = False Then
Worksheets.Add(After:=Worksheets(Worksheets.Count)).Name = NewName
i = NumSheets + 1
Else
Range("TabNameAdj").Value = Range("TabNameAdj").Value + 1
End If
Next i
End Sub
Thanks for any help you can give me.