Almost every Excel macro that breaks in someone else's hands breaks for the same reason: it wrote to the wrong sheet, or it went looking for a sheet that was not there. It worked perfectly on your screen, because the right tab happened to be in front. Then a colleague ran it from the summary tab, or renamed Data to Daten, or had a second workbook open, and the macro either crashed with subscript out of range or, worse, quietly overwrote the wrong numbers.
This lesson is for anyone who has started writing VBA, with the recorder or by hand, and wants their macros to hit the right sheet every single time. You will learn what a Worksheet object is, the four ways to refer to one and how each of them can fail, and the two habits that make sheet references robust: the code name and a Worksheet variable set once at the top of a procedure.
The example is the macro from the free lesson above, WorksheetObjectTour. It builds a small data sheet with eight fictional regions, then a second sheet that lists every worksheet in the workbook with its tab name, code name, position, visibility and last used row, and finally renames the data tab to show that a variable does not care. All names and numbers are made up for practice.
A sheet is an object, not a word
When you work by hand, a sheet is the tab you click. In VBA, a sheet is an object: a thing with properties (its Name, Index, Visible state, UsedRange) and methods (Delete, Copy, Protect). Objects live inside other objects. Excel itself is the Application. It holds a collection called Workbooks, every workbook holds a collection called Worksheets, and every worksheet holds the cells you address with Range and Cells.
You pick one member out of a collection in two ways: by name, Worksheets("Data"), or by position, Worksheets(1), which is simply the leftmost tab. There is also a second collection, Sheets, which contains worksheets and chart sheets. Sheets(2) might be a chart sheet with no cells at all, so Sheets(2).Range("A1") can fail. Use Worksheets unless you specifically mean chart sheets as well.
The most important thing VBA does is also the least visible. If you write Range("A1").Value = 5 with nothing in front of it, VBA fills in the gap for you with whatever is active: the active sheet of the active workbook (inside a sheet's own code module, the gap is filled with that sheet instead). In the same way, a bare Worksheets("Data") means the Data sheet of the active workbook, which is not necessarily the workbook that contains your code. Every unqualified reference is a bet on what the user had in front of them when they clicked the button.
Worked example: the sheet that describes itself
Paste WorksheetObjectTour from the lesson into a module of a fresh workbook that has a single empty sheet, Sheet1, and run it with F5. First it adds a data sheet and captures it in one statement, Set wsData = ThisWorkbook.Worksheets.Add, names it Data plus the time and writes eight regions with revenue of 1,200 ร the region number:
| Row | Region (A) | Revenue (B) |
|---|---|---|
| 2 | Region 1 | 1,200 |
| 3 | Region 2 | 2,400 |
| 4 | Region 3 | 3,600 |
| 5 | Region 4 | 4,800 |
| 6 | Region 5 | 6,000 |
| 7 | Region 6 | 7,200 |
| 8 | Region 7 | 8,400 |
| 9 | Region 8 | 9,600 |
| Total | 43,200 |
Then it adds a report sheet directly after the data sheet with Worksheets.Add(After:=wsData) and loops through every worksheet with For Each ws In ThisWorkbook.Worksheets. Because Worksheets.Add without arguments puts the new sheet in front of the active one, the data sheet becomes the first tab, the report the second and the original Sheet1 the third. Run at 09:41:07, for example, the report looks like this:
| Tab name | Code name | Index | Visible | Last used row |
|---|---|---|---|---|
| Data 09-41-07 | Sheet2 | 1 | TRUE | 9 |
| Sheets 09-41-07 | Sheet3 | 2 | TRUE | 3 |
| Sheet1 | Sheet1 | 3 | TRUE | 1 |
Each column teaches something. Tab name is ws.Name, the text on the tab, which anybody can change by double-clicking it. Code name is ws.CodeName, the internal name you see in front of the brackets in the editor's Project Explorer, for example Sheet2 (Data 09-41-07). Index is ws.Index, the position counted from the left, which changes whenever someone drags a tab. Visible is the result of the comparison ws.Visible = xlSheetVisible, so it shows TRUE or FALSE.
Last used row comes from ws.Cells(ws.Rows.Count, 1).End(xlUp).Row: start in the last row of column A and jump up to the last filled cell. The data sheet gives 9 (header plus eight regions). The report sheet gives 3 because it measures itself while it is still being written: at that moment rows 1 to 3 of column A are filled. The empty Sheet1 gives 1, because End(xlUp) stops at row 1 when the column is empty. That last detail matters in real macros: an empty sheet and a sheet with only a header look the same to this formula, so check A1 as well if the difference matters.
Finally the macro renames the data tab to Renamed 09-41-07 and writes into D1 through the same variable. It still lands on the right sheet, because wsData holds the sheet itself, not its name. The message box confirms it: Listed 3 worksheets. The data tab is now called Renamed 09-41-07, and the variable still points at it.
Four ways to point at a sheet, and how each one breaks
Every sheet reference makes an assumption about what will not change. The matrix below tests five common styles against four everyday events: someone renames the tab, someone drags it to a different position, another workbook is active when the macro starts, or another tab of the same workbook is active.
Set has found the sheet; the lookup in the Set line still needs a reliable name or code name.
Range("A1")with nothing in front follows the user. It never mentions a name or position, so renames and moves do not affect it, but it writes to whatever sheet is active.Worksheets("Data")reads well and breaks on any rename, including an invisible trailing space. WithoutThisWorkbook.in front it also looks in the active workbook, which may be a file the user just opened.ThisWorkbook.Worksheets(1)survives renames and other workbooks, but the first tab is whatever tab is first today. One drag and it points at a different sheet without any error.- The code name, for example
shData.Range("A1"), survives everything a user can do from the Excel window, because only the editor can change it. Its limit: it works only for sheets in the workbook that contains the code. - A
Worksheetvariable is how you combine these. Find the sheet once with the safest lookup available,Set ws = shDataorSet ws = ThisWorkbook.Worksheets("Data"), and usews.on every line below.
Put together, a robust procedure looks like this. It finds the sheet once, checks it exists and writes a total with an ordinary Excel formula that returns 43,200 on the demo data:
Option Explicit
Sub WriteRegionTotal()
Dim ws As Worksheet
If Not SheetExists("Data") Then
MsgBox "There is no sheet called Data in this workbook.", vbExclamation
Exit Sub
End If
Set ws = ThisWorkbook.Worksheets("Data")
ws.Range("D1").Value = "Total"
ws.Range("D2").Formula = "=SUM(B2:B9)"
End Sub
Function SheetExists(ByVal sheetName As String) As Boolean
Dim ws As Worksheet
On Error Resume Next
Set ws = ThisWorkbook.Worksheets(sheetName)
On Error GoTo 0
SheetExists = Not ws Is Nothing
End Function
The demo macro names its tabs with the time, so to try this, rename the data tab to exactly Data first, or change the name in both places. The helper function is the standard existence check from the lesson wrapped up for reuse. On Error Resume Next lets the Set line fail silently when the sheet is missing, On Error GoTo 0 switches normal error handling straight back on, and ws Is Nothing tells you whether the lookup found anything. Note that Is Nothing is how you test an object variable; = Nothing does not compile.
Step by step: give your sheets safe names in the editor
- Open the editor. Press
Alt+F11(on a Mac Developer โ Visual Basic). - Show the Project Explorer. Press
Ctrl+Ror choose View โ Project Explorer. Each sheet is listed as code name (tab name), for example Sheet2 (Data 09-41-07). - Show the Properties window. Click the sheet in the Project Explorer and press
F4. The first property, (Name) with brackets, is the code name. The property called Name without brackets further down is the tab name. - Rename the code name. Type a meaningful name into (Name), such as
shData, and pressEnter. Code names must start with a letter and cannot contain spaces. - Use it in code. In any standard module of the same workbook,
shData.Range("A1").Valuenow refers to that sheet, whatever its tab is called. IntelliSense lists its properties when you type the dot. - Ask the workbook questions. Press
Ctrl+Gto open the Immediate window, type?ThisWorkbook.Worksheets.Countand pressEnter. Try?shData.Nameand?shData.Indexas well. - Test the failure on purpose. Rename the tab in Excel, then run a line that uses the old tab name. Read error 9 once, deliberately, so you recognise it immediately next time.
- Save as .xlsm. File โ Save As โ Excel Macro-Enabled Workbook, or the code and your code names are lost.
wsInput, wsReport and wsLog. Code that says wsReport.Range("B2") explains itself; code that says Sheets(3).Range("B2") needs a comment and a prayer.
Common mistakes and how to spot them
- Unqualified ranges.
RangeandCellswithout a sheet in front write to the active sheet. Spot it: search the module for lines that begin withRange(orCells(; in a standard module, each one is a guess. - A half-qualified range.
ws.Range(Cells(2, 1), Cells(9, 2))qualifiesRangebut not the twoCells, which still point at the active sheet. Spot it: run-time error 1004 when another sheet is active. Writews.Range(ws.Cells(2, 1), ws.Cells(9, 2)). - Trailing spaces and look-alike names.
"Data "is not"Data". Case does not matter, spaces do. Spot it: error 9 on a line that looks perfect; check the name with?Len(ActiveSheet.Name)in the Immediate window. Sheetswhere you meantWorksheets. A chart sheet in the collection shifts the numbering and has no cells. Spot it: error 438, object doesn't support this property or method, on a.Rangecall.- Forgetting
Set.ws = Worksheets("Data")withoutSetfails, because objects must be assigned withSet. Spot it: run-time error 91, object variable or With block variable not set. - Using the code name across workbooks.
shDataonly works in the workbook that holds the code. Spot it: withOption Expliciton, a compile error, variable not defined, when you move the code to another file. - Worksheets without ThisWorkbook. A bare
Worksheets("Data")searches the active workbook. Spot it: the macro works until the user opens a second file, then fails with error 9 or writes into that file.
Quick reference: objects, properties and keys
| Item | Example | What it gives you |
|---|---|---|
| Worksheet by name | ThisWorkbook.Worksheets("Data") | The sheet with that tab name; error 9 if missing |
| Worksheet by position | ThisWorkbook.Worksheets(1) | The leftmost worksheet |
| Code name | shData.Range("A1") | The sheet whatever its tab is called (own workbook only) |
| Worksheet variable | Dim ws As Worksheet โฆ Set ws = shData | One reference used on every later line |
| Add a sheet | Set ws = ThisWorkbook.Worksheets.Add(After:=wsData) | Creates the sheet and returns it |
| Tab name / code name / position | ws.Name / ws.CodeName / ws.Index | The three identities of a sheet |
| Last used row | ws.Cells(ws.Rows.Count, 1).End(xlUp).Row | Last filled row in column A |
| Loop over sheets | For Each ws In ThisWorkbook.Worksheets | Every worksheet in tab order |
| Is it there? | If ws Is Nothing Then | True when a lookup found nothing |
| Project Explorer / Properties | Ctrl+R / F4 | See and change code names |
| Immediate window | Ctrl+G | Ask questions such as ?Worksheets.Count |
Real-world uses
- Monthly reporting pack. A workbook with an input sheet, a calculation sheet and a report sheet, each with a code name. The macro refreshes and formats the report, and still works after the finance manager renames the tabs to German.
- Consolidating branch sheets. One sheet per branch, all with the same layout. A
For Eachloop adds up a range from every sheet except the summary, without ever activating a tab. - A contents page. A workbook with forty sheets gets an index sheet that lists every tab name and links to it, rebuilt by one click whenever sheets are added.
- Importing from another file. A macro in a tools workbook opens a supplier's price list, copies the rows it needs into its own sheet and closes the file again, using variables for both workbooks so nothing depends on which window is in front.
- Template sheets. A new month means a copy of a template sheet with the right name, created and positioned by the macro instead of by hand.
What you will build in the rest of this course
This first lesson is free. Lessons 2 to 7 are part of the full course, a one-time purchase of $9.90, and each of them turns one habit from this article into a dependable pattern.
Referencing Sheets Safely. You make the rules from this lesson concrete: why a bare Range is a guess, how to set a variable once and use it everywhere, why you never need Select or Activate, and the existence check written out properly.
Adding, Deleting and Copying Sheets. You create sheets exactly where you want them, delete them without the confirmation pop-up stopping your macro, respect the naming rules Excel enforces and copy a template sheet reliably, even though Copy does not hand back the new sheet.
ThisWorkbook vs ActiveWorkbook. You work through the classic "it worked yesterday" bug, where a macro opens a second file and suddenly writes into it, and learn to give every workbook its own variable.
Opening, Saving and Closing Workbooks. You open files read-only, check they exist before you try, choose correctly between Save, SaveAs and SaveCopyAs, and always close what you opened.
Looping Through Sheets. You run the same job on every sheet, skip the ones you must not touch, build a self-updating index sheet and delete sheets inside a loop without skipping any.
Visibility, Protection and Housekeeping. You use the three levels of hidden, protect sheets so that people cannot type in them while your macros still can, and finish with a housekeeping routine that leaves the workbook in a known state.
Summary
In VBA a sheet is an object inside a workbook inside Excel. Refer to it by tab name and a rename breaks your code; by position and a drag breaks it; with nothing at all and you write to whatever happens to be active. The code name survives every change a user can make in the Excel window, and a Worksheet variable set once at the top of a procedure makes every later line short, explicit and immune to renames. In the demo, the report lists three sheets with their names, code names and positions, and the renamed data tab still receives its write through wsData.
Try it now in the lesson above: run WorksheetObjectTour, open the Project Explorer and compare what you see with the report sheet, then give the data sheet a code name and answer the check question about error 9.
Frequently asked questions
What is the difference between Sheets and Worksheets in VBA?
Worksheets contains only normal grid sheets, while Sheets also contains chart sheets. Use Worksheets when you want to work with cells, because a chart sheet has no Range.
What does run-time error 9 subscript out of range mean in Excel VBA?
The collection has no member with the name or number you asked for. For sheets it usually means a typo, a trailing space, a renamed tab or a lookup in the wrong workbook.
What is a sheet code name in Excel VBA?
It is the internal name of a sheet shown in the VBA editor before the tab name in brackets, set in the (Name) property. Users cannot change it from Excel, so code that uses it survives tab renames.
How do I check if a worksheet exists in VBA?
Try to assign it to a Worksheet variable with On Error Resume Next, switch error handling back on with On Error GoTo 0, and test whether the variable Is Nothing.
How do I refer to a sheet in another workbook?
Qualify the reference with the workbook, for example wb.Worksheets("Data").Range("A1"), where wb is a Workbook variable set when you opened the file. Code names only work inside the workbook that contains the code.
Why does my macro write to the wrong sheet?
Most likely it uses Range or Cells without a sheet in front, so VBA uses the active sheet. Set a Worksheet variable at the top of the procedure and put it in front of every range.
Keep going: Worksheets & Workbooks
This free lab is lesson 1 of 7. Unlock the other 6 hands-on labs, the final exam and your certificate for a one-time $9.90.
- Referencing Sheets Safely
- Adding, Deleting and Copying Sheets
- ThisWorkbook vs ActiveWorkbook
- Opening, Saving and Closing Workbooks
- Looping Through Sheets
- Visibility, Protection and Housekeeping