VBA course · Lesson 7 of 33

Workbooks and worksheets in VBA

Refer to workbooks and sheets safely: ThisWorkbook vs ActiveWorkbook, sheet names, index and code names, add, copy, rename, hide and delete sheets.

Beginner 16 min read

Up to now your macros worked on whatever sheet happened to be active. Real macros need to be precise: "write the total to the Summary sheet of this workbook", "copy the Template sheet", "hide the Settings sheet". This lesson explains the object hierarchy behind that precision and the everyday tasks of adding, copying, renaming, hiding and deleting sheets.

The object hierarchy

Excel organises everything as objects inside other objects, like folders inside folders:

LevelObjectExample
1Application (Excel itself)Application
2Workbook (an open file)Workbooks("Sales2026.xlsm")
3Worksheet (a tab).Worksheets("Invoices")
4Range (cells).Range("B4")

The full "address" of a cell is therefore Application.Workbooks("Sales2026.xlsm").Worksheets("Invoices").Range("B4"). You rarely write all of it, because VBA fills in missing levels with the active ones: a bare Range("B4") means "B4 on the active sheet of the active workbook". That shortcut is exactly what causes bugs when the user is looking at a different sheet or file. The cure is to say which workbook and sheet you mean, once, in a variable.

ThisWorkbook vs ActiveWorkbook

ReferenceMeansUse it for
ThisWorkbookThe workbook that contains the running codeYour own sheets: settings, templates, results
ActiveWorkbookThe workbook in the front window right nowActing on whatever file the user is looking at
Workbooks("Name.xlsx")An open workbook by file nameA specific other file

ThisWorkbook never changes while your code runs, which makes it the safest starting point. ActiveWorkbook changes whenever a workbook is opened or the user clicks another window. A macro stored in your Personal Macro Workbook (The macro recorder: record, read and clean up code) usually wants ActiveWorkbook, because ThisWorkbook would be PERSONAL.XLSB itself.

VBA
Option Explicit

Sub WhichWorkbook()
    MsgBox "Code lives in: " & ThisWorkbook.Name & vbNewLine & _
        "Active window: " & ActiveWorkbook.Name & vbNewLine & _
        "Full path: " & ThisWorkbook.FullName
End Sub
Show the difference

Name is the file name, Path the folder and FullName both together. A workbook that has never been saved has an empty Path and a name such as Book2.

Three ways to refer to a worksheet

By tab name

Worksheets("Invoices") uses the name on the tab. It is readable, but it breaks the moment someone renames the tab to "Invoices 2026": the macro stops with "Subscript out of range" (error 9).

By index

Worksheets(1) is the first sheet from the left, Worksheets(Worksheets.Count) the last. Indexes change when sheets are moved, added or deleted, so use them only in loops or for "the last sheet".

By code name

Every sheet also has a code name, shown in the editor's Project Explorer before the tab name, like Sheet1 (Invoices). Select the sheet there and change its (Name) in the Properties window to something meaningful, such as shInvoices. You can then use that name directly in code, without quotes:

VBA
Option Explicit

Sub StampInvoiceSheet()
    ' shInvoices is the code name set in the Properties window
    shInvoices.Range("H1").Value = "Printed " & Format(Date, "d mmm yyyy")
End Sub
Using a code name

Code names survive renaming of the tab and moving of the sheet, and IntelliSense lists them. Their only limit: they work for sheets in the workbook that contains the code, not for sheets in other files. For your own workbooks, code names are the most robust choice.

Tip. Worksheets contains only worksheets. Sheets contains worksheets and chart sheets. Use Worksheets unless you really work with chart sheets, so that a loop never meets an unexpected chart.

Use variables for workbooks and sheets

A good habit is to set workbook and sheet variables at the start of every macro (Variables and data types: Dim, Option Explicit and scope) and qualify every range with them:

VBA
Option Explicit

Sub BuildSummary()
    Dim wb As Workbook
    Dim wsData As Worksheet
    Dim wsSum As Worksheet

    Set wb = ThisWorkbook
    Set wsData = wb.Worksheets("Sales")
    Set wsSum = wb.Worksheets("Summary")

    wsSum.Range("A1").Value = "Total sales"
    wsSum.Range("B1").Value = Application.WorksheetFunction.Sum(wsData.Range("D2:D500"))
    wsSum.Range("A2").Value = "Orders"
    wsSum.Range("B2").Value = Application.WorksheetFunction.Count(wsData.Range("D2:D500"))
End Sub
Summarise one sheet onto another, never touching the active sheet

This macro works whichever sheet or workbook is active, because each range names its sheet. WorksheetFunction.Sum uses Excel's SUM from VBA; Using Excel worksheet functions in VBA covers that properly.

Activating sheets (and why you rarely need to)

wsSum.Activate brings a sheet to the front, and wb.Activate brings a workbook's window forward. You need this only when the user should see the sheet at the end of the macro. Writing to a sheet, reading from it, formatting it, copying it: none of that requires activating it first.

Watch out. A classic error: Worksheets("Summary").Range("A1").Select fails with error 1004 if Summary is not the active sheet, because you can only select cells on the active sheet. Avoid Select altogether, or activate the sheet first.

Adding sheets

Worksheets.Add creates a new sheet and returns it, so you can capture it in a variable:

VBA
Option Explicit

Sub AddMonthSheet()
    Dim ws As Worksheet
    With ThisWorkbook
        Set ws = .Worksheets.Add(After:=.Worksheets(.Worksheets.Count))
    End With
    ws.Name = "Dec 2026"
    ws.Range("A1").Value = "Sales for December 2026"
End Sub
Add a sheet at the end and name it

After:= (or Before:=) chooses the position; without it, the new sheet appears before the active sheet. .Worksheets(.Worksheets.Count) is the last sheet, so the new one goes to the end.

Sheet name rules

Excel refuses names longer than 31 characters, names that already exist in the workbook, the name "History", and the characters \ / ? * [ ] :. Assigning an invalid name stops the macro with error 1004. Dates are a common trap: Format(Date, "dd/mm/yyyy") contains slashes, so use Format(Date, "yyyy-mm-dd") instead.

Checking whether a sheet exists

Before adding a sheet you often need to know whether it is already there. VBA has no built-in function for that, so here is a small helper you can reuse in every project:

VBA
Option Explicit

Function SheetExists(sheetName As String, Optional wb As Workbook) As Boolean
    Dim ws As Worksheet
    If wb Is Nothing Then Set wb = ThisWorkbook
    For Each ws In wb.Worksheets
        If StrComp(ws.Name, sheetName, vbTextCompare) = 0 Then
            SheetExists = True
            Exit Function
        End If
    Next ws
    SheetExists = False
End Function

Sub AddSheetIfMissing()
    If SheetExists("Archive") Then
        MsgBox "Archive already exists."
    Else
        ThisWorkbook.Worksheets.Add(After:=ThisWorkbook.Worksheets(1)).Name = "Archive"
        MsgBox "Archive created."
    End If
End Sub
A reusable SheetExists function

For Each ws In wb.Worksheets visits every sheet in turn (For loops: For...Next and For Each), and StrComp with vbTextCompare compares names ignoring upper and lower case, just like Excel does for sheet names. Functions are explained in Functions and Subs: parameters, ByVal, ByRef and return values.

Copying and moving sheets

Copy and Move take the same Before:= or After:= arguments. Without either, Excel copies the sheet into a brand-new workbook, which is a quick way to export one sheet.

VBA
Option Explicit

Sub NewInvoiceFromTemplate()
    Dim wsNew As Worksheet

    With ThisWorkbook
        .Worksheets("Template").Copy After:=.Worksheets(.Worksheets.Count)
        ' The copy is now the active sheet, and also the last one
        Set wsNew = .Worksheets(.Worksheets.Count)
    End With

    wsNew.Name = "INV-0148"
    wsNew.Range("B4").Value = "INV-2026-0148"
    wsNew.Range("B5").Value = Date
End Sub
Create this month's invoice sheet from a template

Copy does not return the new sheet, which is why the code picks it up as the last sheet straight afterwards. The template sheet itself stays untouched.

Renaming, hiding and deleting

VBA
Option Explicit

Sub TidyWorkbook()
    With ThisWorkbook
        ' Rename
        .Worksheets("Sheet1").Name = "Inputs"

        ' Hide a sheet the user can unhide from the right-click menu
        .Worksheets("Lookups").Visible = xlSheetHidden

        ' Very hidden: only visible again through VBA or the Properties window
        .Worksheets("Settings").Visible = xlSheetVeryHidden

        ' Delete without the "are you sure?" prompt
        Application.DisplayAlerts = False
        .Worksheets("Old data").Delete
        Application.DisplayAlerts = True
    End With
End Sub
Rename, hide and delete
  • Visible has three values: xlSheetVisible, xlSheetHidden and xlSheetVeryHidden. A very hidden sheet does not appear in the Unhide dialog, which makes it a tidy place for settings, but it is not a security feature: anyone who opens the editor can make it visible again.
  • Delete normally asks for confirmation. Setting Application.DisplayAlerts = False answers the prompt automatically; always set it back to True straight afterwards.
  • A workbook must keep at least one visible sheet. Deleting or hiding the last one gives error 1004.
Watch out. A deleted sheet cannot be restored with Undo. Test delete macros on a copy of the workbook.

Looping through all sheets

Many tasks repeat for every sheet: protecting them, printing them, collecting totals. For Each makes this easy:

VBA
Option Explicit

Sub ListSheets()
    Dim ws As Worksheet
    Dim wsList As Worksheet
    Dim r As Long

    Set wsList = ThisWorkbook.Worksheets.Add(Before:=ThisWorkbook.Worksheets(1))
    wsList.Range("A1:C1").Value = Array("Sheet", "Used range", "Visible")
    r = 2

    For Each ws In ThisWorkbook.Worksheets
        If Not ws Is wsList Then
            wsList.Cells(r, 1).Value = ws.Name
            wsList.Cells(r, 2).Value = ws.UsedRange.Address
            wsList.Cells(r, 3).Value = (ws.Visible = xlSheetVisible)
            r = r + 1
        End If
    Next ws

    wsList.Columns("A:C").AutoFit
End Sub
List every sheet with its used range on a new sheet
ABC
1SheetUsed rangeVisible
2Inputs$A$1:$D$12TRUE
3Sales$A$1:$F$240TRUE
4Settings$A$1:$B$6FALSE

Example output for a workbook with three sheets

Array("Sheet", "Used range", "Visible") writes three headers in one go. ws Is wsList checks whether two object variables point to the same sheet, so the new list sheet skips itself.

Workbooks in brief

Opening, saving and closing files is covered fully in Files and folders: open, save, loop through files and write text files, but here are the basic commands:

VBA
Option Explicit

Sub ReadRatesFromOtherFile()
    Dim wbRates As Workbook
    Set wbRates = Workbooks.Open("C:\Excelversity\Rates.xlsx", ReadOnly:=True)

    ThisWorkbook.Worksheets("Inputs").Range("B2").Value = _
        wbRates.Worksheets(1).Range("B2").Value

    wbRates.Close SaveChanges:=False
End Sub
Open, use and close another workbook

Workbooks.Open returns the opened workbook, so you can capture it in a variable instead of relying on ActiveWorkbook. Close SaveChanges:=False closes it without saving or asking. On a Mac, paths use slashes, for example /Users/maria/Documents/Rates.xlsx, and files outside Excel's sandbox may trigger a one-time permission prompt.

Common mistakes

  • "Subscript out of range" (error 9): the sheet or workbook name does not exist. Check spelling, extra spaces, and whether the workbook name includes the extension (Workbooks("Rates.xlsx")).
  • Writing to the wrong sheet: unqualified Range or Cells refer to the active sheet. Qualify them.
  • Using ActiveWorkbook in a file-specific macro: if the user clicks another window while the macro runs or before it starts, the wrong file is changed. Use ThisWorkbook for your own file.
  • Forgetting to turn DisplayAlerts back on: Excel then silently overwrites files and deletes sheets without asking for the rest of the session.
  • Invalid sheet names with slashes or more than 31 characters.

Check yourself

1. Your macro must always write to the Settings sheet of the file that contains the code. Which reference is safest?

2. What happens to code that uses Worksheets("Invoices") after a user renames the tab to "Invoices 2026"?

3. Which Visible setting hides a sheet so that it does not appear in the Unhide dialog?

4. Why set Application.DisplayAlerts = False before deleting a sheet?

5. Which sheet name is invalid?