To reference a worksheet by its name in Excel VBA, use Worksheets("Sheet1") or Sheets("Sheet1") — for example, Worksheets("Data").Range("A1") = 5 writes the value 5 to cell A1 on the sheet named “Data”. This is the most direct and readable way to access a specific sheet, and it works even if the sheet is not active or visible.
Why Reference by Name Instead of Index
Every worksheet has both a name (the tab label you see) and an index number (its position from left to right). Referencing by name is almost always safer because the index changes if you move, add, or delete sheets. For example, if your workbook has sheets in order: Summary, Data, Charts, then Worksheets(2) points to “Data”. But if you drag “Charts” to the left, Worksheets(2) now points to “Charts”, breaking your code. Using Worksheets("Data") always finds the correct sheet regardless of order.
Another advantage is readability. When you revisit code months later, Worksheets("Data") tells you exactly which sheet you meant, while Worksheets(2) requires you to remember the layout at the time the code was written.
Basic Syntax and Common Variations
The Worksheets collection contains only worksheet-type sheets (not chart sheets or macro sheets). The Sheets collection contains all sheets, including chart sheets. For most tasks, Worksheets is what you want.
Here are the standard ways to refer to a sheet by name:
Worksheets("Sheet1")— returns the worksheet object.Sheets("Sheet1")— same, but also works for chart sheets.ThisWorkbook.Worksheets("Sheet1")— explicitly refers to the workbook containing the code.ActiveWorkbook.Worksheets("Sheet1")— refers to the currently active workbook (use with caution).
If you omit the workbook qualifier, VBA uses the active workbook. That can cause errors if the user has multiple workbooks open. To be safe, always qualify with ThisWorkbook when the sheet is in the same workbook as your code.
Working with the Sheet’s Code Name
Each worksheet also has a “CodeName” that you can set in the VBA editor (in the Properties window, under (Name)). This name is visible in the Project Explorer and does not change when the user renames the tab. For example, if you set the CodeName to wsData, you can write wsData.Range("A1") = 10 directly, without any Worksheets prefix. This is faster and avoids errors if the tab name is changed.
However, CodeNames are not visible to the user and can be confusing if you share the workbook. Many developers prefer to use the tab name with Worksheets because it matches what users see. The choice depends on whether you need stability against user renaming or clarity for other developers.
Handling Sheet Names That Change or Contain Spaces
Sheet names can contain spaces, punctuation, and even start with numbers. In VBA, you always enclose the name in double quotes: Worksheets("Sales Data"). If the name contains a double quote character (rare), you double it: Worksheets("Sheet""1").
A common problem is that users rename sheets. If you hard-code a name like “Data”, and the user changes it to “Data 2024”, your code will fail with a subscript out of range error. To handle this, you can check if the sheet exists before using it:
Dim ws As Worksheet
On Error Resume Next
Set ws = ThisWorkbook.Worksheets("Data")
On Error GoTo 0
If ws Is Nothing Then
MsgBox "Sheet 'Data' not found."
Else
ws.Range("A1") = 100
End If
This code attempts to set ws to the sheet named “Data”. If it doesn’t exist, ws remains Nothing, and you can handle it gracefully.
Looping Through Sheets by Name or Condition
Sometimes you need to process multiple sheets, but only those with certain names. You can loop through the Worksheets collection and filter by name using the Like operator or InStr:
Dim ws As Worksheet
For Each ws In ThisWorkbook.Worksheets
If ws.Name Like "*Data*" Then
ws.Range("A1") = ws.Name
End If
Next ws
This writes each sheet’s name into cell A1 of that sheet, but only for sheets whose names contain “Data”. The Like operator supports wildcards: * for any sequence, ? for a single character.
Common Errors and How to Fix Them
The most frequent error is Subscript out of range (Error 9), which occurs when you reference a sheet name that doesn’t exist. Double-check the spelling, including spaces and case (names are case-insensitive but must match exactly otherwise). Also, ensure the sheet is in the workbook you think it is — if you used ActiveWorkbook and the user has another workbook active, the sheet may not be there.
Another error is Object required when you forget the Set keyword for object variables. For example, Set ws = Worksheets("Data") is correct; ws = Worksheets("Data") causes an error.
If you get a Type mismatch when comparing names, ensure you are comparing strings, not numeric values. Also, remember that Worksheets is a collection, so you cannot use it without an index or name.
Alternatives to Referencing by Name
While referencing by name is the most readable, there are alternatives:
- Index number:
Worksheets(1)— faster but fragile if order changes. - ActiveSheet:
ActiveSheet— uses the currently selected sheet, but is unpredictable if the user clicks elsewhere. - CodeName: As described above, use the sheet’s CodeName directly.
- Find by cell value: Loop through sheets and check a specific cell to identify the right one. This is useful when the name is not reliable but a unique value exists in a cell.
For most cases, name-based referencing is the best balance of clarity and stability. If you need to allow users to rename sheets without breaking code, consider using the CodeName or a hidden helper sheet that stores the actual name.
Frequently Asked Questions
How do I get the name of the current sheet in VBA?
Use ActiveSheet.Name to get the name of the active sheet, or ThisWorkbook.ActiveSheet.Name to be explicit. This returns a string that you can store in a variable or use in a message box.
Can I reference a sheet by name without activating it?
Yes. Worksheets("Data").Range("A1") = 5 works without activating the sheet. The sheet does not need to be visible or selected. This is more efficient than activating and then referencing.
What is the difference between Worksheets and Sheets in VBA?
Worksheets contains only worksheet objects. Sheets contains all sheets, including chart sheets and macro sheets. If you have a chart sheet, Worksheets("Chart1") will fail, but Sheets("Chart1") will work. For normal data sheets, they are interchangeable.
How do I rename a sheet using VBA?
Use the Name property: Worksheets("Sheet1").Name = "NewName". This changes the tab label. Note that the sheet’s CodeName remains unchanged unless you modify it in the VBA editor.
Why does my macro stop with “Subscript out of range”?
This error means the sheet name you referenced does not exist in the workbook. Check for typos, extra spaces, or that the sheet is in the correct workbook. If you use ActiveWorkbook, ensure the intended workbook is active. Use ThisWorkbook to avoid ambiguity.
Can I use a variable as the sheet name?
Yes. Store the name in a string variable and use it: Dim sheetName As String: sheetName = "Data" then Worksheets(sheetName).Range("A1") = 1. This is useful when the name comes from a cell or user input.
Related
- How to Select All in Gallery on Windows (Photos & File Explorer)
- Driver Bit Holder: Types, Uses, and How to Choose
- Google Sheets COUNTIF Not Blank: 3 Easy Ways
Try it: the Column Letter to Number: aA is 27, XFD is 16,384. Converts both ways.
More in VBA & macros
- TMG Macro Recorder? Excel’s Built-In Option Explained“TMG macro recorder” is not the name of a standard feature in Microsoft Excel. If you mean recording…
- Excel VBA: Center a UserForm on Screen AutomaticallyTo center an Excel VBA UserForm on the screen, set its StartUpPosition property to 2 - CenterScreen before…
- Excel VBA Macro Shortcut: How to Assign and Use ItIn Excel for Microsoft 365 on Windows, assign a shortcut to a VBA macro by choosing Developer >…
- Excel Macro Recorder: Keyboard Shortcuts and SetupYes. In Excel for Microsoft 365 on Windows, record a macro from Developer > Code > Record Macro…
- Unload UserForm VBA: Close Forms and Reset State SafelyIn VBA, use Unload UserForm1 to close and unload a form, or use Unload Me from code inside…
- Excel Macro Tiny Task Manager: Build a Simple ListIf you mean a tiny task manager built with an Excel macro, yes: a short VBA macro can…
Sources: Function behaviour and menu paths: Microsoft Support documentation for Excel. Method & sources
Spotted an error in this guide? Let us know.