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, and 2016.

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

Formatting Comments

Need to change the appearance of the text in your comments? It's easy to do using techniques you are already familiar with.

Discover More

Figuring Out the Low-Score Winner

Need to figure out the lowest score in a range of scores? Here's the formulas to get the information you need.

Discover More

Shortcuts to Change Text Colors

Want a way to change the color of your text through a shortcut key? You can do so by using the macros described in this tip.

Discover More

Save Time and Supercharge Excel! Automate virtually any routine task and save yourself hours, days, maybe even weeks. Then, learn how to make Excel do things you thought were simply impossible! Mastering advanced Excel macros has never been easier. Check out Excel 2010 VBA and Macros today!

More ExcelTips (ribbon)

Making Multiple Worksheet Copies

If you spend a lot of time creating a worksheet, you might want to make multiple copies of that worksheet as a starting ...

Discover More

Dynamic Worksheet Tab Names

Need a worksheet's name to change based on the contents of a cell? You'll need to rely on a macro to do the changing, but ...

Discover More

Changing the Color of Worksheet Gridlines

Want the gridlines in your worksheet to be a different color? You aren't limited to stodgy black; Excel lets you make ...

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 seven less than 8?

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.