1
votes

How can i rename a sheet and add a number to the end of the name if the name already exists.

I'm using this code but need to add a number to the end of sheet name if name already exists.

VBA_BlankBidSheet.Copy After:=ActiveSheet
ActiveSheet.Name = "New Name"
4
let me know if the code in my answer below is what you meantShai Rado

4 Answers

2
votes

The code below loops through all worksheets in ThisWorkbook and checks if there is already a sheet with a name of "New Name", if it does it adds a number at the end.

Sub RenameSheet()

Dim Sht                 As Worksheet
Dim NewSht              As Worksheet
Dim VBA_BlankBidSheet   As Worksheet
Dim newShtName          As String

' modify to your sheet's name
Set VBA_BlankBidSheet = Sheets("Sheet1")

VBA_BlankBidSheet.Copy After:=ActiveSheet    
Set NewSht = ActiveSheet

' you can change it to your needs, or add an InputBox to select the Sheet's name
newShtName = "New Name"

For Each Sht In ThisWorkbook.Sheets
    If Sht.Name = "New Name" Then
        newShtName = "New Name" & "_" & ThisWorkbook.Sheets.Count               
    End If
Next Sht

NewSht.Name = newShtName

End Sub
0
votes

The test procedure on a new workbook will generate these sheet names: Sheet1_1, Sheet2_1 and ABC.

If Sheet1_1 exists and we ask for a new Sheet1 it will return Sheet1_2, as ABC doesn't exist in a new workbook it will return ABC.

The Test code adds a new sheet called 'DEF'. If you run it a second time it will create 'DEF_1'.

Sub Test()

    Debug.Print RenameSheet("Sheet1")
    Debug.Print RenameSheet("Sheet2")
    Debug.Print RenameSheet("ABC")

    Dim wrkSht As Worksheet
    Set wrkSht = Worksheets.Add
    wrkSht.Name = RenameSheet("DEF")

End Sub

    Public Function RenameSheet(SheetName As String, Optional Book As Workbook) As String

        Dim lCounter As Long
        Dim wrkSht As Worksheet

        If Book Is Nothing Then
            Set Book = ThisWorkbook
        End If

        lCounter = 0
        On Error Resume Next
            Do
                'Try and set a reference to the worksheet.
                Set wrkSht = Book.Worksheets(SheetName & IIf(lCounter > 0, "_" & lCounter, ""))
                If Err.Number <> 0 Then
                    'If an error occurs then the sheet name doesn't exist and we can use it.
                    RenameSheet = SheetName & IIf(lCounter > 0, "_" & lCounter, "")
                    Exit Do
                End If
                Err.Clear
                'If the sheet name does exist increment the counter and try again.
                lCounter = lCounter + 1
            Loop
        On Error GoTo 0

    End Function  

Edit: Removed the Do While bNotExists as I wasn't checking bNotExists - just using Exit Do instead.

0
votes

Building on Darren's answer, I thought it might be easier to just rename the sheet right away instead of returning the name that can be used. I also refactored a bit. Here's my take:

Private Sub nameNewSheet(sheetName As String, newSheet As Worksheet)
    Dim named As Boolean, counter As Long
    On Error Resume Next
        'try to name the sheet. If name is already taken, start looping
        newSheet.Name = sheetName
        If Err Then
            If Err.Number = 1004 Then 'name already used
                Err.Clear
            Else 'unexpected error
                GoTo nameNewSheet_Error
            End If
        Else
            Exit Sub
        End If

        named = False
        counter = 1

        Do
            newSheet.Name = sheetName & counter
            If Err Then
                If Err.Number = 1004 Then 'name already used
                    Err.Clear
                    counter = counter + 1 'increment the number until the sheet can be named
                Else 'unexpected error
                    GoTo nameNewSheet_Error
                End If
            Else
                named = True
            End If
        Loop While Not named

        On Error GoTo 0
        Exit Sub

    nameNewSheet_Error:
    'add errorhandler here

End Sub
0
votes

The .net version of VB uses the Try ... Catch formulation to catch runtime errors, see {https://msdn.microsoft.com/en-us/library/ms973849.aspx}(https://msdn.microsoft.com/en-us/library/ms973849.aspx) for a comparison with the old "on error" formulation of VB6 and before. It is better suited to do what you want, and will make shorter exception runs imho.

I'm trying to find out what exception is thrown when trying to rename to an existing sheetname, and will edit here to a workable script when i find it.