Excel VBA Set Worksheet Name Variable Guide
In this article
To set a worksheet name as a variable in Excel VBA, you declare a String variable and assign it the .Name property of a specific sheet, such as mySheetName = ActiveSheet.Name. This allows your code to remember a sheet's name and reference it later in the script without having to hard-code the name, making your macros dynamic and flexible across different workbooks.
What You'll Need
- Microsoft Excel installed on a Windows or Mac computer.
- A workbook with at least one worksheet containing data.
- The Developer tab enabled in the Excel Ribbon.
- Basic familiarity with opening the Visual Basic Editor (VBE).
Step-by-Step
- Open the Visual Basic Editor: Press
Alt + F11on your keyboard. This opens the VBE window where all your VBA modules and code reside. - Insert a New Module: In the top menu, go to
Insert > Module. This creates a blank space where you can write your macro. - Declare the Variable: At the top of your subroutine, you must tell Excel what kind of data the variable will hold. Since a worksheet name is text, use the
Stringdata type. TypeDim wsName As String. This allocates memory for a text string. - Assign the Worksheet Name: You now need to tell the variable which sheet's name to capture. There are three common ways to do this depending on your goal:
- Active Sheet: Use
wsName = ActiveSheet.Name. This captures the name of whatever sheet is currently selected on the screen. - Specific Index: Use
wsName = Sheets(1).Name. This captures the name of the first sheet in the workbook, regardless of what it is named. - Specific Code Name: Use
wsName = Sheet1.Name. This uses the internal VBA code name, which remains the same even if a user changes the tab name in Excel.
- Active Sheet: Use
- Use the Variable in Your Code: Now that the name is stored in
wsName, you can use it to reference the sheet later. For example, to select that sheet again, you would writeSheets(wsName).Select. - Test the Macro: Press
F5or click the green "Run" arrow in the toolbar to execute the code and ensure the variable is capturing the name correctly.
Common Mistakes
One of the most frequent errors is forgetting to declare the variable using Dim. While VBA allows "implicit declaration" (creating variables on the fly), this often leads to typos. For example, if you define wsName but later type wsNam, VBA will treat the second one as a brand new, empty variable, and your code will fail to find the worksheet.
Another common mistake is trying to set the variable after the sheet has been deleted or renamed by another part of the script. If you capture the name at the start of the macro, then rename the sheet, the variable wsName still holds the old name. Attempting to call Sheets(wsName) after the rename will result in a "Subscript out of range" error because a sheet with the old name no longer exists.
Users also frequently confuse the Worksheet object with a String variable. A String variable only holds the text of the name (e.g., "Sales Data"). A Worksheet object holds the entire sheet including its cells, colors, and properties. If you try to use a String variable where an Object is required, or vice versa, the code will crash.
Tips
To prevent the typo errors mentioned above, always place Option Explicit at the very top of your module. This forces you to declare every variable. If you misspell a variable name, VBA will highlight it and stop you before you even run the code, saving hours of debugging time.
If you are working with multiple workbooks, be explicit about which workbook you are referencing. Instead of ActiveSheet.Name, use ThisWorkbook.Sheets("Sheet1").Name. ThisWorkbook refers to the file where the code is actually written, ensuring that your macro doesn't accidentally grab a sheet name from a different open file.
For more advanced automation, consider using a loop to set variables for multiple sheets. You can use For Each ws In ThisWorkbook.Worksheets to iterate through every sheet, capturing each name into a variable or an array to perform bulk updates across the entire workbook.
Troubleshooting
If your code returns a "Run-time error '9': Subscript out of range", it means VBA cannot find a worksheet with the name stored in your variable. First, check for trailing or leading spaces in your sheet tabs. A sheet named "Data " (with a space) is different from a sheet named "Data". Use the Trim() function in VBA to remove accidental spaces from your variable.
If the variable appears to be empty (blank), ensure that the assignment line (e.g., wsName = ActiveSheet.Name) is actually being executed. Use the Debug.Print wsName command to print the value to the Immediate Window (Ctrl+G) to verify that the variable is capturing the name at the exact moment you expect it to.
If you receive a "Type Mismatch" error, you likely declared the variable as an Integer or Boolean instead of a String. Double-check your Dim statement to ensure it says As String.
Frequently Asked Questions
Can I set the variable based on a cell value?
Yes. Instead of using ActiveSheet.Name, you can set the variable to the value of a cell: wsName = Range("A1").Value. This allows you to drive your macro's target sheet based on user input in the spreadsheet.
What is the difference between a String variable and a Worksheet object?
A String variable stores only the text name of the sheet. A Worksheet object (declared as Dim ws As Worksheet) stores a reference to the actual sheet object, allowing you to access properties like ws.Cells or ws.Range directly without needing the name.
How do I handle sheets with names that change frequently?
The best approach is to use the CodeName. In the VBE properties window, you can see the (Name) property (e.g., Sheet1). This is the internal name. You can reference it directly in code as Sheet1.Name to get the current tab name, regardless of what the user has renamed it to in the Excel interface.
Can I use this to rename a sheet?
Yes. Once you have a variable, you can assign a new value to it and then apply that value to the sheet: wsName = "New Name" followed by ActiveSheet.Name = wsName.
Does this work across different Excel versions?
Yes, the .Name property and String variable declaration are fundamental parts of VBA and work consistently across all modern versions of Excel for Windows and Mac.