Excel VBA worksheets: working with several sheets
Hardly any workbook has just one sheet: data on one, the report on another, a sheet per month or region. Here you learn to point at a specific sheet, add and rename sheets, and loop through every sheet in the workbook.
In short: Worksheets("Report").Range("B3").Value = 5 writes to B3 on the "Report" sheet, whichever sheet happens to be active. A Range with no sheet in front always means the active sheet. Worksheets.Add creates a sheet, and For Each ws In Worksheets visits every sheet.
What you need to know: For Each and object variables with Set from Variables.
Try it right now
This exercise has two sheets; you see them as tabs below the grid. "Report" is active, and the total sits on the other sheet.
Task The workbook has two sheets, and "Report" is active right now. Write a macro CopyTotal that writes the total from Sales!B5 into cell B3 on the "Report" sheet. No .Select or .Activate: refer to the sheets directly with Worksheets("Name").
Report
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Quarterly report | |||
| 2 | ||||
| 3 | Sales Q1 | |||
| 4 | ||||
| 5 |
Sales
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Month | Sales | ||
| 2 | January | 18,400.00 | ||
| 3 | February | 16,950.00 | ||
| 4 | March | 21,300.00 | ||
| 5 | Total | 56,650.00 |
How to refer to a sheet
Sub CopyTotal()
Worksheets("Report").Range("B3").Value = Worksheets("Sales").Range("B5").Value
End Sub
| Code | What it means |
|---|---|
Worksheets("Sales") | The sheet with that name on its tab. Case does not matter, spaces do. |
Worksheets(1) | The first sheet from the left. If someone drags the tabs around, it is a different sheet. |
ActiveSheet | The sheet currently in front. Range or Cells without a sheet always means this one. |
Worksheets.Count | The number of sheets, so Worksheets(Worksheets.Count) is the last one. |
ws.Name | A sheet's name. You can read it and set it. |
An object variable saves you from repeating the sheet name on every line:
Dim dataWs As Worksheet
Set dataWs = Worksheets("Sales")
MsgBox dataWs.Range("B5").Value
Do not forget Set. A sheet is an object, not a number or a piece of text, and without Set the macro stops.
Add and rename a sheet
Worksheets.Add creates a new sheet. With no arguments, it goes in front of the active sheet. After:= or Before:= decide where it goes instead. The new sheet becomes the active sheet, and Add hands it back to you:
Dim ws As Worksheet
Set ws = Worksheets.Add(After:=Worksheets(Worksheets.Count))
ws.Name = "March"
A sheet name can be at most 31 characters long and cannot contain [ ] : * ? / \. Two sheets cannot share a name, not even with different capitalisation.
Task Each month has its own sheet. Write a macro AddMonth that adds a new sheet after the last one, names it after the month in Settings!B1 and writes "Report " plus the month name into its cell A1 (here: "Report March").
Settings
| A | B | C | D | |
|---|---|---|---|---|
| 1 | New month | March | ||
| 2 | ||||
| 3 | Settings for the monthly report go here. | |||
| 4 | ||||
| 5 |
January
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Report January | |||
| 2 | ||||
| 3 | ||||
| 4 | ||||
| 5 |
February
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Report February | |||
| 2 | ||||
| 3 | ||||
| 4 | ||||
| 5 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Loop through every sheet
Worksheets is a collection, much like a range is a collection of cells. So For Each works here too, and hands you each sheet once, left to right.
Dim ws As Worksheet
For Each ws In Worksheets
Debug.Print ws.Name, ws.Range("B6").Value
Next ws
A common job is a summary sheet that pulls together all the other sheets. An If keeps the summary itself out of the list.
Task Each region has its own sheet with the total in B6. Write a macro BuildSummary that uses For Each to go through all sheets and, for every sheet except "Summary", writes the sheet name to column A and the total from B6 to column B of the summary, starting in row 2.
Summary
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Region | Sales | ||
| 2 | ||||
| 3 | ||||
| 4 | ||||
| 5 |
North
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Customer | Amount | ||
| 2 | Carter Ltd | 4200 | ||
| 3 | Hughes and Sons | 1850 | ||
| 4 | Brooks Supply | 3120 | ||
| 5 | Northgate Inc | 990 | ||
| 6 | Total | 10160 |
South
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Customer | Amount | ||
| 2 | Delgado Builders | 5400 | ||
| 3 | Rivera Print | 2275 | ||
| 4 | Shaw Optics | 1460 | ||
| 5 | Baker and Co | 3010 | ||
| 6 | Total | 12145 |
West
| A | B | C | D | |
|---|---|---|---|---|
| 1 | Customer | Amount | ||
| 2 | Pacific Freight | 2980 | ||
| 3 | Morgan Dental | 4410 | ||
| 4 | Evans Legal | 760 | ||
| 5 | Collins Media | 1890 | ||
| 6 | Total | 10040 |
This exercise is part of Premium.
Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.
See Premium Already Premium? Log in
The first exercise in this lesson is free.
Delete a sheet
Application.DisplayAlerts = False
Worksheets("Old").Delete
Application.DisplayAlerts = True
When you delete a sheet, Excel normally asks you to confirm. Application.DisplayAlerts = False skips that question, so the sheet is gone without a prompt. Turn alerts back on afterwards. A deleted sheet cannot be brought back with Undo, so test on a copy. You cannot delete the last sheet of a workbook.
Common mistakes
Sheet name spelled wrong
If the code says Worksheets("Sale") but the tab says "Sales", VBA reports "Run-time error '9': Subscript out of range". You get the same message for Worksheets(7) in a workbook with fewer sheets. Check the name on the tab, including trailing spaces.
Reading the wrong sheet after Add
After Worksheets.Add, the new, empty sheet is active. Range("B1") with no sheet in front reads from there and gets nothing. Use that empty value as a name and the exercise reports "Run-time error '1004': Application-defined or object-defined error". Always put the source sheet in front, or read the value before you add the sheet.
Forgetting Set
ws = Worksheets.Add without Set leads to "Run-time error '91': Object variable or With block variable not set". Objects such as sheets and ranges are always assigned with Set.
Jumping around with Activate and Select
The macro recorder likes to write Sheets("Report").Select followed by Range("B3").Select. It works, but it is slow and breaks easily when a different sheet is in front at the start. With the sheet name in front of the range you need neither, which is why the exercises here do not accept .Select or .Activate.
In real Excel
In the VBA editor, the Project Explorer on the left lists every sheet, for example "Sheet1 (Sales)". The name in parentheses is the one on the tab, the one you use in Worksheets("Sales"). Your code still belongs in a module (Insert > Module), not in a sheet's code window. Save the workbook before you run a macro that adds or deletes sheets; there is no undo.
FAQ
What is the difference between Worksheets and Sheets?
Sheets holds every sheet in the workbook, chart sheets included. Worksheets holds only the worksheets. As long as there are no chart sheets, both give you the same thing; for tables, Worksheets is the more precise choice.
How do I refer to a sheet in another workbook?
Put the workbook in front: Workbooks("Sales.xlsx").Worksheets("January"). That workbook has to be open. ThisWorkbook is the workbook the code lives in. Opening files is not possible in the exercises here, because there is no file system.
How can I check whether a sheet already exists?
Loop through all sheets with For Each and compare ws.Name with the name you are looking for. Another way uses error handling from level 5: try to access the sheet and catch error 9.
Can I change the tab colour?
Yes, with ws.Tab.Color = RGB(255, 192, 0). How colours work with RGB is covered in the next lesson.