Auto increment by 1 when rename excel any tab if name exist

Mohsin110

New Member
Joined
Aug 26, 2023
Messages
23
Office Version
  1. 2021
Platform
  1. Windows
Please suggest me a VBA code, when copy any tab and rename it if the names already exist, it should auto increment by 1 instead of giving a message (That name is already taken. Try a different name).
For example if the sheets already are available as SP001-1633, SP001-1633 (2), SP001-1633 (3), then I copy and paste any tab and try to rename as SP001-1633 it should auto increment as SP001-1633 (4).

Pic001.png
 

Excel Facts

Select a hidden cell
Somehide hide payroll data in column G? Press F5. Type G1. Enter. Look in formula bar while you arrow down through G.
Something like this?

VBA Code:
Option Explicit

Sub RenameASheet()
    Dim thisSheet As Worksheet
    Dim indexNum As Long
    Dim newName As String
    Dim leftOfName As String
    Set thisSheet = ActiveSheet
    newName = InputBox("Please provide the new name for this sheet", "Rename sheet " & thisSheet.Name, thisSheet.Name)
    If newName <> thisSheet.Name Then
        indexNum = GetIndexForSheetName(newName)
        If indexNum = 0 Then
            thisSheet.Name = newName
        Else
            leftOfName = Trim(CStr(Split(newName, "(")(0)))
            thisSheet.Name = leftOfName & " (" & indexNum & ")"
        End If
    End If
End Sub

Function GetIndexForSheetName(newName) As Long
    Dim sh As Worksheet
    Dim leftOfName As String
    Dim ct As Long
    leftOfName = Trim(CStr(Split(newName, "(")(0)))
    For Each sh In ThisWorkbook.Worksheets
        If LCase(sh.Name) Like LCase(leftOfName) & "*" Then
            ct = ct + 1
        End If
    Next
    GetIndexForSheetName = ct
End Function
 
Upvote 0
Solution

Forum statistics

Threads
1,221,310
Messages
6,159,176
Members
451,543
Latest member
cesymcox

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top