Tabellab

The Worksheet Object

Lesson 1 of 7Reading

A sheet is a thing, not a word

Working by hand you click a tab and start typing. VBA has no hands, so it needs a way to say which sheet it means, and that way is the Worksheet object. Every workbook owns a collection called Worksheets; you pick one out of it by tab name, Worksheets("Data"), or by position, Worksheets(1). Back comes an object with a name, an index, a used range and a few hundred other properties.

Worksheets or Sheets?

  • Worksheets โ€” normal grid sheets only. What you want almost every time.
  • Sheets โ€” grid sheets and chart sheets mixed, so Sheets(2) may not be a grid at all and .Range on it fails.
  • By name โ€” Worksheets("Data") reads well, and breaks when somebody renames the tab.
  • By index โ€” Worksheets(1) is simply the leftmost tab, so it breaks the moment somebody drags one.

A macro that shows a sheet describing itself

Paste this into a module (Alt+F11 โ†’ Insert โ†’ Module) and press F5. It builds a data sheet, then a second sheet listing every worksheet with its tab name, code name, position, visibility and last used row โ€” and finally renames the data tab to prove a point.

Option Explicit

Sub WorksheetObjectTour()
    Dim wsData As Worksheet
    Dim wsReport As Worksheet
    Dim ws As Worksheet
    Dim stamp As String
    Dim i As Long
    Dim r As Long

    stamp = Format(Now, "hh-mm-ss")

    ' --- a data sheet, built by the macro itself ---
    Set wsData = ThisWorkbook.Worksheets.Add
    wsData.Name = "Data " & stamp
    wsData.Range("A1:B1").Value = Array("Region", "Revenue")

    For i = 1 To 8
        wsData.Cells(i + 1, 1).Value = "Region " & i
        wsData.Cells(i + 1, 2).Value = 1200 * i
    Next i

    wsData.Range("A1:B1").Font.Bold = True

    ' --- a report sheet, listing every worksheet in this workbook ---
    Set wsReport = ThisWorkbook.Worksheets.Add(After:=wsData)
    wsReport.Name = "Sheets " & stamp
    wsReport.Range("A1:E1").Value = _
        Array("Tab name", "Code name", "Index", "Visible", "Last used row")

    r = 1
    For Each ws In ThisWorkbook.Worksheets
        r = r + 1
        wsReport.Cells(r, 1).Value = ws.Name
        wsReport.Cells(r, 2).Value = ws.CodeName
        wsReport.Cells(r, 3).Value = ws.Index
        wsReport.Cells(r, 4).Value = (ws.Visible = xlSheetVisible)
        wsReport.Cells(r, 5).Value = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    Next ws

    wsReport.Range("A1:E1").Font.Bold = True
    wsReport.Columns("A:E").AutoFit

    ' --- rename the data tab, then keep writing to it ---
    wsData.Name = "Renamed " & stamp
    wsData.Range("D1").Value = "Written after the rename"
    wsData.Columns("D").AutoFit

    MsgBox "Listed " & (r - 1) & " worksheets. The data tab is now called " & _
        wsData.Name & ", and the variable still points at it.", _
        vbInformation, "Worksheet tour"
End Sub

Line by line

  • Set wsData = ThisWorkbook.Worksheets.Add โ€” Add hands back the new sheet, so you capture it in the same statement. Objects need Set.
  • Worksheets.Add(After:=wsData) โ€” a named argument decides where the tab lands. Without it, new sheets appear in front of the active one.
  • ws.Name is the tab; ws.CodeName the internal name; ws.Index the position from the left.
  • ws.Cells(ws.Rows.Count, 1).End(xlUp).Row โ€” from the bottom of column A, jump up to the last filled cell. ws.Rows.Count is qualified too: the sheet is asked how many rows it has.
  • ws.Visible = xlSheetVisible is a comparison here, not an assignment; it yields the True or False that lands in the cell.
  • wsData.Name = "Renamed " & stamp โ€” and the lines after it still write to the right sheet. The variable holds the sheet itself, not its name, so a rename cannot break it.

The code name never changes underneath you

In the Project Explorer you see entries like Sheet1 (Data). The bracketed half is the tab; the half in front is the code name, which you can type straight into your code as if it were a variable: Sheet1.Range("A1").Value = 10. Renaming the tab leaves it untouched, and F4 lets you set it to something meaningful such as shData. One limitation worth knowing: code names work only for sheets in the workbook holding the code.

The trap: error 9, subscript out of range

The most common run-time error in Excel VBA, and its message tells you nothing useful. It means the name you asked for is not in the collection โ€” usually an invisible trailing space in the tab name, or a colleague who renamed Data to Daten:

' Two of these three die with run-time error 9, subscript out of range:
Worksheets("Data ").Range("A1").Value = 1     ' trailing space in the tab name
Worksheets("data").Range("A1").Value = 1      ' this one is fine - names ignore case
Worksheets("Daten").Range("A1").Value = 1     ' someone renamed the tab last week

' Does the sheet exist? Ask before you use it:
Dim ws As Worksheet
On Error Resume Next
Set ws = ThisWorkbook.Worksheets("Data")
On Error GoTo 0

If ws Is Nothing Then
    MsgBox "There is no sheet called Data in this workbook.", vbExclamation
    Exit Sub
End If

Why that costs an hour

The macro dies on a line that looks perfect, and the tab in front of you seems to be called exactly what you typed. Two habits kill it for good: refer to important sheets by their code name, and where you must use a tab name, ask whether the sheet exists instead of hoping. The On Error Resume Next pattern above is the standard way to ask โ€” and the On Error GoTo 0 after it is not optional.

Set a Worksheet variable at the top of a procedure and use it everywhere below. Every later line gets shorter, renames stop mattering, and no stray Range("A1") can point at the wrong sheet.

How it goes on

The next lesson turns those habits into rules: why a bare Range is a guess, and the existence check written out properly. After that come adding, deleting and copying sheets without the confirmation pop-up, ThisWorkbook versus ActiveWorkbook, opening and closing other files safely, looping over sheets, and protection that still lets macros work.

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.

From Excel down to a cell: the object pathApplicationExcel itselfWorkbookThisWorkbookWorksheetWorksheets("Data")RangeRange("B2")Each arrow is one step through a collection:Workbooks, then Worksheets, then the cells of the sheet.ThisWorkbook.Worksheets("Data").Range("B2").Value
The object path from Excel to a single cell. Writing the full path removes every guess about which file and which sheet you mean.

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:

The data sheet built by the macro. The total is not written by the macro; it is what =SUM(B2:B9) returns.
RowRegion (A)Revenue (B)
2Region 11,200
3Region 22,400
4Region 33,600
5Region 44,800
6Region 56,000
7Region 67,200
8Region 78,400
9Region 89,600
Total43,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:

The report sheet. Code names are typical for a new workbook; yours may differ if sheets were added and deleted before.
Tab nameCode nameIndexVisibleLast used row
Data 09-41-07Sheet21TRUE9
Sheets 09-41-07Sheet32TRUE3
Sheet1Sheet13TRUE1

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.

Which reference survives which change?Tab renamedTab movedOther file activeOther tab activeRange("A1") aloneworksworksbreaksbreaksWorksheets("Data")breaksworksbreaksworksThisWorkbook.Worksheets(1)worksbreaksworksworksCode name shDataworksworksworksworksVariable ws, Set onceworksworksworksworksGreen: still hits the intended sheet. Peach: wrong sheet or run-time error.
Only the code name and a variable set once survive all four changes. The variable is safe for the rest of the run once 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. Without ThisWorkbook. 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 Worksheet variable is how you combine these. Find the sheet once with the safest lookup available, Set ws = shData or Set ws = ThisWorkbook.Worksheets("Data"), and use ws. 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

  1. Open the editor. Press Alt+F11 (on a Mac Developer โ†’ Visual Basic).
  2. Show the Project Explorer. Press Ctrl+R or choose View โ†’ Project Explorer. Each sheet is listed as code name (tab name), for example Sheet2 (Data 09-41-07).
  3. 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.
  4. Rename the code name. Type a meaningful name into (Name), such as shData, and press Enter. Code names must start with a letter and cannot contain spaces.
  5. Use it in code. In any standard module of the same workbook, shData.Range("A1").Value now refers to that sheet, whatever its tab is called. IntelliSense lists its properties when you type the dot.
  6. Ask the workbook questions. Press Ctrl+G to open the Immediate window, type ?ThisWorkbook.Worksheets.Count and press Enter. Try ?shData.Name and ?shData.Index as well.
  7. 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.
  8. Save as .xlsm. File โ†’ Save As โ†’ Excel Macro-Enabled Workbook, or the code and your code names are lost.
Declare your sheet variables at the top of each procedure and name them after their job, such as 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.

Worksheets and Workbooks in Excel VBA course: referencing sheets and files safely in macros
The Worksheets & Workbooks course: point your code at the right sheet and the right file, every single time.

Common mistakes and how to spot them

  • Unqualified ranges. Range and Cells without a sheet in front write to the active sheet. Spot it: search the module for lines that begin with Range( or Cells(; in a standard module, each one is a guess.
  • A half-qualified range. ws.Range(Cells(2, 1), Cells(9, 2)) qualifies Range but not the two Cells, which still point at the active sheet. Spot it: run-time error 1004 when another sheet is active. Write ws.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.
  • Sheets where you meant Worksheets. 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 .Range call.
  • Forgetting Set. ws = Worksheets("Data") without Set fails, because objects must be assigned with Set. Spot it: run-time error 91, object variable or With block variable not set.
  • Using the code name across workbooks. shData only works in the workbook that holds the code. Spot it: with Option Explicit on, 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

Keyboard shortcuts are for the VBA editor on Windows.
ItemExampleWhat it gives you
Worksheet by nameThisWorkbook.Worksheets("Data")The sheet with that tab name; error 9 if missing
Worksheet by positionThisWorkbook.Worksheets(1)The leftmost worksheet
Code nameshData.Range("A1")The sheet whatever its tab is called (own workbook only)
Worksheet variableDim ws As Worksheet โ€ฆ Set ws = shDataOne reference used on every later line
Add a sheetSet ws = ThisWorkbook.Worksheets.Add(After:=wsData)Creates the sheet and returns it
Tab name / code name / positionws.Name / ws.CodeName / ws.IndexThe three identities of a sheet
Last used rowws.Cells(ws.Rows.Count, 1).End(xlUp).RowLast filled row in column A
Loop over sheetsFor Each ws In ThisWorkbook.WorksheetsEvery worksheet in tab order
Is it there?If ws Is Nothing ThenTrue when a lookup found nothing
Project Explorer / PropertiesCtrl+R / F4See and change code names
Immediate windowCtrl+GAsk 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 Each loop 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.

  1. Referencing Sheets Safely
  2. Adding, Deleting and Copying Sheets
  3. ThisWorkbook vs ActiveWorkbook
  4. Opening, Saving and Closing Workbooks
  5. Looping Through Sheets
  6. Visibility, Protection and Housekeeping

Buy course โ€” $9.90 See the full course

Knowledge check

Your macro runs Worksheets("Data").Range("A1").Value = 1 and stops with run-time error 9, subscript out of range, although a tab named Data is right there. What is the most likely cause?

Continues in this course
  • Referencing Sheets Safely
  • Adding, Deleting and Copying Sheets
  • ThisWorkbook vs ActiveWorkbook
  • Opening, Saving and Closing Workbooks
  • Looping Through Sheets
  • Visibility, Protection and Housekeeping

Buy the course to unlock the remaining 6 lessons, the exam and the certificate.

Buy course โ€” $9.90