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

ABCD
1Quarterly report
2
3Sales Q1
4
5

Sales

ABCD
1MonthSales
2January18,400.00
3February16,950.00
4March21,300.00
5Total56,650.00

How to refer to a sheet

Sub CopyTotal()
    Worksheets("Report").Range("B3").Value = Worksheets("Sales").Range("B5").Value
End Sub
CodeWhat 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.
ActiveSheetThe sheet currently in front. Range or Cells without a sheet always means this one.
Worksheets.CountThe number of sheets, so Worksheets(Worksheets.Count) is the last one.
ws.NameA 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

ABCD
1New monthMarch
2
3Settings for the monthly report go here.
4
5

January

ABCD
1Report January
2
3
4
5

February

ABCD
1Report 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

ABCD
1RegionSales
2
3
4
5

North

ABCD
1CustomerAmount
2Carter Ltd4200
3Hughes and Sons1850
4Brooks Supply3120
5Northgate Inc990
6Total10160

South

ABCD
1CustomerAmount
2Delgado Builders5400
3Rivera Print2275
4Shaw Optics1460
5Baker and Co3010
6Total12145

West

ABCD
1CustomerAmount
2Pacific Freight2980
3Morgan Dental4410
4Evans Legal760
5Collins Media1890
6Total10040

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.

Learn this next: format cells

Set bold, fill colour, number format and alignment from a macro, including only for rows that meet a condition.

Format cells with VBA

Write to us

Choose language

Select your preferred language