How to rename multiple sheets based on cell values using VBA?

Renaming multiple sheets in Excel based on cell values using VBA can be quite useful for organizing your workbook dynamically. Below is a step-by-step guide and example code to achieve this.

Step-by-Step Guide

  • Open VBA Editor:
    • Press `ALT + F11` in Excel to open the Visual Basic for Applications editor.
  • Insert a Module:
    • In the VBA editor, go to `Insert` > `Module` to create a new module.
  • Write the VBA Code:
    • Copy and paste the VBA code below into the module. This code iterates over all sheets and renames them using the value from a specific cell.
  • Run the Macro:
    • Close the VBA editor and run the macro from Excel by pressing `ALT + F8`, selecting the macro, and clicking `Run`.

VBA Code Example

Here’s a VBA macro that renames each sheet based on the value of a specific cell (A1, for instance) in each sheet.

Sub RenameSheetsBasedOnCellValue()
    Dim ws As Worksheet
    Dim newName As String

    ' Loop through each worksheet in the workbook
    For Each ws In ThisWorkbook.Worksheets
        ' Get the new name from cell A1 of each sheet
        newName = ws.Range("A1").Value
        
        ' Check if the new name is not empty and doesn't exceed 31 characters
        If newName <> "" And Len(newName) <= 31 Then
            ' Optionally, check if the new name contains any invalid characters
            ' Common invalid characters are:  / ? * [ ]
            If Not (InStr(newName, "*") > 0 Or InStr(newName, ":") > 0 Or _
                    InStr(newName, "/") > 0 Or InStr(newName, "") > 0 Or _

Unlock Your Potential

Excel

Basic - Advanced

Access

Access Basic - Advanced

Power BI

Power BI Basic - Advanced

Help us grow the project