Automatically Renaming Worksheets

by Allen Wyatt
(last updated October 13, 2018)

Renier has a workbook that has ten worksheets in it, named Resources 1 through Resources 10. If he deletes one of these worksheets (say, Resources 3), Renier would like the remaining worksheets to be renamed, automatically, to "close up the gap," so to speak. Thus, Resources 4 through Resources 10 would automatically rename to become Resources 3 through Resources 9.

There are several ways that you can go about this task, all through the use of macros. One approach is probably less automatic than what Renier would prefer, but it works great:

Sub ReNameSheets()
    Dim J As Integer
    Dim wks As Worksheet

    J = 0
    For Each wks In ActiveWorkbook.Worksheets
        J = J + 1
        wks.Name = "TempSheet " & J
    Next wks

    J = 0
    For Each wks In ActiveWorkbook.Worksheets
        J = J + 1
        wks.Name = "Resources " & J
    Next wks
End Sub

This macro simply steps through all the worksheets, renaming them using the convention that Renier preferred. The macro could be run on demand, anytime a renaming of the worksheets is desired.

Note that the code actually makes two naming passes through the worksheets. The first one is to set the names of the worksheets to temporary names, and the second is to set them to final names. The two passes helps avoid a potential problem when you add worksheets to the workbook—for instance, if you add a new worksheet just before Resources 4, then a single-pass renaming would try to rename the new worksheet as Resources 4, which would generate an error because worksheet 5 would, at that point, also be named Resources 4. By doing two passes, you rename everything to something entirely new and then do the final name setting.

For a more automatic approach, you might want to consider using the SheetBeforeDelete event for the Workbook object. This event is triggered (as its name suggests) immediately before a worksheet is deleted. Here's an example of an event-handler approach:

Private Sub Workbook_SheetBeforeDelete(ByVal Sh As Object)
    Dim sPrefix As String
    Dim iNum1 As Integer
    Dim iNum2 As Integer
    Dim wks As Worksheet

    sPrefix = "Resources "
    If Left(Sh.Name, Len(sPrefix)) = sPrefix Then
        iNum1 = CInt(Right(Sh.Name, Len(Sh.Name) - Len(sPrefix)))
        Sh.Name = "TempSheet 9999"
        For Each wks In Sheets
            If Left(wks.Name, Len(sPrefix)) = sPrefix Then
                iNum2 = CInt(Right(wks.Name, Len(wks.Name) - Len(Prefix)))
                If iNum2 > iNum1 Then
                    wks.Name = sPrefix & (iNum2 - 1)
                End If
            End If
        Next
    End If
End Sub

The event handler checks to see if the worksheet being deleted begins with the designated prefix ("Resources "). If it does, then it renames the worksheet being deleted to a temporary name ("TempSheet 9999"). Then, it steps through each of the worksheets in the workbook and renames any worksheet that has the proper prefix and a higher suffix number than the worksheet that is being deleted.

There are two big caveats with this approach. First, it won't handle if you add worksheets. Second, it will only reliably handle the deletion of single worksheets. If you delete multiple worksheets at one time, the numbering will be incorrect and, in fact, the macro may crash because of the way in which Excel handles the deletions.

If you anticipate deleting multiple worksheets quite often, then you can sidestep the issue by using a different approach. This one relies on the use of the SheetActivate and SheetDeactivate events of the Workbook object.

' These variables are declared OUTSIDE of the events,
' so they are available globally.

    Dim shName As String
    Dim Avail As Variant

Private Sub Workbook_SheetDeactivate(ByVal Sh As Object)
    ' When the worksheet is deactivated, the name of
    ' that worksheet is stored in the shName variable.

    shName = Sh.Name
End Sub
Private Sub Workbook_SheetActivate(ByVal Sh As Object)
    Dim wks As Worksheet
    Dim J As Integer

    On Error Resume Next
    ' The following line will generate an error if the
    ' the worksheet shName was deleted. If the error
    ' occurrs, then we can trigger the renaming.
    Avail = Sheets(shName).Range("A1")
    If Err Then
        J = 0
        For Each wks In ActiveWorkbook.Worksheets
            J = J + 1
            wks.Name = "Resources " & J
        Next wks
    End If
    On Error GoTo 0
End Sub

These event handlers work because the SheetDeactivate event is triggered automatically whenever a worksheet is left (for example, when you activate a different worksheet) or whenever one is deleted. The SheetActivate event is then triggered and it checks, essentially, to see if the sheet previously deactivated can be reached or not. If it cannot be reached, then we know it was deleted and we can trigger a renaming of all the worksheets.

The approach you use to renaming is entirely up to you based on a determination of how you want to work with your worksheets.

Note:

If you would like to know how to use the macros described on this page (or on any other page on the ExcelTips sites), I've prepared a special page that includes helpful information. Click here to open that special page in a new browser tab.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (13572) applies to Microsoft Excel 2007, 2010, 2013, 2016, 2019, and Excel in Office 365.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Backing Up Your AutoText Entries

Got a bunch of AutoText entries defined for your system? You'll undoubtedly want to back them up at some time. Here's how ...

Discover More

Avoiding Rounding Errors in Formula Results

Some formulas just don't give the results you expect. Sometimes this is due to the way that Excel handles rounding. ...

Discover More

Combining Documents

Need to combine quite a few text documents? A macro may be the easiest way to stuff them all into a single Word document.

Discover More

Program Successfully in Excel! John Walkenbach's name is synonymous with excellence in deciphering complex technical topics. With this comprehensive guide, "Mr. Spreadsheet" shows how to maximize your Excel experience using professional spreadsheet application development tips from his own personal bookshelf. Check out Excel 2013 Power Programming with VBA today!

More ExcelTips (ribbon)

Comparing Formulas on Two Worksheets

As you develop worksheets, it is not unusual to end up with two that are essentially the same. At some point you may want ...

Discover More

Jumping to Alphabetic Worksheets

Got a workbook with a lot of worksheets in it? Here are some handy ways to jump to the worksheet you want, alphabetically.

Discover More

Protecting a Single Worksheet

Excel allows you to protect your worksheets easily—and that includes if you need to protect only a single worksheet ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is 6 - 5?

There are currently no comments for this tip. (Be the first to leave your comment—just use the simple form above!)


This Site

Got a version of Excel that uses the ribbon interface (Excel 2007 or later)? This site is for you! If you use an earlier version of Excel, visit our ExcelTips site focusing on the menu interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.