In this Article
- Sheets Vs. Worksheets
- Referencing Sheets
- ActiveSheet
- Sheet Name
- Sheet Index Number
- Sheet “Code Name”
- Referencing Sheets in Other Workbooks
- Activate vs. Select Sheet
- Activate a Sheet
- Select a Sheet
- Select Multiple Sheets
- Worksheet Variable
- Loop Through All Sheets in Workbook
- Worksheet Protection
- Workbook Protection
- Worksheet Protection
- Protect Worksheet
- Unprotect Worksheet
- Worksheet Visible Property
- Unhide Worksheet
- Hide Worksheet
- Very Hide Worksheet
- Worksheet-Level Events
- Worksheet Activate Event
- Worksheet Change Event
- Worksheet Cheat Sheet
- VBA Worksheets Cheatsheet
This is the ultimate guide to working with Excel Sheets / Worksheets in VBA.
At the bottom of this guide, we’ve created a cheat sheet of common commands for working with sheets.
Sheets Vs. Worksheets
There are two ways to reference Sheets using VBA. The first is with the Sheets object:
Sheets("Sheet1").Activate
The other is with the Worksheets object:
Worksheets("Sheet1").Activate
99% of the time, these two objects are identical. In fact, if you’ve searched online for VBA code examples, you’ve probably seen both objects used. Here is the difference:
The Sheets Collection contains Worksheets AND Chart Sheets.
So use Sheets if you want to include regular Worksheets AND Chart Sheets. Use Worksheets if you want to exclude Chart Sheets. For the rest of this guide we will use Sheets and Worksheets interchangeably.
Referencing Sheets
There are several different ways to reference Sheets:
- ActiveSheet
- Sheet Tab Name
- Sheet Index Number
- Sheet Code Name
ActiveSheet
The ActiveSheet is the Sheet that’s currently active. In other words, if you paused your code and looked at Excel, it’s the sheet that is visible. The below code example will display a MessageBox with the ActiveSheet name.
MsgBox ActiveSheet.Name
Sheet Name
You are probably most familiar with referencing Sheets by their Tab Name:
Sheets("TabName").Activate
This is the sheet name that’s visible to Excel users. Enter it into the sheets object, as a string of text, surrounded by quotations.
Sheet Index Number
The Sheet Index number is the sheet position in the workbook. 1 is the first sheet. 2 is the second sheet etc.:
Sheets(1).Activate
Sheet Index Number – Last Sheet in Workbook
To reference the last Sheet in the workbook, use Sheets.Count to get the last Index Number and activate that sheet:
Sheets(Sheets.Count).Activate
Sheet “Code Name”
The Sheet Code Name is it’s Object name in VBA:
CodeName.Activate
VBA Coding Made Easy
Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!
Learn More
Referencing Sheets in Other Workbooks
It’s also easy to reference Sheets in other Workbooks. To do so, you need to use the Workbooks Object:
Workbooks("VBA_Examples.xlsm").Worksheets("Sheet1").Activate
Important: The Workbook must be open before you can reference its Sheets.
Activate vs. Select Sheet
In another article we discuss everything about activating and selecting sheets. The short version is this:
When you Activate a Sheet it becomes the ActiveSheet. This is the sheet you would see if you looked at your Excel program. Only one sheet may be activate at a time.
Activate a Sheet
Sheets("Sheet1").Activate
When you select a Sheet, it also becomes the ActiveSheet. However, you can select multiple sheets at once. When multiple sheets are selected at once, the “top” sheet is the ActiveSheet. However, you can toggle the ActiveSheet within selected sheets.
VBA Programming | Code Generator does work for you!
Select a Sheet
Sheets("Sheet1").Select
Select Multiple Sheets
Use an array to select multiple sheets at once:
Worksheets(Array("Sheet2", "Sheet3")).Select
Worksheet Variable
Assigning a worksheet to an object variable allows you to reference the worksheet by it’s variable name. This can save a lot of typing and make your code easier to read. There are also many other reasons you might want to use variables.
To declare a worksheet variable:
Dim ws as worksheet
Assign a worksheet to a variable:
Set ws = Sheets("Sheet1")
Now you can reference the worksheet variable in your code:
ws.Activate
Loop Through All Sheets in Workbook
Worksheet variables are useful when you want to loop through all the worksheets in a workbook. The easiest way to do this is:
Dim ws as Worksheet
For Each ws in Worksheets
MsgBox ws.name
Next ws
This code will loop through all worksheets in the workbook, displaying each worksheet name in a message box. Looping through all the sheets in a workbook is very useful when locking / unlocking or hiding / unhiding multiple worksheets at once.
Worksheet Protection
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Workbook Protection
Workbook protection locks the workbook from structural changes like adding, deleting, moving, or hiding worksheets.
You can turn on workbook protection using VBA:
ActiveWorkbook.Protect Password:="Password"
or disable workbook protection:
ActiveWorkbook.UnProtect Password:="Password"
Note: You can also protect / unprotect without a password by omitting the Password argument:
ActiveWorkbook.Protect
Worksheet Protection
Worksheet-level protection prevents changes to individual worksheets.
Protect Worksheet
Worksheets("Sheet1").Protect "Password"
Unprotect Worksheet
Worksheets("Sheet1").Unprotect "Password"
There are a variety of options when protecting worksheets (allow formatting changes, allow user to insert rows, etc.) We recommend using the Macro Recorder to record your desired settings.
We discuss worksheet protection in more detail here.
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Worksheet Visible Property
You might already know that worksheets can be hidden:
There are actually three worksheet visibility settings: Visible, Hidden, and VeryHidden. Hidden sheets can be unhidden by any regular Excel user – by right-clicking in the worksheet tab area (shown above). VeryHidden sheets can only be unhidden with VBA code or from within the VBA Editor. Use the following code examples to hide / unhide worksheets:
Unhide Worksheet
Worksheets("Sheet1").Visible = xlSheetVisible
Hide Worksheet
Worksheets("Sheet1").visible = xlSheetHidden
Very Hide Worksheet
Worksheets("Sheet1").Visible = xlSheetVeryHidden
AutoMacro | Ultimate VBA Add-in | Click for Free Trial!
Worksheet-Level Events
Events are triggers that can cause “Event Procedures” to run. For example, you can cause code to run every time any cell on a worksheet is changed or when a worksheet is activated.
Worksheet event procedures must be placed in a worksheet module:
There are numerous worksheet events. To see a complete list, go to a worksheet module, select “Worksheet” from the first drop-down. Then selecting an event procedure from the second drop-down to insert it into the module.
Worksheet Activate Event
Worksheet activate events run each time the worksheet is opened.
Private Sub Worksheet_Activate()
Range("A1").Select
End Sub
This code will select cell A1 (resetting the view area to the top-left of the worksheet) each time the worksheet is opened.
Worksheet Change Event
Worksheet change events run whenever a cell value is changed on the worksheet. Read our tutorial about Worksheet Change Events for more information.
Worksheet Cheat Sheet
Below you will find a cheat sheet containing common code examples for working with sheets in VBA
VBA Worksheets Cheatsheet
VBA worksheets Cheatsheet
Description | Code Example |
---|---|
Referencing and Activating Sheets | |
Tab Name | Sheets(«Input»).Activate |
VBA Code Name | Sheet1.Activate |
Index Position | Sheets(1).Activate |
Select Sheet | |
Select Sheet | Sheets(«Input»).Select |
Set to Variable | Dim ws as Worksheet Set ws = ActiveSheet |
Name / Rename | ActiveSheet.Name = «NewName» |
Next Sheet | ActiveSheet.Next.Activate |
Loop Through all Sheets | Dim ws as Worksheet
For each ws in Worksheets |
Loop Through Selected Sheets | Dim ws As Worksheet
For Each ws In ActiveWindow.SelectedSheets |
Get ActiveSheet | MsgBox ActiveSheet.Name |
Add Sheet | Sheets.Add |
Add Sheet and Name | Sheets.Add.Name = «NewSheet» |
Add Sheet With Name From Cell | Sheets.Add.Name = range(«a3»).value |
Add Sheet After Another | Sheets.Add After:=Sheets(«Input») |
Add Sheet After and Name | Sheets.Add(After:=Sheets(«Input»)).Name = «NewSheet» |
Add Sheet Before and Name | Sheets.Add(Before:=Sheets(«Input»)).Name = «NewSheet» |
Add Sheet to End of Workbook | Sheets.Add After:=Sheets(Sheets.Count) |
Add Sheet to Beginning of Workbook | Sheets.Add(Before:=Sheets(1)).Name = «FirstSheet» |
Add Sheet to Variable | Dim ws As Worksheet Set ws = Sheets.Add |
Copy Worksheets | |
Move Sheet to End of Workbook | Sheets(«Sheet1»).Move After:=Sheets(Sheets.Count) |
To New Workbook | Sheets(«Sheet1»).Copy |
Selected Sheets To New Workbook | ActiveWindow.SelectedSheets.Copy |
Before Another Sheet | Sheets(«Sheet1»).Copy Before:=Sheets(«Sheet2») |
Before First Sheet | Sheets(«Sheet1»).Copy Before:=Sheets(1) |
After Last Sheet | Sheets(«Sheet1»).Copy After:=Sheets(Sheets.Count) |
Copy and Name | Sheets(«Sheet1»).Copy After:=Sheets(Sheets.Count) ActiveSheet.Name = «LastSheet» |
Copy and Name From Cell Value | Sheets(«Sheet1»).Copy After:=Sheets(Sheets.Count) ActiveSheet.Name = Range(«A1»).Value |
To Another Workbook | Sheets(«Sheet1»).Copy Before:=Workbooks(«Example.xlsm»).Sheets(1) |
Hide / Unhide Sheets | |
Hide Sheet | Sheets(«Sheet1»).visible = False or Sheets(«Sheet1»).visible = xlSheetHidden |
Unhide Sheet | Sheets(«Sheet1»).Visible = True or Sheets(«Sheet1»).Visible = xlSheetVisible |
Very Hide Sheet | Sheets(Sheet1).Visible = xlSheetVeryHidden |
Delete or Clear Sheets | |
Delete Sheet | Sheets(«Sheet1»).Delete |
Delete Sheet (Error Handling) | On Error Resume Next Sheets(«Sheet1»).Delete On Error GoTo 0 |
Delete Sheet (No Prompt) | Application.DisplayAlerts = False Sheets(«Sheet1»).Delete Application.DisplayAlerts = True |
Clear Sheet | Sheets(«Sheet1»).Cells.Clear |
Clear Sheet Contents Only | Sheets(«Sheet1»).Cells.ClearContents |
Clear Sheet UsedRange | Sheets(«Sheet1»).UsedRange.Clear |
Protect or Unprotect Sheets | |
Unprotect (No Password) | Sheets(«Sheet1»).Unprotect |
Unprotect (Password) | Sheets(«Sheet1»).Unprotect «Password» |
Protect (No Password) | Sheets(«Sheet1»).Protect |
Protect (Password) | Sheets(«Sheet1»).Protect «Password» |
Protect but Allow VBA Access | Sheets(«Sheet1»).Protect UserInterfaceOnly:=True |
Unprotect All Sheets | Dim ws As Worksheet
For Each ws In Worksheets |
Home / VBA / VBA Objects / VBA Worksheet Object -Working with Excel Worksheet in VBA
In VBA, the worksheet object represents a single worksheet that is a part of the workbook’s worksheets (or sheets) collection. Using the worksheet object, you can refer to the worksheet in a VBA code, and refer to a worksheet you can also get access to the properties, methods, and events related to it.
Here’s a small snapshot of where a worksheet stands in the Excel object hierarchy.
Application ➪ Workbook ➪ Worksheets ➪ Worksheet
In this tutorial, we will learn about using and referring to a worksheet in Excel using a VBA code.
Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook
Sheets Vs. Worksheets
First thing first. This is important to understand the difference between a worksheet and a sheet. In Excel, you have types of sheets that you can insert into a workbook, and a worksheet is one of those types. As you can see in the below snapshot when you insert a new sheet Excel asks you to select the sheet type.
Here’s the point to understand: When you use the word “Sheets” you are referring to all the sheets (Worksheets, Macro Sheets, and Chart Sheets), but when you use the word “Worksheet” you are referring only to the worksheets (see also).
Accessing a Worksheet (Sheet) using VBA
VBA gives you different ways to access a worksheet from a workbook, and ahead, we will see different ways to do that.
1. Refer to a Sheet using the Name
Every sheet has its name to identify it, and you can use it to refer to that sheet as well. Let’s say you want to refer to the “Sheet1”, the code would be:
Sheets(“Sheet1”)
Worksheets(“Sheet1”)
Both above codes refer to the “Sheet1”.
2. Refer to Sheet using Number
You can also use a sheet’s number to refer to it. Let’s if a sheet is at the fifth position in the workbook then you can use this number to refer to it.
Sheets (5)
Worksheets (5)
Now here above two lines of code work in two different ways. The first line refers to the 5th sheet, and the second line refers to the 5th worksheet in the workbook.
3. Refer to the ActiveSheet
If a sheet is already active, then you can refer to it, using the keyword “Activesheet” instead of its name.
ActiveSheet
If you want to perform an activity in the ActiveSheet, you can use the “Activesheet” object, but if you skip using it, VBA will still perform the activity in the active sheet.
Read: Select a Range using VBA
4. Refer to a Sheet using Code Window Name
Each sheet has its code window, and there’s a name to that code window. Usually, a user can change the sheet name from the tab, but the name that you have in the code window can’t be changed unless you do it from the properties.
Open the Visual Basic Editor from the Developer Tab, and in the properties section, you can see the name of the sheet that you have selected.
And you can also change this name from the properties section.
Now you can refer to it by using the code window name.
mySheet
5. Refer to More than One Sheet
You can also refer to more than one sheet in one go using a single line of code. For this, you can use an array, just like the following code.
Sheets(Array("Sheet1", "Sheet2"))
This code refers to “Sheet1” and “Sheet2”, but, there’s one thing that you need to understand when you refer to more than one sheet, there are a few methods and properties that you can’t use.
6. Refer to Sheet in a Different Workbook
A worksheet or a sheet is a part of the worksheets collection in a workbook, and if you want to refer to a specific sheet other than the active workbook, then you need to refer to that workbook first.
Workbooks("Book1").Sheets("Sheet1")
To run this code, you need to have “Book1” open.
Properties, Methods, and Events Related to a Sheet or a Worksheet
In VBA, each Excel object has some properties, methods, and events that you can use, and in the same way, you can access the properties and methods that come with it. Once you specify a worksheet, type a dot (.), and you’ll get the list.
In this list, all the icons where you can see a hand are properties, and where you have green brick are methods.
Property Example
Let’s say you want to change the color of the worksheet’s tab, in this case, you can use the TAB property of the worksheet.
mySheet.Tab.ThemeColor = xlThemeColorAccent2
In the above line of code, you have the tab property and further theme color property to change the tab color of the worksheet.
Method Example
In the same way, you can use the methods that come with worksheets. One of the most common methods is the “Select” method that you can use to select a sheet.
mySheet.Select
The moment you run this code, it selects the “mySheet” from the active workbook.
Event Example
Some events are associated with a worksheet. For example, when you activate a sheet, that’s an event, and in the same way, when you change something within the sheet. See the following code where you have code to run when an event (change in the worksheet) happens.
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Range("A1").Value = Range("A1").Value + 1
End Sub
This code enters a value in the cell A1 of the sheet every time you make a change in the worksheet.
Declaring a Worksheet Object
You can also declare a variable as a worksheet, making it easy to use that worksheet in a VBA code. First, use the DIM keyword, and then the name of the variable. After that, specify the object type as a worksheet.
More on VBA Worksheets
Activate a Sheet | Add a New Sheet | Copy a Sheet | Rename a Sheet | Hide a Sheet | Delete Sheet | Protect Sheet | Clear a Sheet | Check IF Sheet Exists | Loop Through Each Sheet in the Workbook | Count Sheets
- VBA Tutorial
“The visionary starts with a clean sheet of paper, and re-imagines the world” – Malcolm Gladwell
This post provides a complete guide to using the Excel VBA Worksheet in Excel VBA. If you want to know how to do something quickly then check out the quick guide to the VBA Worksheet below.
If you are new to VBA then this post is a great place to start. I like to break things down into simple terms and explain them in plain English without the jargon.
You can read through the post from start to finish as it is written in a logical order. If you prefer, you can use the table of contents below and go directly to the topic of your choice.
A Quick Guide to the VBA Worksheet
The following table gives a quick run down to the different worksheet methods.
Note: I use Worksheets in the table below without specifying the workbook i.e.Worksheets rather than ThisWorkbook.Worksheets, wk.Worksheets etc. This is to make the examples clear and easy to read. You should always specify the workbook when using Worksheets. Otherwise the active workbook will be used by default.
Task | How to |
---|---|
Access worksheet by name | Worksheets(«Sheet1») |
Access worksheet by position from left | Worksheets(2) Worksheets(4) |
Access the left most worksheet | Worksheets(1) |
Access the right most worksheet | Worksheets(Worksheets.Count) |
Access using worksheet code name(current workbook only) | see Code Name section below |
Access using worksheet code name(other workbook) | see Code Name section below |
Access the active worksheet | ActiveSheet |
Declare worksheet variable | Dim sh As Worksheet |
Assign worksheet variable | Set sh = Worksheets(«Sheet1») |
Add worksheet | Worksheets.Add |
Add worksheet and assign to variable | Set sh =Worksheets.Add |
Add worksheet to first position(left) | Worksheets.Add Before:=Worksheets(1) |
Add worksheet to last position(right) | Worksheets.Add after:=Worksheets(Worksheets.Count) |
Add multiple worksheets | Worksheets.Add Count:=3 |
Activate Worksheet | sh.Activate |
Copy Worksheet | sh.Copy |
Copy after a worksheet | sh1.Copy After:=Sh2 |
Copy before a worksheet | sh1.Copy Before:=Sh2 |
Delete Worksheet | sh.Delete |
Delete Worksheet without warning | Application.DisplayAlerts = False sh.Delete Application.DisplayAlerts = True |
Change worksheet name | sh.Name = «Data» |
Show/hide worksheet | sh.Visible = xlSheetHidden sh.Visible = xlSheetVisible |
Loop through all worksheets(For) | Dim i As Long For i = 1 To Worksheets.Count Debug.Print Worksheets(i).Name Next i |
Loop through all worksheets(For Each) | Dim sh As Worksheet For Each sh In Worksheets Debug.Print sh.Name Next |
Introduction
The three most important elements of VBA are the Workbook, the Worksheet and Cells. Of all the code your write, 90% will involve one or all of them.
The most common use of the worksheet in VBA is for accessing its cells. You may use it to protect, hide, add, move or copy a worksheet. However, you will mainly use it to perform some action on one or more cells on the worksheet.
Using Worksheets is more straightforward than using workbooks. With workbooks you may need to open them, find which folder they are in, check if they are in use and so on. With a worksheet, it either exists in the workbook or it doesn’t.
Accessing the Worksheet
In VBA, each workbook has a collection of worksheets. There is an entry in this collection for each worksheet in the workbook. This collection is simply called Worksheets and is used in a very similar way to the Workbooks collection. To get access to a worksheet all you have to do is supply the name.
The code below writes “Hello World” in Cell A1 of Sheet1, Sheet2 and Sheet3 of the current workbook.
' https://excelmacromastery.com/ Public Sub WriteToCell1() ' Write To cell A1 In Sheet1,Sheet2 And Sheet3 ThisWorkbook.Worksheets("Sheet1").Range("A1") = "Hello World" ThisWorkbook.Worksheets("Sheet2").Range("A1") = "Hello World" ThisWorkbook.Worksheets("Sheet3").Range("A1") = "Hello World" End Sub
The Worksheets collection is always belong to a workbook. If we don’t specify the workbook then the active workbook is used by default.
' https://excelmacromastery.com/ Public Sub WriteToCell1() ' Worksheets refers to the worksheets in the active workbook Worksheets("Sheet1").Range("A1") = "Hello World" Worksheets("Sheet2").Range("A1") = "Hello World" Worksheets("Sheet3").Range("A1") = "Hello World" End Sub
Hide Worksheet
The following examples show how to hide and unhide a worksheet
ThisWorkbook.Worksheets("Sheet1").Visible = xlSheetHidden ThisWorkbook.Worksheets("Sheet1").Visible = xlSheetVisible
If you want to prevent a user accessing the worksheet, you can make it “very hidden”. This means it can only be made visible by the code.
' Hide from user access ThisWorkbook.Worksheets("Sheet1").Visible = xlVeryHidden ' This is the only way to make a xlVeryHidden sheet visible ThisWorkbook.Worksheets("Sheet1").Visible = xlSheetVisible
Protect Worksheet
Another example of using the worksheet is when you want to protect it
ThisWorkbook.Worksheets("Sheet1").Protect Password:="MyPass" ThisWorkbook.Worksheets("Sheet1").Unprotect Password:="MyPass"
Subscript Out of Range
When you use Worksheets you may get the error:
Run-time Error 9 Subscript out of Range
This means you tried to access a worksheet that doesn’t exist. This may happen for the following reasons
- The worksheet name given to Worksheets is spelled incorrectly.
- The name of the worksheet has changed.
- The worksheet was deleted.
- The index was to large e.g. You used Worksheets(5) but there are only four worksheets
- The wrong workbook is being used e.g. Workbooks(“book1.xlsx”).Worksheets(“Sheet1”) instead of Workbooks(“book3.xlsx”).Worksheets(“Sheet1”).
If you still have issues then use one of the loops from Loop Through The Worksheets section to print the names of all worksheets the collection.
Using the Index to Access the Worksheet
So far we have been using the sheet name to access the sheet. The index refers to the sheet tab position in the workbook. As the position can easily be changed by the user it is not a good idea to use this.
The following code shows examples of using the index
' https://excelmacromastery.com/ ' Using this code is a bad idea as ' sheet positions changes all the time Public Sub UseSheetIdx() With ThisWorkbook ' Left most sheet Debug.Print .Worksheets(1).Name ' The third sheet from the left Debug.Print .Worksheets(3).Name ' Right most sheet Debug.Print .Worksheets(.Worksheets.Count).Name End With End Sub
In the example above, I used Debug.Print to print to the Immediate Window. To view this window select View->Immediate Window(or Ctrl G)
Using the Code Name of a Worksheet
The best method of accessing the worksheet is using the code name. Each worksheet has a sheet name and a code name. The sheet name is the name that appears in the worksheet tab in Excel.
Changing the sheet name does not change the code name meaning that referencing a sheet by the code name is a good idea.
If you look in the VBE property window you will see both names. In the image you can see that the code name is the name outside the parenthesis and the sheet name is in the parenthesis.
You can change both the sheet name and the code name in the property window of the sheet(see image below).
If your code refers to the code name then the user can change the name of the sheet and it will not affect your code. In the example below we reference the worksheet directly using the code name.
' https://excelmacromastery.com/ Public Sub UseCodeName2() ' Using the code name of the worksheet Debug.Print CodeName.Name CodeName.Range("A1") = 45 CodeName.Visible = True End Sub
This makes the code easy to read and safe from the user changing the sheet name.
Code Name in other Workbooks
There is one drawback to using the code name. It can only refer to worksheets in the workbook that contains the code i.e. ThisWorkbook.
However, we can use a simple function to find the code name of a worksheet in a different workbook.
' https://excelmacromastery.com/ Public Sub UseSheet() Dim sh As Worksheet ' Get the worksheet using the codename Set sh = SheetFromCodeName("CodeName", ThisWorkbook) ' Use the worksheet Debug.Print sh.Name End Sub ' This function gets the worksheet object from the Code Name Public Function SheetFromCodeName(Name As String, bk As Workbook) As Worksheet Dim sh As Worksheet For Each sh In bk.Worksheets If sh.CodeName = Name Then Set SheetFromCodeName = sh Exit For End If Next sh End Function
Using the above code means that if the user changes the name of the worksheet then your code will not be affected.
There is another way of getting the sheet name of an external workbook using the code name. You can use the VBProject element of that Workbook.
You can see how to do this in the example below. I have included this for completeness only and I would recommend using the method in the previous example rather than this one.
' https://excelmacromastery.com/ Public Function SheetFromCodeName2(codeName As String _ , bk As Workbook) As Worksheet ' Get the sheet name from the CodeName using the VBProject Dim sheetName As String sheetName = bk.VBProject.VBComponents(codeName).Properties("Name") ' Use the sheet name to get the worksheet object Set SheetFromCodeName2 = bk.Worksheets(sheetName) End Function
Code Name Summary
The following is a quick summary of using the Code Name
- The code name of the worksheet can be used directly in the code e.g. Sheet1.Range
- The code name will still work if the worksheet name is changed.
- The code name can only be used for worksheets in the same workbook as the code.
- Anywhere you see ThisWorkbook.Worksheets(“sheetname”) you can replace it with the code name of the worksheet.
- You can use the SheetFromCodeName function from above to get the code name of worksheets in other workbooks.
The Active Sheet
The ActiveSheet object refers to the worksheet that is currently active. You should only use ActiveSheet if you have a specific need to refer to the worksheet that is active.
Otherwise you should specify the worksheet you are using.
If you use a worksheet method like Range and don’t mention the worksheet, it will use the active worksheet by default.
' Write to Cell A1 in the active sheet ActiveSheet.Range("A1") = 99 ' Active sheet is the default if no sheet used Range("A1") = 99
Declaring a Worksheet Object
Declaring a worksheet object is useful for making your code neater and easier to read.
The next example shows code for updating ranges of cells. The first Sub does not declare a worksheet object. The second sub declares a worksheet object and the code is therefore much clearer.
' https://excelmacromastery.com/ Public Sub SetRangeVals() Debug.Print ThisWorkbook.Worksheets("Sheet1").Name ThisWorkbook.Worksheets("Sheet1").Range("A1") = 6 ThisWorkbook.Worksheets("Sheet1").Range("B2:B9").Font.Italic = True ThisWorkbook.Worksheets("Sheet1").Range("B2:B9").Interior.Color = rgbRed End Sub
' https://excelmacromastery.com/ Public Sub SetRangeValsObj() Dim sht As Worksheet Set sht = ThisWorkbook.Worksheets("Sheet1") sht.Range("A1") = 6 sht.Range("B2:B9").Font.Italic = True sht.Range("B2:B9").Interior.Color = rgbRed End Sub
You could also use the With keyword with the worksheet object as the next example shows.
' https://excelmacromastery.com/ Public Sub SetRangeValsObjWith() Dim sht As Worksheet Set sht = ThisWorkbook.Worksheets("Sheet1") With sht .Range("A1") = 6 .Range("B2:B9").Font.Italic = True .Range("B2:B9").Interior.Color = rgbRed End With End Sub
Accessing the Worksheet in a Nutshell
With all the different ways to access a worksheet, you may be feeling overwhelmed or confused. So in this section, I am going to break it down into simple terms
1. If you want to use whichever worksheet is currently active then use ActiveSheet.
ActiveSheet.Range("A1") = 55
2. If the worksheet is in the same workbook as the code then use the Code Name.
Sheet1.Range("A1") = 55
3. If the worksheet is in a different workbook then first get workbook and then get the worksheet.
' Get workbook Dim wk As Workbook Set wk = Workbooks.Open("C:DocsAccounts.xlsx", ReadOnly:=True) ' Then get worksheet Dim sh As Worksheet Set sh = wk.Worksheets("Sheet1")
If you want to protect against the user changing the sheet name then use the SheetFromCodeName function from the Code Name section.
' Get workbook Dim wk As Workbook Set wk = Workbooks.Open("C:DocsAccounts.xlsx", ReadOnly:=True) ' Then get worksheet Dim sh As Worksheet Set sh = SheetFromCodeName("sheetcodename",wk)
Add Worksheet
The examples in this section show you how to add a new worksheet to a workbook. If you do not supply any arguments to the Add function then the new worksheet will be placed before the active worksheet.
When you add a Worksheet, it is created with a default name like “Sheet4”. If you want to change the name then you can easily do this using the Name property.
The following example adds a new worksheet and changes the name to “Accounts”. If a worksheet with the name “Accounts” already exists then you will get an error.
' https://excelmacromastery.com/ Public Sub AddSheet() Dim sht As Worksheet ' Adds new sheet before active sheet Set sht = ThisWorkbook.Worksheets.Add ' Set the name of sheet sht.Name = "Accounts" ' Adds 3 new sheets before active sheet ThisWorkbook.Worksheets.Add Count:=3 End Sub
In the previous example, you are adding worksheets in relation to the active worksheet. You can also specify the exact position to place the worksheet.
To do this you need to specify which worksheet the new one should be inserted before or after. The following code shows you how to do this.
' https://excelmacromastery.com/ Public Sub AddSheetFirstLast() Dim shtNew As Worksheet Dim shtFirst As Worksheet, shtLast As Worksheet With ThisWorkbook Set shtFirst = .Worksheets(1) Set shtLast = .Worksheets(.Worksheets.Count) ' Adds new sheet to first position in the workbook Set shtNew = Worksheets.Add(Before:=shtFirst) shtNew.Name = "FirstSheet" ' Adds new sheet to last position in the workbook Set shtNew = Worksheets.Add(After:=shtLast) shtNew.Name = "LastSheet" End With End Sub
Delete Worksheet
To delete a worksheet you simply call the Delete member.
Dim sh As Worksheet Set sh = ThisWorkbook.Worksheets("Sheet12") sh.Delete
Excel will display a warning message when you delete a worksheet. If you want to hide this message you can use the code below
Application.DisplayAlerts = False sh.Delete Application.DisplayAlerts = True
There are two issues to watch out for when it comes to deleting worksheets.
If you try to access the worksheet after deleting it you will get the “Subscript out of Range” error we saw in the Accessing the Worksheet section.
Dim sh As Worksheet Set sh = ThisWorkbook.Worksheets("Sheet2") sh.Delete ' This line will give 'Subscript out of Range' as "Sheet2" does not exist Set sh = ThisWorkbook.Worksheets("Sheet2")
The second issue is when you assign a worksheet variable. If you try to use this variable after the worksheet is deleted then you will get an Automation error like this
Run-Time error -21147221080 (800401a8′) Automation Error
If you are using the Code Name of the worksheet rather than a variable, then this will cause Excel to crash rather than give the automation error.
The following example shows how an automation errors occurs
sh.Delete ' This line will give Automation error Debug.Assert sh.Name
If you assign the Worksheet variable to a valid worksheet it will work fine
sh.Delete ' Assign sh to another worksheet Set sh = Worksheets("sheet3") ' This line will work fine Debug.Assert sh.Name
Loop Through the Worksheets
The Worksheets member of Workbooks is a collection of worksheets belonging to a workbook. You can go through each sheet in the worksheets collection using a For Each Loop or a For Loop.
The following example uses a For Each loop.
' https://excelmacromastery.com/ Public Sub LoopForEach() ' Writes "Hello World" into cell A1 for each worksheet Dim sht As Worksheet For Each sht In ThisWorkbook.Worksheets sht.Range("A1") = "Hello World" Next sht End Sub
The next example uses the standard For loop
' https://excelmacromastery.com/ Public Sub LoopFor() ' Writes "Hello World" into cell A1 for each worksheet Dim i As Long For i = 1 To ThisWorkbook.Worksheets.Count ThisWorkbook.Worksheets(i).Range("A1") = "Hello World" Next sht End Sub
You have seen how to access all open workbooks and how to access all worksheets in ThisWorkbook. Lets take it one step further. Lets access all worksheets in all open workbooks.
Note: If you use code like this to write to worksheets then back everything up first as you could end up writing the incorrect data to all the sheets.
' https://excelmacromastery.com/ Public Sub AllSheetNames() ' Prints the workbook and sheet names for ' all sheets in open workbooks Dim wrk As Workbook Dim sht As Worksheet For Each wrk In Workbooks For Each sht In wrk.Worksheets Debug.Print wrk.Name + ":" + sht.Name Next sht Next wrk End Sub
Using the Sheets Collection
The workbook has another collection similar to Worksheets called Sheets. This causes confusion at times among users. To explain this first you need to know about a sheet type that is a chart.
It is possible in Excel to have a sheet that is a chart. To do this
- Create a chart on any sheet.
- Right click on the chart and select Move.
- Select the first option which is “New Sheet” and click Ok.
Now you have a workbook with sheets of type worksheet and one of type chart.
- The Worksheets collection refers to all worksheets in a workbook. It does not include sheets of type chart.
- The Sheets collection refers to all sheets belonging to a workbook including sheets of type chart.
There are two code examples below. The first goes through all the Sheets in a workbook and prints the name of the sheet and type of sheet it is. The second example does the same with the Worksheets collection.
To try out these examples you should add a Chart sheet to your workbook first so you will see the difference.
' https://excelmacromastery.com/ Public Sub CollSheets() Dim sht As Variant ' Display the name and type of each sheet For Each sht In ThisWorkbook.Sheets Debug.Print sht.Name & " is type " & TypeName(sht) Next sht End Sub Public Sub CollWorkSheets() Dim sht As Variant ' Display the name and type of each sheet For Each sht In ThisWorkbook.Worksheets Debug.Print sht.Name & " is type " & TypeName(sht) Next sht End Sub
If do not have chart sheets then using the Sheets collection is the same as using the Worksheets collection.
Conclusion
This concludes the post on the VBA Worksheet. I hope you found it useful.
The three most important elements of Excel VBA are Workbooks, Worksheets and Ranges and Cells. These elements will be used in almost everything you do. Understanding them will make you life much easier and make learning VBA much simpler.
What’s Next?
Free VBA Tutorial If you are new to VBA or you want to sharpen your existing VBA skills then why not try out the The Ultimate VBA Tutorial.
Related Training: Get full access to the Excel VBA training webinars and all the tutorials.
(NOTE: Planning to build or manage a VBA Application? Learn how to build 10 Excel VBA applications from scratch.)
Introduction
This is a tutorial about writing code in Excel spreadsheets using Visual Basic for Applications (VBA).
Excel is one of Microsoft’s most popular products. In 2016, the CEO of Microsoft said «Think about a world without Excel. That’s just impossible for me.” Well, maybe the world can’t think without Excel.
- In 1996, there were over 30 million users of Microsoft Excel (source).
- Today, there are an estimated 750 million users of Microsoft Excel. That’s a little more than the population of Europe and 25x more users than there were in 1996.
We’re one big happy family!
In this tutorial, you’ll learn about VBA and how to write code in an Excel spreadsheet using Visual Basic.
Prerequisites
You don’t need any prior programming experience to understand this tutorial. However, you will need:
- Basic to intermediate familiarity with Microsoft Excel
- If you want to follow along with the VBA examples in this article, you will need access to Microsoft Excel, preferably the latest version (2019) but Excel 2016 and Excel 2013 will work just fine.
- A willingness to try new things
Learning Objectives
Over the course of this article, you will learn:
- What VBA is
- Why you would use VBA
- How to get set up in Excel to write VBA
- How to solve some real-world problems with VBA
Important Concepts
Here are some important concepts that you should be familiar with to fully understand this tutorial.
Objects: Excel is object-oriented, which means everything is an object — the Excel window, the workbook, a sheet, a chart, a cell. VBA allows users to manipulate and perform actions with objects in Excel.
If you don’t have any experience with object-oriented programming and this is a brand new concept, take a second to let that sink in!
Procedures: a procedure is a chunk of VBA code, written in the Visual Basic Editor, that accomplishes a task. Sometimes, this is also referred to as a macro (more on macros below). There are two types of procedures:
- Subroutines: a group of VBA statements that performs one or more actions
- Functions: a group of VBA statements that performs one or more actions and returns one or more values
Note: you can have functions operating inside of subroutines. You’ll see later.
Macros: If you’ve spent any time learning more advanced Excel functionality, you’ve probably encountered the concept of a “macro.” Excel users can record macros, consisting of user commands/keystrokes/clicks, and play them back at lightning speed to accomplish repetitive tasks. Recorded macros generate VBA code, which you can then examine. It’s actually quite fun to record a simple macro and then look at the VBA code.
Please keep in mind that sometimes it may be easier and faster to record a macro rather than hand-code a VBA procedure.
For example, maybe you work in project management. Once a week, you have to turn a raw exported report from your project management system into a beautifully formatted, clean report for leadership. You need to format the names of the over-budget projects in bold red text. You could record the formatting changes as a macro and run that whenever you need to make the change.
What is VBA?
Visual Basic for Applications is a programming language developed by Microsoft. Each software program in the Microsoft Office suite is bundled with the VBA language at no extra cost. VBA allows Microsoft Office users to create small programs that operate within Microsoft Office software programs.
Think of VBA like a pizza oven within a restaurant. Excel is the restaurant. The kitchen comes with standard commercial appliances, like large refrigerators, stoves, and regular ole’ ovens — those are all of Excel’s standard features.
But what if you want to make wood-fired pizza? Can’t do that in a standard commercial baking oven. VBA is the pizza oven.
Yum.
Why use VBA in Excel?
Because wood-fired pizza is the best!
But seriously.
A lot of people spend a lot of time in Excel as a part of their jobs. Time in Excel moves differently, too. Depending on the circumstances, 10 minutes in Excel can feel like eternity if you’re not able to do what you need, or 10 hours can go by very quickly if everything is going great. Which is when you should ask yourself, why on earth am I spending 10 hours in Excel?
Sometimes, those days are inevitable. But if you’re spending 8-10 hours everyday in Excel doing repetitive tasks, repeating a lot of the same processes, trying to clean up after other users of the file, or even updating other files after changes are made to the Excel file, a VBA procedure just might be the solution for you.
You should consider using VBA if you need to:
- Automate repetitive tasks
- Create easy ways for users to interact with your spreadsheets
- Manipulate large amounts of data
Getting Set Up to Write VBA in Excel
Developer Tab
To write VBA, you’ll need to add the Developer tab to the ribbon, so you’ll see the ribbon like this.
To add the Developer tab to the ribbon:
- On the File tab, go to Options > Customize Ribbon.
- Under Customize the Ribbon and under Main Tabs, select the Developer check box.
After you show the tab, the Developer tab stays visible, unless you clear the check box or have to reinstall Excel. For more information, see Microsoft help documentation.
VBA Editor
Navigate to the Developer Tab, and click the Visual Basic button. A new window will pop up — this is the Visual Basic Editor. For the purposes of this tutorial, you just need to be familiar with the Project Explorer pane and the Property Properties pane.
Excel VBA Examples
First, let’s create a file for us to play around in.
- Open a new Excel file
- Save it as a macro-enabled workbook (. xlsm)
- Select the Developer tab
- Open the VBA Editor
Let’s rock and roll with some easy examples to get you writing code in a spreadsheet using Visual Basic.
Example #1: Display a Message when Users Open the Excel Workbook
In the VBA Editor, select Insert -> New Module
Write this code in the Module window (don’t paste!):
Sub Auto_Open()
MsgBox («Welcome to the XYZ Workbook.»)
End Sub
Save, close the workbook, and reopen the workbook. This dialog should display.
Ta da!
How is it doing that?
Depending on your familiarity with programming, you may have some guesses. It’s not particularly complex, but there’s quite a lot going on:
- Sub (short for “Subroutine): remember from the beginning, “a group of VBA statements that performs one or more actions.”
- Auto_Open: this is the specific subroutine. It automatically runs your code when the Excel file opens — this is the event that triggers the procedure. Auto_Open will only run when the workbook is opened manually; it will not run if the workbook is opened via code from another workbook (Workbook_Open will do that, learn more about the difference between the two).
- By default, a subroutine’s access is public. This means any other module can use this subroutine. All examples in this tutorial will be public subroutines. If needed, you can declare subroutines as private. This may be needed in some situations. Learn more about subroutine access modifiers.
- msgBox: this is a function — a group of VBA statements that performs one or more actions and returns a value. The returned value is the message “Welcome to the XYZ Workbook.”
In short, this is a simple subroutine that contains a function.
When could I use this?
Maybe you have a very important file that is accessed infrequently (say, once a quarter), but automatically updated daily by another VBA procedure. When it is accessed, it’s by many people in multiple departments, all across the company.
- Problem: Most of the time when users access the file, they are confused about the purpose of this file (why it exists), how it is updated so often, who maintains it, and how they should interact with it. New hires always have tons of questions, and you have to field these questions over and over and over again.
- Solution: create a user message that contains a concise answer to each of these frequently answered questions.
Real World Examples
- Use the MsgBox function to display a message when there is any event: user closes an Excel workbook, user prints, a new sheet is added to the workbook, etc.
- Use the MsgBox function to display a message when a user needs to fulfill a condition before closing an Excel workbook
- Use the InputBox function to get information from the user
Example #2: Allow User to Execute another Procedure
In the VBA Editor, select Insert -> New Module
Write this code in the Module window (don’t paste!):
Sub UserReportQuery()
Dim UserInput As Long
Dim Answer As Integer
UserInput = vbYesNo
Answer = MsgBox(«Process the XYZ Report?», UserInput)
If Answer = vbYes Then ProcessReport
End Sub
Sub ProcessReport()
MsgBox («Thanks for processing the XYZ Report.»)
End Sub
Save and navigate back to the Developer tab of Excel and select the “Button” option. Click on a cell and assign the UserReportQuery macro to the button.
Now click the button. This message should display:
Click “yes” or hit Enter.
Once again, tada!
Please note that the secondary subroutine, ProcessReport, could be anything. I’ll demonstrate more possibilities in example #3. But first…
How is it doing that?
This example builds on the previous example and has quite a few new elements. Let’s go over the new stuff:
- Dim UserInput As Long: Dim is short for “dimension” and allows you to declare variable names. In this case, UserInput is the variable name and Long is the data type. In plain English, this line means “Here’s a variable called “UserInput”, and it’s a Long variable type.”
- Dim Answer As Integer: declares another variable called “Answer,” with a data type of Integer. Learn more about data types here.
- UserInput = vbYesNo: assigns a value to the variable. In this case, vbYesNo, which displays Yes and No buttons. There are many button types, learn more here.
- Answer = MsgBox(“Process the XYZ Report?”, UserInput): assigns the value of the variable Answer to be a MsgBox function and the UserInput variable. Yes, a variable within a variable.
- If Answer = vbYes Then ProcessReport: this is an “If statement,” a conditional statement, which allows us to say if x is true, then do y. In this case, if the user has selected “Yes,” then execute the ProcessReport subroutine.
When could I use this?
This could be used in many, many ways. The value and versatility of this functionality is more so defined by what the secondary subroutine does.
For example, maybe you have a file that is used to generate 3 different weekly reports. These reports are formatted in dramatically different ways.
- Problem: Each time one of these reports needs to be generated, a user opens the file and changes formatting and charts; so on and so forth. This file is being edited extensively at least 3 times per week, and it takes at least 30 minutes each time it’s edited.
- Solution: create 1 button per report type, which automatically reformats the necessary components of the reports and generates the necessary charts.
Real World Examples
- Create a dialog box for user to automatically populate certain information across multiple sheets
- Use the InputBox function to get information from the user, which is then populated across multiple sheets
Example #3: Add Numbers to a Range with a For-Next Loop
For loops are very useful if you need to perform repetitive tasks on a specific range of values — arrays or cell ranges. In plain English, a loop says “for each x, do y.”
In the VBA Editor, select Insert -> New Module
Write this code in the Module window (don’t paste!):
Sub LoopExample()
Dim X As Integer
For X = 1 To 100
Range(«A» & X).Value = X
Next X
End Sub
Save and navigate back to the Developer tab of Excel and select the Macros button. Run the LoopExample macro.
This should happen:
Etc, until the 100th row.
How is it doing that?
- Dim X As Integer: declares the variable X as a data type of Integer.
- For X = 1 To 100: this is the start of the For loop. Simply put, it tells the loop to keep repeating until X = 100. X is the counter. The loop will keep executing until X = 100, execute one last time, and then stop.
- Range(«A» & X).Value = X: this declares the range of the loop and what to put in that range. Since X = 1 initially, the first cell will be A1, at which point the loop will put X into that cell.
- Next X: this tells the loop to run again
When could I use this?
The For-Next loop is one of the most powerful functionalities of VBA; there are numerous potential use cases. This is a more complex example that would require multiple layers of logic, but it communicates the world of possibilities in For-Next loops.
Maybe you have a list of all products sold at your bakery in Column A, the type of product in Column B (cakes, donuts, or muffins), the cost of ingredients in Column C, and the market average cost of each product type in another sheet.
You need to figure out what should be the retail price of each product. You’re thinking it should be the cost of ingredients plus 20%, but also 1.2% under market average if possible. A For-Next loop would allow you to do this type of calculation.
Real World Examples
- Use a loop with a nested if statement to add specific values to a separate array only if they meet certain conditions
- Perform mathematical calculations on each value in a range, e.g. calculate additional charges and add them to the value
- Loop through each character in a string and extract all numbers
- Randomly select a number of values from an array
Conclusion
Now that we’ve talked about pizza and muffins and oh-yeah, how to write VBA code in Excel spreadsheets, let’s do a learning check. See if you can answer these questions.
- What is VBA?
- How do I get set up to start using VBA in Excel?
- Why and when would you use VBA?
- What are some problems I could solve with VBA?
If you have a fair idea of how to you could answer these questions, then this was successful.
Whether you’re an occasional user or a power user, I hope this tutorial provided useful information about what can be accomplished with just a bit of code in your Excel spreadsheets.
Happy coding!
Learning Resources
- Excel VBA Programming for Dummies, John Walkenbach
- Get Started with VBA, Microsoft Documentation
- Learning VBA in Excel, Lynda
A bit about me
I’m Chloe Tucker, an artist and developer in Portland, Oregon. As a former educator, I’m continuously searching for the intersection of learning and teaching, or technology and art. Reach out to me on Twitter @_chloetucker and check out my website at chloe.dev.
Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started
In this VBA Tutorial, you learn how to refer to, and work with, sheets and worksheets in macros. This includes:
- How to refer to all sheets in a workbook.
- How to refer to all worksheets in a workbook.
- How to refer to the active sheet.
- How to refer to a sheet by its index number.
- How to refer to a worksheet by its index number.
- How to refer to a sheet by its name.
- How to refer to a worksheet by its name.
- How to refer to a sheet by its code name.
- How to refer to several sheets.
- How to refer to several worksheets.
- How to loop through all sheets in a workbook with the For Each… Next loop.
- How to loop through all worksheets in a workbook with the For Each… Next loop.
- How to loop through all sheets in a workbook with the For… Next loop.
- How to loop through all worksheets in a workbook with the For… Next loop.
- How to loop through all sheets in a workbook in reverse order.
- How to loop through all worksheets in a workbook in reverse order.
This VBA Tutorial is accompanied by an Excel workbook containing the macros I use in the examples below. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.
Alternatively, you can access all the files that accompany my Tutorials here.
Related Excel VBA and Macro Tutorials
The following VBA and Macro Tutorials may help you better understand and implement the contents below:
- General VBA constructs and structures:
- Learn the basics of working with macros here.
- Learn about basic VBA terms and constructs here.
- Learn how to enable or disable macros here.
- Learn how to work with the Visual Basic Editor here.
- Learn how to create Sub procedures here.
- Learn how to create object references here.
- Learn how to work with object properties here.
- Learn how to work with object methods here.
- Learn how to declare and work with variables here.
- Learn about VBA data types here.
- Learn how to work with arrays here.
- Learn how to work with loops here.
- Practical VBA applications and macro examples:
- Learn how to delete sheets and worksheets here.
You can find additional VBA and Macro Tutorials in the Archives.
#1: Refer to all sheets in workbook
VBA code to refer to all sheets in workbook
To refer to all sheets in a workbook with VBA, use an object reference with the following structure:
Workbook.Sheets
Process to refer to all sheets in workbook
To refer to all sheets in a workbook with VBA, follow these steps:
- Identify the workbook containing the sheets (Workbook).
- Refer to the Sheets collection representing all sheets in Workbook (Sheets).
VBA statement explanation
Item: Workbook
Workbook object representing the Excel workbook containing the sheets you refer to.
You can usually work with one of the following properties to refer to this Workbook object:
- Application.ActiveWorkbook.
- Application.ThisWorkbook.
- Application.Workbooks.
Item: Sheets
The Workbook.Sheets property returns a Sheets collection representing all sheets in Workbook. The Sheets collection can, generally, contain both:
- Chart objects, where each Chart object represents an individual chart sheet; or
- Worksheet objects, where each Worksheet object represents an individual worksheet.
Macro example to refer to all sheets in workbook
The following macro example displays a message box (MsgBox) with the number of sheets (Sheets.Count) in the workbook where the macro is stored (ThisWorkbook).
Sub referToSheetsCollection() 'source: https://powerspreadsheets.com/ 'displays a message box with the number of sheets in this workbook 'for further information: https://powerspreadsheets.com/excel-vba-sheets-worksheets/ 'display message box with number of sheets in this workbook MsgBox ThisWorkbook.Sheets.Count End Sub
Effects of executing macro example to refer to all sheets in workbook
The following GIF illustrates the results of executing the macro example. The workbook where the macro is stored contains 5 worksheets (Sheet1 through Sheet5) and 5 chart sheets (Chart1 through Chart5). Therefore, Excel displays a message box with the number 10.
#2: Refer to all worksheets in workbook
VBA code to refer to all worksheets in workbook
To refer to all worksheets in a workbook with VBA, use an object reference with the following structure:
Workbook.Worksheets
Process to refer to all worksheets in workbook
To refer to all worksheets in a workbook with VBA, follow these steps:
- Identify the workbook containing the worksheets (Workbook).
- Refer to the Sheets collection representing all worksheets in Workbook (Worksheets).
VBA statement explanation
Item: Workbook
Workbook object representing the Excel workbook containing the worksheets you refer to.
You can usually work with one of the following properties to refer to this Workbook object:
- Application.ActiveWorkbook.
- Application.ThisWorkbook.
- Application.Workbooks.
Item: Worksheets
The Workbook.Worksheets property returns a Sheets collection representing all worksheets in Workbook.
Macro example to refer to all worksheets in workbook
The following macro example displays a message box (MsgBox) with the number of worksheets (Worksheets.Count) in the workbook where the macro is stored (ThisWorkbook).
Sub referToWorksheetsCollection() 'source: https://powerspreadsheets.com/ 'displays a message box with the number of worksheets in this workbook 'for further information: https://powerspreadsheets.com/excel-vba-sheets-worksheets/ 'display message box with number of worksheets in this workbook MsgBox ThisWorkbook.Worksheets.Count End Sub
Effects of executing macro example to refer to all worksheets in workbook
The following GIF illustrates the results of executing the macro example. The workbook where the macro is stored contains 5 worksheets (Sheet1 through Sheet5). Therefore, Excel displays a message box with the number 5.
#3: Refer to active sheet
VBA code to refer to active sheet
To refer to the active sheet with VBA, use an object reference with the following structure:
Workbook.ActiveSheet
Process to refer to active sheet
To refer to the active sheet with VBA, follow these steps:
- Identify the workbook containing the sheet (Workbook). If you don’t identify Workbook, VBA works with the active workbook.
- Refer to the active sheet in Workbook (ActiveSheet).
VBA statement explanation
Item: Workbook
Workbook object representing the Excel workbook containing the active sheet you refer to.
You can usually work with one of the following properties to refer to this Workbook object:
- Application.ActiveWorkbook.
- Application.ThisWorkbook.
- Application.Workbooks.
If you don’t specify Workbook when referring to the active sheet with ActiveSheet, VBA works with the active workbook (the workbook on top).
Item: ActiveSheet
The ActiveSheet returns an object representing the active sheet (the sheet on top) in Workbook, as follows:
- If you specify Workbook, ActiveSheet returns an object representing the active sheet in Workbook.
- If you don’t specify Workbook, ActiveSheet returns an object representing the active sheet in the active workbook (the workbook on top).
Macro example to refer to active sheet
The following macro example displays a message box (MsgBox) with the name (Name) of the active sheet in the active workbook (ActiveSheet).
Sub referToActiveSheet() 'source: https://powerspreadsheets.com/ 'displays a message box with the name of the active sheet 'for further information: https://powerspreadsheets.com/excel-vba-sheets-worksheets/ 'display message box with name of active sheet MsgBox ActiveSheet.Name End Sub
Effects of executing macro example to refer to active sheet
The following GIF illustrates the results of executing the macro example. As expected, Excel displays a message box with the name of the active sheet (Sheet1).
#4: Refer to sheet by index number
VBA code to refer to sheet by index number
To refer to a sheet by its index number with VBA, use an object reference with the following structure:
Workbook.Sheets(SheetIndexNumber)
Process to refer to sheet by index number
To refer to a sheet by its index number with VBA, follow these steps:
- Identify the workbook containing the sheet (Workbook).
- Identify the sheet by its index number (Sheets(SheetIndexNumber)).
VBA statement explanation
Item: Workbook
Workbook object representing the Excel workbook containing the sheet you refer to.
You can usually work with one of the following properties to refer to this Workbook object:
- Application.ActiveWorkbook.
- Application.ThisWorkbook.
- Application.Workbooks.
Item: Sheets(SheetIndexNumber)
The Workbook.Sheets property returns a Sheets collection representing all sheets in Workbook. The Sheets collection can, generally, contain both:
- Chart objects, where each Chart object represents an individual chart sheet; or
- Worksheet objects, where each Worksheet object represents an individual worksheet.
SheetIndexNumber is the index number of the sheet you refer to. This index number represents the position of the sheet in the tab bar of Workbook, from left to right. For these purposes, the count usually includes:
- Hidden sheets; and
- Both chart sheets and worksheets.
Therefore, Sheets(SheetIndexNumber) usually returns an individual Chart or Worksheet object representing the chart sheet or worksheet whose index number is SheetIndexNumber.
Macro example to refer to sheet by index number
The following macro example activates (Activate) the fifth sheet (Sheets(5)) in the workbook where the macro is stored (ThisWorkbook).
Sub referToSheetIndex() 'source: https://powerspreadsheets.com/ 'activates the fifth sheet in this workbook 'for further information: https://powerspreadsheets.com/excel-vba-sheets-worksheets/ 'activate fifth sheet in this workbook ThisWorkbook.Sheets(5).Activate End Sub
Effects of executing macro example to refer to sheet by index number
The following GIF illustrates the results of executing the macro example.
When the macro is executed, the active sheet is Sheet1. As expected, Excel activates the fifth sheet (Chart1).
#5: Refer to worksheet by index number
VBA code to refer to worksheet by index number
To refer to a worksheet by its index number with VBA, use an object reference with the following structure:
Workbook.Worksheets(WorksheetIndexNumber)
Process to refer to worksheet by index number
To refer to a worksheet by its index number with VBA, follow these steps:
- Identify the workbook containing the worksheet (Workbook).
- Identify the worksheet by its index number (Worksheets(WorksheetIndexNumber)).
VBA statement explanation
Item: Workbook
Workbook object representing the Excel workbook containing the worksheet you refer to.
You can usually work with one of the following properties to refer to this Workbook object:
- Application.ActiveWorkbook.
- Application.ThisWorkbook.
- Application.Workbooks.
Item: Worksheets(WorksheetIndexNumber)
The Workbook.Worksheets property returns a Sheets collection representing all worksheets in Workbook.
WorksheetIndexNumber is the index number of the worksheet you refer to. This index number represents the position of the worksheet in the tab bar of Workbook, from left to right. For these purposes, the count usually:
- Includes hidden worksheets; but
- Doesn’t include chart sheets.
Therefore, Worksheets(WorksheetIndexNumber) returns an individual Worksheet object representing the worksheet whose index number is WorksheetIndexNumber.
Macro example to refer to worksheet by index number
The following macro example activates (Activate) the first worksheet (Worksheets(1)) in the workbook where the macro is stored (ThisWorkbook).
Sub referToWorksheetIndex() 'source: https://powerspreadsheets.com/ 'activates the first worksheet in this workbook 'for further information: https://powerspreadsheets.com/excel-vba-sheets-worksheets/ 'activate first worksheet in this workbook ThisWorkbook.Worksheets(1).Activate End Sub
Effects of executing macro example to refer to worksheet by index number
The following GIF illustrates the results of executing the macro example.
When the macro is executed, the active sheet is Sheet5. As expected, Excel activates the first worksheet (Sheet1).
#6: Refer to sheet by name
VBA code to refer to sheet by name
To refer to a sheet by its name with VBA, use an object reference with the following structure:
Workbook.Sheets("SheetName")
Process to refer to sheet by name
To refer to a sheet by its name with VBA, follow these steps:
- Identify the workbook containing the sheet (Workbook).
- Identify the sheet by its name (Sheets(“SheetName”)).
VBA statement explanation
Item: Workbook
Workbook object representing the Excel workbook containing the sheet you refer to.
You can usually work with one of the following properties to refer to this Workbook object:
- Application.ActiveWorkbook.
- Application.ThisWorkbook.
- Application.Workbooks.
Item: Sheets(“SheetName”)
The Workbook.Sheets property returns a Sheets collection representing all sheets in Workbook. The Sheets collection can, generally, contain both:
- Chart objects, where each Chart object represents an individual chart sheet; or
- Worksheet objects, where each Worksheet object represents an individual worksheet.
“SheetName” is a string representing the name of the sheet you refer to, as displayed in the sheet’s tab. If you explicitly declare a variable to represent “SheetName”, you can usually declare it as of the String data type.
Therefore, Sheets(“SheetName”) usually returns an individual Chart or Worksheet object representing the chart sheet or worksheet whose name is SheetName.
Macro example to refer to sheet by name
The following macro example activates (Activate) the sheet named “Chart1” (Sheets(“Chart1”)) in the workbook where the macro is stored (ThisWorkbook).
Sub referToSheetName() 'source: https://powerspreadsheets.com/ 'activates the sheet named "Chart1" in this workbook 'for further information: https://powerspreadsheets.com/excel-vba-sheets-worksheets/ 'activate Chart1 in this workbook ThisWorkbook.Sheets("Chart1").Activate End Sub
Effects of executing macro example to refer to sheet by name
The following GIF illustrates the results of executing the macro example.
When the macro is executed, the active sheet is Sheet1. As expected, Excel activates Chart1.
#7: Refer to worksheet by name
VBA code to refer to worksheet by name
To refer to a worksheet by its name with VBA, use an object reference with the following structure:
Workbook.Worksheets("WorksheetName")
Process to refer to worksheet by name
To refer to a worksheet by its name with VBA, follow these steps:
- Identify the workbook containing the worksheet (Workbook).
- Identify the worksheet by its name (Worksheets(“WorksheetName”)).
VBA statement explanation
Item: Workbook
Workbook object representing the Excel workbook containing the worksheet you refer to.
You can usually work with one of the following properties to refer to this Workbook object:
- Application.ActiveWorkbook.
- Application.ThisWorkbook.
- Application.Workbooks.
Item: Worksheets(“WorksheetName”)
The Workbook.Worksheets property returns a Sheets collection representing all worksheets in Workbook.
“WorksheetName” is a string representing the name of the worksheet you refer to, as displayed in the worksheet’s tab. If you explicitly declare a variable to represent “WorksheetName”, you can usually declare it as of the String data type.
Therefore, Worksheets(“WorksheetName”) returns an individual Worksheet object representing the worksheet whose name is WorksheetName.
Macro example to refer to worksheet by name
The following macro example activates (Activate) the worksheet named “Sheet1” (Worksheets(“Sheet1”)) in the workbook where the macro is stored (ThisWorkbook).
Sub referToWorksheetName() 'source: https://powerspreadsheets.com/ 'activates the worksheet named "Sheet1" in this workbook 'for further information: https://powerspreadsheets.com/excel-vba-sheets-worksheets/ 'activate Sheet1 in this workbook ThisWorkbook.Worksheets("Sheet1").Activate End Sub
Effects of executing macro example to refer to worksheet by name
The following GIF illustrates the results of executing the macro example.
When the macro is executed, the active sheet is Chart1. As expected, Excel activates Sheet1.
#8: Refer to sheet by code name
VBA code to refer to sheet by code name
To refer to a sheet by its code name with VBA, use the sheet’s code name:
SheetCodeName
Process to refer to sheet by code name
To refer to a sheet by its code name with VBA, use the sheet’s code name.
VBA statement explanation
Item: SheetCodeName
SheetCodeName is the code name of the sheet you refer to.
You can use a sheet’s code name instead of an object reference (such as the ones I explain in other sections of this VBA Tutorial) returning the Chart or Sheet object you refer to.
Macro example to refer to sheet by code name
The following macro example activates (Activate) the worksheet whose code name is Sheet1 (Sheet1).
Sub referToSheetCodeName() 'source: https://powerspreadsheets.com/ 'activates Sheet1 in this workbook 'for further information: https://powerspreadsheets.com/excel-vba-sheets-worksheets/ 'activate Sheet1 in this workbook Sheet1.Activate End Sub
Effects of executing macro example to refer to sheet by code name
The following GIF illustrates the results of executing the macro example.
When the macro is executed, the active sheet is Sheet5. As expected, Excel activates Sheet1 (both the name and code name are Sheet1).
#9: Refer to several sheets
VBA code to refer to several sheets
To refer to several sheets with VBA, use an object reference with the following structure:
Workbook.Sheets(Array(SheetList))
Process to refer to several sheets
To refer to several sheets with VBA, follow these steps:
- Identify the workbook containing the sheets (Workbook).
- Obtain an array with the index numbers or names of the sheets you refer to (Array(SheetList)).
- Identify the sheets (Sheets(Array(SheetList))).
VBA statement explanation
Item: Workbook
Workbook object representing the Excel workbook containing the sheets you refer to.
You can usually work with one of the following properties to refer to this Workbook object:
- Application.ActiveWorkbook.
- Application.ThisWorkbook.
- Application.Workbooks.
Item: Sheets(Array(SheetList))
The Workbook.Sheets property returns a Sheets collection representing all sheets in Workbook. The Sheets collection can, generally, contain both:
- Chart objects, where each Chart object represents an individual chart sheet; or
- Worksheet objects, where each Worksheet object represents an individual worksheet.
The Array function (Array(SheetList)) returns a Variant containing an array with the index numbers or names of the sheets you refer to.
SheetList is the argument list of the Array function, which contains a comma-delimited list of the values you assign to each of the elements in the array returned by Array. When referring to several sheets, you can usually identify the specific objects in the Sheets collection you work with using the appropriate index number or sheet name, as follows:
- The index number represents the position of a sheet in the tab bar of Workbook, from left to right. For these purposes, the count usually includes:
- Hidden sheets; and
- Both chart sheets and worksheets.
- The sheet name is that displayed in the sheet’s tab.
Therefore, Sheets(Array(SheetList)) represents the chart sheets or worksheets you specify in SheetList.
Macro example to refer to several sheets
The following macro example moves (Move) the first sheet, the sheet named “Sheet3” and the sheet named “Chart1” (Sheets(Array(1, “Sheet3”, “Chart1”))) in the workbook where the macro is stored (ThisWorkbook) to the end of the workbook (After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count)).
Sub referToSeveralSheets() 'source: https://powerspreadsheets.com/ 'moves several sheets to end of this workbook 'for further information: https://powerspreadsheets.com/excel-vba-sheets-worksheets/ 'move the first sheet, "Sheet3" and "Chart1" to end of this workbook ThisWorkbook.Sheets(Array(1, "Sheet3", "Chart1")).Move After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count) End Sub
Effects of executing macro example to refer to several sheets
The following GIF illustrates the results of executing the macro example. As expected, Sheet1 (the first sheet), Sheet3 and Chart1 are moved to the end of the workbook.
#10: Refer to several worksheets
VBA code to refer to several worksheets
To refer to several worksheets with VBA, use an object reference with the following structure:
Workbook.Worksheets(Array(WorksheetList))
Process to refer to several worksheets
To refer to several worksheets with VBA, follow these steps:
- Identify the workbook containing the worksheets (Workbook).
- Obtain an array with the index numbers or names of the worksheets you refer to (Array(WorksheetList)).
- Identify the worksheets (Sheets(Array(WorksheetList))).
VBA statement explanation
Item: Workbook
Workbook object representing the Excel workbook containing the worksheets you refer to.
You can usually work with one of the following properties to refer to this Workbook object:
- Application.ActiveWorkbook.
- Application.ThisWorkbook.
- Application.Workbooks.
Item: Worksheets(Array(WorksheetList))
The Workbook.Worksheets property returns a Sheets collection representing all worksheets in Workbook.
The Array function (Array(WorksheetList)) returns a Variant containing an array with the index numbers or names of the worksheets you refer to.
WorksheetList is the argument list of the Array function, which contains a comma-delimited list of the values you assign to each of the elements in the array returned by Array. When referring to several worksheets, you can usually identify the specific objects in the Worksheets collection you work with using the appropriate index number or sheet name, as follows:
- The index number represents the position of a worksheet in the tab bar of Workbook, from left to right. For these purposes, the count usually:
- Includes hidden sheets; but
- Doesn’t include chart sheets.
- The worksheet name is that displayed in the worksheet’s tab.
Therefore, Sheets(Array(WorksheetList)) represents the chart sheets or worksheets you specify in WorksheetList.
Macro example to refer to several worksheets
The following macro example moves (Move) the worksheets named “Sheet1”, “Sheet2” and “Sheet3” (Worksheets(Array(“Sheet1”, “Sheet2”, “Sheet3”))) in the workbook where the macro is stored (ThisWorkbook) after the last worksheets in the workbook (After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count)).
Sub referToSeveralWorksheets() 'source: https://powerspreadsheets.com/ 'moves several worksheets after the last worksheet in this workbook 'for further information: https://powerspreadsheets.com/excel-vba-sheets-worksheets/ 'move "Sheet1", "Sheet2" and "Sheet3" after the last worksheet in this workbook ThisWorkbook.Worksheets(Array("Sheet1", "Sheet2", "Sheet3")).Move After:=ThisWorkbook.Worksheets(ThisWorkbook.Worksheets.Count) End Sub
Effects of executing macro example to refer to several worksheets
The following GIF illustrates the results of executing the macro example. As expected, Sheet1, Sheet2 and Sheet3 are moved after the last worksheet in the workbook (Sheet5).
#11: Loop through all sheets in workbook with For Each… Next
VBA code to loop through all sheets in workbook with For Each… Next
To loop through all sheets in a workbook with a For Each… Next VBA loop, use a macro with the following statement structure:
For Each Sheet In Workbook.Sheets Statements Next Sheet
Process to loop through all sheets in workbook with For Each… Next
To loop through all sheets in a workbook with a For Each… Next VBA loop, follow these steps:
- Identify the workbook containing the sheets (Workbook).
- Identify the Sheets collection representing all sheets in Workbook (Sheets).
- Use an object variable to iterate through the Sheets in Workbook (Sheet).
- Execute a set of Statements for each Sheet in Workbook.
VBA statement explanation
Lines #1 and #3: For Each Sheet In Workbook.Sheets | Next Sheet
Item: For Each … In … | Next …
The For Each… Next statement repeats the Statements for each Sheet in Workbook.Sheets.
Item: Sheet
Object variable used to iterate through the Sheets in Workbook.
If you explicitly declare an object variable to represent Sheet, you can usually declare it as of the Variant or Object data type.
Item: Workbook.Sheets
Sheets collection through which the For Each… Next statement loops through.
Workbook is a Workbook object representing the Excel workbook containing the sheets you loop through.
You can usually work with one of the following properties to refer to this Workbook object:
- Application.ActiveWorkbook.
- Application.ThisWorkbook.
- Application.Workbooks.
The Workbook.Sheets property returns a Sheets collection representing all sheets in Workbook. The Sheets collection can, generally, contain both:
- Chart objects, where each Chart object represents an individual chart sheet; or
- Worksheet objects, where each Worksheet object represents an individual worksheet.
Therefore, For Each… Next loops through all sheets in Workbook.
Line #2: Statements
Statements that are executed for each Sheet in Workbook.Sheets.
Macro example to loop through all sheets in workbook with For Each… Next
The following macro example:
- Loops through each sheet in the workbook where the macro is stored (For Each iSheet In ThisWorkbook.Sheets | Next iSheet).
- Displays a message box (MsgBox) with the name (Name) of the current sheet (iSheet).
Sub loopThroughAllSheetsForEachNext() 'source: https://powerspreadsheets.com/ 'loops through all sheets in this workbook, and displays a message box with each sheet name 'for further information: https://powerspreadsheets.com/excel-vba-sheets-worksheets/ 'declare variable to iterate through all sheets Dim iSheet As Object 'loop through all sheets in this workbook For Each iSheet In ThisWorkbook.Sheets 'display message box with name of current sheet MsgBox iSheet.Name Next iSheet End Sub
Effects of executing macro example to loop through all sheets in workbook with For Each… Next
The following GIF illustrates the results of executing the macro example. As expected, Excel displays a message box with the name of each sheet (both worksheets and chart sheets) in the workbook.
#12: Loop through all worksheets in workbook with For Each… Next
VBA code to loop through all worksheets in workbook with For Each… Next
To loop through all worksheets in a workbook with a For Each… Next VBA loop, use a macro with the following statement structure:
For Each Worksheet In Workbook.Worksheets Statements Next Worksheet
Process to loop through all worksheets in workbook with For Each… Next
To loop through all worksheets in a workbook with a For Each… Next VBA loop, follow these steps:
- Identify the workbook containing the worksheets (Workbook).
- Identify the Sheets collection representing all worksheets in Workbook (Worksheets).
- Use an object variable to iterate through the worksheets in Workbook (Worksheet).
- Execute a set of Statements for each worksheet in Workbook.
VBA statement explanation
Lines #1 and #3: For Each Worksheet In Workbook.Worksheets | Next Worksheet
Item: For Each … In … | Next …
The For Each… Next statement repeats the Statements for each Worksheet in Workbook.Worksheets.
Item: Worksheet
Object variable used to iterate through the worksheets in Workbook.
If you explicitly declare an object variable to represent Worksheet, you can usually declare it as of the Worksheet object data type.
Item: Workbook.Worksheets
Sheets collection through which the For Each… Next statement loops through.
Workbook is a Workbook object representing the Excel workbook containing the worksheets you loop through.
You can usually work with one of the following properties to refer to this Workbook object:
- Application.ActiveWorkbook.
- Application.ThisWorkbook.
- Application.Workbooks.
The Workbook.Worksheets property returns a Sheets collection representing all worksheets in Workbook.
Therefore, For Each… Next loops through all worksheets in Workbook.
Line #2: Statements
Statements that are executed for each worksheet in Workbook.
Macro example to loop through all worksheets in workbook with For Each… Next
The following macro example:
- Loops through each worksheet in the workbook where the macro is stored (For Each iWorksheet In ThisWorkbook.Worksheets | Next iWorksheet).
- Displays a message box (MsgBox) with the name (Name) of the current sheet (iSheet).
Sub loopThroughAllWorksheetsForEachNext() 'source: https://powerspreadsheets.com/ 'loops through all worksheets in this workbook, and displays a message box with each worksheet name 'for further information: https://powerspreadsheets.com/excel-vba-sheets-worksheets/ 'declare variable to iterate through all worksheets Dim iWorksheet As Worksheet 'loop through all worksheets in this workbook For Each iWorksheet In ThisWorkbook.Worksheets 'display message box with name of current worksheet MsgBox iWorksheet.Name Next iWorksheet End Sub
Effects of executing macro example to loop through all worksheets in workbook with For Each… Next
The following GIF illustrates the results of executing the macro example. As expected, Excel displays a message box with the name of each worksheet in the workbook.
#13: Loop through all sheets in workbook with For… Next
VBA code to loop through all sheets in workbook with For… Next
To loop through all sheets in a workbook with a For… Next VBA loop, use a macro with the following statement structure:
For Counter = 1 To Workbook.Sheets.Count Statements Next Counter
Process to loop through all sheets in workbook with For… Next
To loop through all sheets in a workbook with a For… Next VBA loop, follow these steps:
- Identify the workbook containing the sheets (Workbook).
- Identify the Sheets collection representing all sheets in Workbook (Sheets).
- Count the number of sheets in the Sheets collection (Count).
- Execute a set of Statements a number of times equal to the number of Sheets in Workbook (For Counter = 1 To Workbook.Sheets.Count).
VBA statement explanation
Lines #1 and #3: For Counter = 1 To Workbook.Sheets.Count | Next Counter
Item: For … To … | Next …
The For… Next statement repeats the statements a number of times equal to the number of Sheets in Workbook.
Item: Counter
Numeric variable used as loop counter. If you explicitly declare Counter, you can usually declare it as of the Long data type.
Item: = 1
Counter’s initial value.
Item: Workbook.Sheets.Count
Counter’s end value, which is equal to the number of Sheets in Workbook.
Workbook is a Workbook object representing the Excel workbook containing the sheets you loop through.
You can usually work with one of the following properties to refer to this Workbook object:
- Application.ActiveWorkbook.
- Application.ThisWorkbook.
- Application.Workbooks.
The Workbook.Sheets property returns a Sheets collection representing all sheets in Workbook. The Sheets collection can, generally, contain both:
- Chart objects, where each Chart object represents an individual chart sheet; or
- Worksheet objects, where each Worksheet object represents an individual worksheet.
The Sheets.Count property returns the number of objects in the Sheets collection.
Therefore:
- Workbook.Sheets.Count returns the number of Sheets in Workbook; and
- For… Next loops through all Sheets in Workbook (From Counter = 1 To Workbook.Sheets.Count).
Line #2: Statements
Statements that are executed a number of times equal to the number of Sheets in Workbook.
Macro example to loop through all sheets in workbook with For… Next
The following macro example:
- Loops through each sheet in the workbook where the macro is stored (For iCounter = 1 To ThisWorkbook.Sheets.Count | Next iCounter).
- Displays a message box (MsgBox) with the name (Name) of the current sheet (ThisWorkbook.Sheets(iCounter)).
Sub loopThroughAllSheetsForNext() 'source: https://powerspreadsheets.com/ 'loops through all sheets in this workbook, and displays a message box each sheet name 'for further information: https://powerspreadsheets.com/excel-vba-sheets-worksheets/ 'declare variable to hold loop counter Dim iCounter As Long 'loop through all sheets in this workbook For iCounter = 1 To ThisWorkbook.Sheets.Count 'display message box with name of current sheet MsgBox ThisWorkbook.Sheets(iCounter).Name Next iCounter End Sub
Effects of executing macro example to loop through all sheets in workbook with For… Next
The following GIF illustrates the results of executing the macro example. As expected, Excel displays a message box with the name of each sheet (both worksheets and chart sheets) in the workbook.
#14: Loop through all worksheets in workbook with For… Next
VBA code to loop through all worksheets in workbook with For… Next
To loop through all worksheets in a workbook with a For… Next VBA loop, use a macro with the following statement structure:
For Counter = 1 To Workbook.Worksheets.Count Statements Next Counter
Process to loop through all worksheets in workbook with For… Next
To loop through all worksheets in a workbook with a For… Next VBA loop, follow these steps:
- Identify the workbook containing the worksheets (Workbook).
- Identify the Sheets collection representing all worksheets in Workbook (Worksheets).
- Count the number of worksheets in the Sheets collection (Count).
- Execute a set of Statements a number of times equal to the number of worksheets in Workbook (For Counter = 1 To Workbook.Worksheets.Count).
VBA statement explanation
Lines #1 and #3: For Counter = 1 To Workbook.Worksheets.Count | Next Counter
Item: For … To … | Next …
The For… Next statement repeats the statements a number of times equal to the number of worksheets in Workbook.
Item: Counter
Numeric variable used as loop counter. If you explicitly declare Counter, you can usually declare it as of the Long data type.
Item: = 1
Counter’s initial value.
Item: Workbook.Worksheets.Count
Counter’s end value, which is equal to the number of worksheets in Workbook.
Workbook is a Workbook object representing the Excel workbook containing the worksheets you loop through.
You can usually work with one of the following properties to refer to this Workbook object:
- Application.ActiveWorkbook.
- Application.ThisWorkbook.
- Application.Workbooks.
The Workbook.Worksheets property returns a Sheets collection representing all worksheets in Workbook.
The Worksheets.Count property returns the number of objects in the Sheets collection returned by the Worksheets property.
Therefore:
- Workbook.Worksheets.Count returns the number of worksheets in Workbook; and
- For… Next loops through all worksheets in Workbook (From Counter = 1 to Workbook.Worksheets.Count).
Line #2: Statements
Statements that are executed a number of times equal to the number of worksheets in Workbook.
Macro example to loop through all worksheets in workbook with For… Next
The following macro example:
- Loops through each worksheet in the workbook where the macro is stored (For iCounter = 1 To ThisWorkbook.Worksheets.Count | Next iCounter).
- Displays a message box (MsgBox) with the name (Name) of the current worksheet (ThisWorkbook.Worksheets(iCounter)).
Sub loopThroughAllWorksheetsForNext() 'source: https://powerspreadsheets.com/ 'loops through all worksheets in this workbook, and displays a message box with each worksheet name 'for further information: https://powerspreadsheets.com/excel-vba-sheets-worksheets/ 'declare variable to hold loop counter Dim iCounter As Long 'loop through all worksheets in this workbook For iCounter = 1 To ThisWorkbook.Worksheets.Count 'display message box with name of current worksheet MsgBox ThisWorkbook.Worksheets(iCounter).Name Next iCounter End Sub
Effects of executing macro example to loop through all worksheets in workbook with For… Next
The following GIF illustrates the results of executing the macro example. As expected, Excel displays a message box with the name of each worksheet in the workbook.
#15: Loop through all sheets in reverse order
VBA code to loop through all sheets in reverse order
To loop through all sheets in a workbook in reverse order with VBA, use a macro with the following statement structure:
For Counter = Workbook.Sheets.Count To 1 Step -1 Statements Next Counter
Process to loop through all sheets in reverse order
To loop through all sheets in a workbook in reverse order with VBA, follow these steps:
- Identify the workbook containing the sheets (Workbook).
- Identify the Sheets collection representing all sheets in Workbook (Sheets).
- Count the number of sheets in the Sheets collection (Count).
- Execute a set of Statements a number of times equal to the number of Sheets in Workbook while clarifying that the looping occurs in reverse order (For Counter = Workbook.Sheets.Count To 1 Step -1).
VBA statement explanation
Lines #1 and #3: For Counter = Workbook.Sheets.Count To 1 Step -1 | Next Counter
Item: For … To …. | Next …
The For… Next statement repeats the statements a number of times equal to the number of worksheets in Workbook.
Item: Counter
Numeric variable used as loop counter. If you explicitly declare Counter, you can usually declare it as of the Long data type.
Item: = Workbook.Sheets.Count
Counter’s initial value, which is equal to the number of Sheets in Workbook.
Workbook is a Workbook object representing the Excel workbook containing the sheets you loop through.
You can usually work with one of the following properties to refer to this Workbook object:
- Application.ActiveWorkbook.
- Application.ThisWorkbook.
- Application.Workbooks.
The Workbook.Sheets property returns a Sheets collection representing all sheets in Workbook. The Sheets collection can, generally, contain both:
- Chart objects, where each Chart object represents an individual chart sheet; or
- Worksheet objects, where each Worksheet object represents an individual worksheet.
The Sheets.Count property returns the number of objects in the Sheets collection. Therefore, Workbook.Sheets.Count returns the number of Sheets in Workbook.
Item: 1
Counter’s end value.
Item: Step -1
Amount Counter changes each loop iteration.
When looping through all sheets in reverse order:
- Counter’s initial value is equal to the number of Sheets in Workbook (Workbook.Sheets.Count).
- Counter’s end value is 1.
- Counter decreases by 1 each iteration.
Therefore, For… Next loops through all Sheets in Workbook in reverse order (From Counter = Workbook.Sheets.Count To 1 Step -1).
Line #2: Statements
Statements that are executed a number of times equal to the number of Sheets in Workbook.
Macro example to loop through all sheets in reverse order
The following macro example:
- Loops through each sheet in the workbook where the macro is stored in reverse order (For iCounter = ThisWorkbook.Sheets.Count To 1 Step -1 | Next iCounter).
- Displays a message box (MsgBox) with the name (Name) of the current sheet (ThisWorkbook.Sheets(iCounter)).
Sub loopThroughAllSheetsBackwards() 'source: https://powerspreadsheets.com/ 'loops through all sheets in this workbook (in reverse order), and displays a message box with each sheet name 'for further information: https://powerspreadsheets.com/excel-vba-sheets-worksheets/ 'declare variable to hold loop counter Dim iCounter As Long 'loop through all sheets in this workbook (in reverse order) For iCounter = ThisWorkbook.Sheets.Count To 1 Step -1 'display message box with name of current sheet MsgBox ThisWorkbook.Sheets(iCounter).Name Next iCounter End Sub
Effects of executing macro example to loop through all sheets in reverse order
The following GIF illustrates the results of executing the macro example. As expected, Excel displays a message box with the name of each sheet (both worksheets and chart sheets) in the workbook in reverse order.
#16: Loop through all worksheets in reverse order
VBA code to loop through all worksheets in reverse order
To loop through all worksheets in a workbook in reverse order with VBA, use a macro with the following statement structure:
For Counter = Workbook.Worksheets.Count To 1 Step -1 Statements Next Counter
Process to loop through all worksheets in reverse order
To loop through all worksheets in a workbook in reverse order with VBA, follow these steps:
- Identify the workbook containing the worksheets (Workbook).
- Identify the Sheets collection representing all worksheets in Workbook (Worksheets).
- Count the number of worksheets in the Sheets collection (Count).
- Execute a set of Statements a number of times equal to the number of worksheets in Workbook while clarifying that the looping occurs in reverse order (For Counter = Workbook.Worksheets.Count To 1 Step -1).
VBA statement explanation
Lines #1 and #3: For Counter = ThisWorkbook.Worksheets.Count To 1 Step -1 | Next Counter
Item: For … To … | Next …
The For… Next statement repeats the statements a number of times equal to the number of worksheets in Workbook.
Item: Counter
Numeric variable used as loop counter. If you explicitly declare Counter, you can usually declare it as of the Long data type.
Item: = Workbook.Worksheets.Count
Counter’s initial value, which is equal to the number of worksheets in Workbook.
Workbook is a Workbook object representing the Excel workbook containing the worksheets you loop through.
You can usually work with one of the following properties to refer to this Workbook object:
- Application.ActiveWorkbook.
- Application.ThisWorkbook.
- Application.Workbooks.
The Workbook.Worksheets property returns a Sheets collection representing all worksheets in Workbook.
The Worksheets.Count property returns the number of objects in the Sheets collection returned by the Worksheets property. Therefore, Workbook.Worksheets.Count returns the number of worksheets in Workbook.
Item: 1
Counter’s end value.
Item: Step -1
Amount Counter changes each loop iteration.
When looping through all worksheets in reverse order:
- Counter’s initial value is equal to the number of worksheets in Workbook (Workbook.Worksheets.Count).
- Counter’s end value is 1.
- Counter decreases by 1 each iteration.
Therefore, For… Next loops through all worksheets in Workbook in reverse order (From Counter = Workbook.Worksheets.Count To 1 Step -1).
Line #2: Statements
Statements that are executed a number of times equal to the number of worksheets in Workbook.
Macro example to loop through all worksheets in reverse order
The following macro example:
- Loops through each worksheet in the workbook where the macro is stored in reverse order (For iCounter = ThisWorkbook.Worksheets.Count To 1 Step -1 | Next iCounter).
- Displays a message box (MsgBox) with the name (Name) of the current worksheet (ThisWorkbook.Worksheets(iCounter)).
Sub loopThroughAllWorksheetsBackwards() 'source: https://powerspreadsheets.com/ 'loops through all worksheets in this workbook (in reverse order), and displays a message box with each worksheet name 'for further information: https://powerspreadsheets.com/excel-vba-sheets-worksheets/ 'declare variable to hold loop counter Dim iCounter As Long 'loop through all worksheets in this workbook (in reverse order) For iCounter = ThisWorkbook.Worksheets.Count To 1 Step -1 'display message box with name of current worksheet MsgBox ThisWorkbook.Worksheets(iCounter).Name Next iCounter End Sub
Effects of executing macro example to loop through all worksheets in reverse order
The following GIF illustrates the results of executing the macro example. As expected, Excel displays a message box with the name of each worksheet in the workbook in reverse order.
Learn more about working with sheets and worksheets in VBA
You can get immediate free access to the example workbook that accompanies this VBA Tutorial by subscribing to the Power Spreadsheets Newsletter.
Alternatively, you can access all the files that accompany my Tutorials here.
The following Books are referenced in this Excel VBA sheets and worksheets Tutorial:
- Alexander, Michael (2015). Excel Macros for Dummies. Hoboken, NJ: John Wiley & Sons Inc.
- Alexander, Michael and Kusleika, Dick (2016). Excel 2016 Power Programming with VBA. Indianapolis, IN: John Wiley & Sons Inc.
- Jelen, Bill and Syrstad, Tracy (2015). Excel 2016 VBA and Macros. United States of America: Pearson Education, Inc.
- Walkenbach, John (2015). Excel VBA Programming for Dummies. Hoboken, NJ: John Wiley & Sons Inc.