Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA Workbook Sheets: How to Work With Them

· 7 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

You work with workbook sheets in Excel VBA through the Worksheets and Sheets collections, referencing each sheet by name, by index number, or through the ActiveSheet and ThisWorkbook objects. The shortest working pattern is ThisWorkbook.Worksheets("Sheet1").Range("A1").Value = 100: it names the workbook, names the sheet, and then acts on a range. Everything else in this guide is about doing that reliably when sheet names change, when sheets are added or deleted, and when you need to loop through every sheet in the workbook.

What You'll Need

  • Excel for Windows or Excel for Mac with the Developer tab enabled. On Windows, enable it via File > Options > Customize Ribbon and tick Developer. On Mac, open Excel > Preferences > Ribbon & Toolbar and tick Developer.
  • A workbook saved as .xlsm (macro-enabled) if you want your code to survive closing and reopening. A plain .xlsx will strip the macros on save.
  • Basic familiarity with the VBA Editor: press Alt+F11 on Windows, or Fn+Option+F11 on many Macs, to open it. Insert > Module gives you a place to paste code.
  • At least one worksheet in the workbook. A workbook must always contain at least one visible sheet, which matters when you start deleting.

Step-by-Step

  1. Open the VBA Editor and add a module. Press Alt+F11 (Windows) or Fn+Option+F11 (Mac), then choose Insert > Module. Code placed in a standard module can be run from anywhere in the workbook. Menu labels can differ slightly by version and platform, but Insert > Module is present in all current versions.
  2. Reference the workbook explicitly. Start every macro with ThisWorkbook rather than relying on ActiveWorkbook. ThisWorkbook always means the workbook that contains the code, so the macro keeps working when the user switches to another open file. Write Dim ws As Worksheet and then Set ws = ThisWorkbook.Worksheets("Data").
  3. Choose the right collection. Worksheets contains only worksheet-type sheets. Sheets contains worksheets plus chart sheets and, in older macro workbooks, dialog sheets. If you only ever deal with normal grids, use Worksheets; it is the safer default and avoids type mismatches when a chart sheet is present.
  4. Reference by name or by index. By name: Worksheets("Data"). By position: Worksheets(1) for the leftmost sheet. Name references break if the tab is renamed; index references break if tabs are reordered. For code you will keep, names are usually clearer, but wrap them in an error check (step 6).
  5. Read and write cells through the sheet object. Once ws points at a sheet, use ws.Range("A1").Value or ws.Cells(1, 1).Value. Avoid unqualified references like Range("A1"), which act on whatever sheet happens to be active and produce wrong results when the user clicks another tab mid-run.
  6. Check that a sheet exists before using it. A missing sheet raises run-time error 9, subscript out of range. A short helper loop over ThisWorkbook.Worksheets comparing ws.Name to your target name lets you branch cleanly, create the sheet with Worksheets.Add, or exit with a message instead of crashing.
  7. Loop through every sheet. Use Dim ws As Worksheet then For Each ws In ThisWorkbook.Worksheets and act inside the loop. This is the standard way to clear cells, apply formatting, or collect totals across all tabs. If you need to skip hidden sheets, test ws.Visible = xlSheetVisible before acting.
  8. Add, copy, and delete sheets deliberately. Worksheets.Add inserts a new sheet; you can pass Before or After to control placement. ws.Copy After:=Worksheets(Worksheets.Count) duplicates a sheet, optionally to another workbook. ws.Delete removes it permanently, and Excel will refuse to delete the last visible sheet.
  9. Handle visibility and protection. Set ws.Visible = xlSheetHidden or xlSheetVeryHidden to hide a tab; very hidden sheets do not appear in the right-click Unhide list, which is useful for lookup tables. If a sheet is protected, unprotect it with the correct password before writing, then re-protect it in the same macro so the protection is not left off.
  10. Turn off screen updating for speed. For macros that touch many sheets, set Application.ScreenUpdating = False at the start and restore it to True at the end, including in any error handler. This alone often cuts run time noticeably on large loops.
  11. Save as .xlsm and test. Press F5 in the editor to run, then close and reopen the file to confirm the macro persists. If you saved as .xlsx, the code is gone and you will need to re-add it.

Common Mistakes

  • Using ActiveSheet when you meant a specific sheet. The active sheet changes whenever a user clicks a tab or another macro selects something, so results drift.
  • Confusing Worksheets with Sheets. A chart sheet in the workbook will cause a type mismatch if you declare a Worksheet variable and loop over Sheets.
  • Assuming sheet names are fixed. Renaming a tab, or a user doing so, breaks every hard-coded name reference. Use a constant or a lookup cell for the name so there is one place to change.
  • Deleting a sheet without warning. Delete does not prompt and cannot be undone with Ctrl+Z. Ask for confirmation or work on a copy.
  • Forgetting to restore ScreenUpdating after an error. The application stays in a sluggish state until Excel is restarted.
  • Leaving a sheet unprotected after a macro unprotects it. Always re-protect in the same routine.

Tips

  • Use the sheet's code name (visible in the Properties window, for example Sheet1) when you want a reference that survives tab renaming. Sheet1.Range("A1") keeps working even if the tab is renamed to "Data".
  • Store frequently used sheet names in a hidden configuration sheet or in named ranges, then read them into variables at the top of the macro.
  • Use xlSheetVeryHidden for reference tables so users cannot easily unhide them, but document it in the workbook so a future editor is not confused.
  • Write a small helper function that returns a worksheet or Nothing, then test for Nothing before acting. It keeps every macro short and predictable.
  • Keep one module for sheet helpers and separate modules for business logic; it makes debugging far easier than one giant module.

Troubleshooting

If you get run-time error 9, subscript out of range, the sheet name or index does not exist in that workbook. Check spelling, check you are pointing at ThisWorkbook and not another open file, and confirm the sheet has not been renamed or deleted. If you get error 1004, application-defined or object-defined error, the usual causes are a protected sheet, a misspelled range address, or writing to a cell outside the used range in a way the sheet does not allow. Unprotect the sheet or correct the range. If the macro runs but changes the wrong tab, you are almost certainly using unqualified Range or Cells calls; qualify them with the worksheet variable. If the macro is slow, add ScreenUpdating = False and avoid selecting or activating sheets inside loops. If the macro disappears after saving, the file was saved as .xlsx; use File > Save As and choose the macro-enabled format. If a delete fails, you are probably trying to remove the last visible sheet, which Excel blocks by design.

Frequently Asked Questions

What is the difference between Worksheets and Sheets in VBA?

Worksheets contains only worksheet objects. Sheets contains worksheets plus chart sheets and any legacy dialog sheets. Use Worksheets unless you specifically need to include chart sheets.

How do I refer to a sheet by its tab name in VBA?

Use ThisWorkbook.Worksheets("TabName"). If the tab name might change, use the sheet's code name instead, such as Sheet1, which stays the same through renames.

How do I loop through all sheets in a workbook?

Declare a worksheet variable and use For Each ws In ThisWorkbook.Worksheets. Inside the loop, ws refers to each sheet in turn, so you can read, write, or format without activating anything.

Can I create a new sheet with VBA?

Yes. Worksheets.Add inserts a sheet, and you can pass Before or After to control placement. Set the new sheet's Name property immediately so later code can find it by name.

Why does my macro fail when a sheet is protected?

Protected sheets block writes to locked cells. Unprotect the sheet with the correct password at the start of the macro, do the work, then re-protect it before the macro ends so the protection is not left off.

Does this work the same on Excel for Mac?

The object model is the same, so ThisWorkbook.Worksheets and the rest behave identically. The differences are in the editor shortcuts and some file dialog behaviour, not in how sheets are referenced.