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 |
Содержание
- VBA-Урок 3. Коллекция Sheets
- Как посчитать количество листов в книге
- Как добавить лист в книгу
- Как скрыть лист
- Объект Sheets (Excel)
- Замечания
- Пример
- Методы
- Свойства
- См. также
- Поддержка и обратная связь
- Sheets object (Excel)
- Remarks
- Example
- Methods
- Properties
- See also
- Support and feedback
- VBA Sheets – The Ultimate Guide
- Sheets Vs. Worksheets
- Referencing Sheets
- ActiveSheet
- Sheet Name
- Sheet Index Number
- Sheet Index Number – Last Sheet in Workbook
- Sheet “Code Name”
- VBA Coding Made Easy
- 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
- VBA Code Examples Add-in
VBA-Урок 3. Коллекция Sheets
Данная коллекция представляет собой набор листов (Sheets) в книге (Workbooks). Давайте посмотрим, какие действия мы можем делать над листами.
Как посчитать количество листов в книге
Сначала попробуем узнать сколько листов имеет наша книга:
Данным кодом мы вызвали сообщения на экран (MsgBox), которое отобразило количество листов (Sheets.Count) в книге (Workbooks) » Test.xls«.
Под листом понимается не только ячейки, но и диаграммы. Также, как и лист для расчета, диаграмма будет включена в подсчет листов.
Как добавить лист в книгу
В коллекции листов также есть возможность добавлять свои листы, для этого существует метод Add. Этот метод имеет 4 параметра Add (Before, After, Count, Type). Все эти параметры необязательны. Первые два отвечают за место вставки листа. Далее, количество листов, вставляемых Count и тип листа Type . Типы могут быть, например, такие xlWorkSheet для расчетного листа и xlChart для диаграммы. Если местоположение не указывать, то лист будет вставляться относительно текущего листа.
Таким образом мы вставили 4 листа (Count: = 4) после листа «Лист3» .
Также можно вставить лист в самый конец книги:
Как скрыть лист
Если у Вас есть желание, то некоторые листы можно скрыть. Это бывает полезно, если у Вас есть константы или расчеты, которые Вы не хотите чтобы видели на экране в виде листов. Для этого можно использовать метод Visible. Устанавливая это свойство в TRUE или FALSE вы можете убрать или отобразить необходимый лист.
Источник
Объект Sheets (Excel)
Коллекция всех листов в указанной или активной книге.
Замечания
Коллекция Листов может содержать объекты Chart или Worksheet .
Коллекция Листов полезна, если требуется вернуть листы любого типа. Если вам нужно работать с листами только одного типа, см. раздел объекта для этого типа листа.
Пример
Используйте свойство Sheets объекта Workbook , чтобы вернуть коллекцию Sheets . В следующем примере печатаются все листы активной книги.
Используйте метод Add , чтобы создать новый лист и добавить его в коллекцию. В следующем примере два листа диаграммы добавляются в активную книгу, помещая их после двух листов в книге.
Используйте листы (индекс), где индекс — это имя листа или номер индекса, чтобы вернуть один объект Chart или Worksheet . В следующем примере активируется лист с именем Sheet1.
Используйте листы (массив), чтобы указать несколько листов. В следующем примере листы с именами Sheet4 и Sheet5 перемещаются в начало книги.
Методы
Свойства
См. также
Поддержка и обратная связь
Есть вопросы или отзывы, касающиеся Office VBA или этой статьи? Руководство по другим способам получения поддержки и отправки отзывов см. в статье Поддержка Office VBA и обратная связь.
Источник
Sheets object (Excel)
A collection of all the sheets in the specified or active workbook.
The Sheets collection can contain Chart or Worksheet objects.
The Sheets collection is useful when you want to return sheets of any type. If you need to work with sheets of only one type, see the object topic for that sheet type.
Example
Use the Sheets property of the Workbook object to return the Sheets collection. The following example prints all sheets in the active workbook.
Use the Add method to create a new sheet and add it to the collection. The following example adds two chart sheets to the active workbook, placing them after sheet two in the workbook.
Use Sheets (index), where index is the sheet name or index number, to return a single Chart or Worksheet object. The following example activates the sheet named Sheet1.
Use Sheets (array) to specify more than one sheet. The following example moves the sheets named Sheet4 and Sheet5 to the beginning of the workbook.
Methods
Properties
See also
Support and feedback
Have questions or feedback about Office VBA or this documentation? Please see Office VBA support and feedback for guidance about the ways you can receive support and provide feedback.
Источник
VBA Sheets – The Ultimate Guide
In this Article
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:
The other is with the Worksheets object:
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.
Sheet Name
You are probably most familiar with referencing Sheets by their Tab Name:
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.:
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:
Sheet “Code Name”
The Sheet Code Name is it’s Object name in VBA:
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!
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:
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
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.
Select a Sheet
Select Multiple Sheets
Use an array to select multiple sheets at once:
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:
Assign a worksheet to a variable:
Now you can reference the worksheet variable in your code:
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:
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
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:
or disable workbook protection:
Note: You can also protect / unprotect without a password by omitting the Password argument:
Worksheet Protection
Worksheet-level protection prevents changes to individual worksheets.
Protect Worksheet
Unprotect Worksheet
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.
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
Hide Worksheet
Very Hide Worksheet
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.
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
Msgbox ws.name
Next ws Loop Through Selected Sheets Dim ws As Worksheet
For Each ws In ActiveWindow.SelectedSheets
MsgBox ws.Name
Next ws 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
ws.Unprotect «password»
Next ws
VBA Code Examples Add-in
Easily access all of the code examples found on our site.
Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.
Источник
In this article you will be learning about sheets vs worksheets in excel VBA and how to use of these functions when manipulating spreadsheets.
Table of Contents
- Difference between Worksheets and Sheets in VBA
- Sheets
- Looping through each Object in the Sheets collection
- Looping through every Sheet in the Sheets collection
- Worksheets
- Referencing a Worksheet in VBA
- Using the Worksheet Name
- Using the Index Number
- Using the Worksheet Code Name
- Referring to a Worksheet in a Different Workbook
- Adding a Worksheet
- Deleting a Worksheet
- Delete a specific worksheet.
- Renaming the Worksheets
- Adding Multiple Sheets
- Assigning Worksheet Object to a Variable
- Hide Worksheets Using VBA
- To unhide the sheets
- Hide Sheets Based on the Text in it
- Sorting the Worksheets in an Alphabetical Order
- Creating a Table of Contents of All Worksheets with Hyperlinks
- Referencing a Worksheet in VBA
Difference between Worksheets and Sheets in VBA
In VBA, you have two collections that can be a bit confusing at times. In a workbook, you can have worksheets and as well as chart sheets.
In Excel VBA:
- The ‘Worksheets’ collection would refer to the collection of all the worksheet objects in a workbook.
- The ‘Sheets’ collection would refer to all the worksheets as well as chart sheets in the workbook.
To run the VBA code in Excel, perform the following first
- Under the developer tab, click visual basic
- Click the insert option and choose a module
- Enter your codes and click run.
Now we know, ‘sheets’ is the collection of worksheets and chart sheets.
Looping through each Object in the Sheets collection
To loop through every sheet,
Code:
Sub UsingObject() Dim obj As Object For Each obj In ActiveWorkbook.Sheets MsgBox obj.Name Next obj End Sub
Looping through every Sheet in the Sheets collection
We can also count the sheets, then loop using a For loop.
Code
Sub UsingCount() Dim i As Integer For i = 1 To Sheets.Count MsgBox Sheets(i).Name Next i End Sub
This method of looping by counting the objects will work equally well with Charts and Worksheets.
Worksheets
When you have to work with worksheets only, use the ‘Worksheets’ collection, and when you have to refer to all sheets, then use the ‘Sheets’ collection.
Let’s see worksheets in detail.
Referencing a Worksheet in VBA
You can refer a worksheet in the following methods.
Using the Worksheet Name
This is the easiest way to refer to a worksheet.
When you are working with a workbook with three worksheets namely Sheet 1, Sheet 2, Sheet 3 (which is common in any excel file) and you want to activate Sheet 3.
Use the following code:
Code:
Sub ActivateSheet() Worksheets("Sheet3").Activate End Sub
You can also use the sheets collection method to activate the sheets, as we are using the name of the sheet as the key point.
Use this code
Code:
Sub ActivateSheet() Sheets("Sheet3").Activate End Sub
Using the Index Number
The difficult part of using the name of the sheet to refer them is you need to know the exact name of the sheet or the program doesn’t work.
In this case, you can use the index number of the worksheets. The indexing starts from 1 in the collection of sheets.
Use this code to activate Sheet3:
Code
Sub ActivateSheet() Worksheets(3).Activate End Sub
Important: A chart sheet is not a part of the worksheets collection.
This is because when we use the index numbers in the Worksheet collection, it will only refer to the worksheets in the workbook.
Note: Indexing goes from left to right. So if you shift Sheet3 to the left of Sheet2, then Worksheets (2) would refer to Sheet3.
Using the Worksheet Code Name
You can use the code name of the worksheet to refer to a worksheet. This code name can be assigned in the VB Editor and it won’t change when you change the name of the worksheet.
To give your worksheet a code name, follow these steps:
- Under the Developer tab, click the Visual Basic option.
- This will open the VB Editor.
- Now, Click the View option in the menu and click on Project Window.
- Click on the sheet name in the project explorer that you want to rename.
- In the Properties pane, change the name in the field in front of (Name).
Note: Don’t include spaces in the name.
This would change the name of your Worksheet in the VBA, i.e., the code name. Therefore, when you change the worksheet name it doesn’t affect the code in your VBA.
Now, you can use either the Worksheets collection to refer to the worksheet or use the codename.
The following code uses both worksheet collection method and name of the sheet method.
Code
Worksheets("Sheet3").Activate SH3.Activate
(I have code named my sheet as SH3)
Referring to a Worksheet in a Different Workbook
If you need to access a worksheet in a different workbook,
Code
Sub SheetActivate() Workbooks("Examples.xlsx").Worksheets("Sheet1").Activate End Sub
Adding a Worksheet
When you need to add a worksheet
Code
Sub AddSheet() Worksheets.Add End Sub
Deleting a Worksheet
When you want to delete a worksheet:
Code
Sub DeleteSheet() ActiveSheet.Delete End Sub
Click ok on the warning prompt. The worksheet gets deleted.
To avoid the warning prompt, use the below code:
Code
Sub DeleteSheet() Application.DisplayAlerts = False ActiveSheet.Delete Application.DisplayAlerts = True End Sub
Note: You can’t undo this delete option. So be sure.
Delete a specific worksheet.
If you want to delete a specific sheet,
Code
Sub DeleteSheet() Worksheets("Sheet3").Delete End Sub
You can also use the code name of the sheet to delete it.
Sub DeleteSheet() SH3.Delete End Sub
Renaming the Worksheets
When you want to rename the sheets using VBA code:
Sub RenameSheet() Worksheets("Sheet1").Name = "Naming sheet" End Sub
Code
Adding Multiple Sheets
When you need to add multiple sheets
Code
Sub RenameSheet() Dim Countsheets As Integer Countsheets = Worksheets.Count For i = 1 To 4 Worksheets.Add after:=Worksheets(Countsheets + i – 1) Worksheets(Countsheets + i).Name = "Multiple Sheets 1" & i Next i End Sub
Assigning Worksheet Object to a Variable
You can assign a worksheet to an object variable, and then use the variable instead of the worksheet references.
Code
Sub RenameSheet() Dim Ws As Worksheet For Each Ws In Worksheets Ws.Name = "Assigning Variable " & Ws.Name Next Ws End Sub
Hide Worksheets Using VBA
You can hide and unhide worksheets using VBA. Normally when a worksheet is hidden, you can easily unhide the worksheet by right-clicking on any sheet tab.
But if you don’t want to unhide the worksheet in this method, you can do this using VBA.
The code below would hide all the worksheets in the workbook (except the active sheet), such that you cannot unhide it by right-clicking on the sheet name.
Code
Sub HideAllExcetActiveSheet() Dim Ws As Worksheet For Each Ws In ThisWorkbook.Worksheets If Ws.Name <> ActiveSheet.Name Then Ws.Visible = xlSheetVeryHidden Next Ws End Sub
If you want to hide sheets that can be unhidden easily, use the below code.
Code
Sub HideAllExceptActiveSheet() Dim Ws As Worksheet For Each Ws In ThisWorkbook.Worksheets If Ws.Name <> ActiveSheet.Name Then Ws.Visible = xlSheetHidden Next Ws End Sub
To unhide the sheets
Code:
Sub UnhideAllWoksheets() Dim Ws As Worksheet For Each Ws In ThisWorkbook.Worksheets Ws.Visible = xlSheetVisible Next Ws End Sub
Hide Sheets Based on the Text in it
You can hide sheets based on the text in it. You can do this using the VBA INSTR function.
The below code would hide all the sheets except the ones with the text 2020 in it.
Code:
Sub HideWithMatchingText() Dim Ws As Worksheet For Each Ws In Worksheets If InStr(1, Ws.Name, "2020", vbBinaryCompare) = 0 Then Ws.Visible = xlSheetHidden End If Next Ws End Sub
Sorting the Worksheets in an Alphabetical Order
Using VBA, you can quickly sort the worksheets based on their names.
Use the below code to quickly sort sheets in an ascending order.
Code
Sub SortSheetsTabName() Application.ScreenUpdating = False Dim ShCount As Integer, i As Integer, j As Integer ShCount = Sheets.Count For i = 1 To ShCount – 1 For j = i + 1 To ShCount If Sheets(j).Name < Sheets(i).Name Then Sheets(j).Move before:=Sheets(i) End If Next j Next i Application.ScreenUpdating = True End Sub
Creating a Table of Contents of All Worksheets with Hyperlinks
To create a table of contents of all worksheets:
Code
Sub AddIndexSheet() Worksheets.Add ActiveSheet.Name = "Index" For i = 2 To Worksheets.Count ActiveSheet.Hyperlinks.Add Anchor:=Cells(i – 1, 1), _ Address:="", SubAddress:=Worksheets(i).Name & "!A1", _ TextToDisplay:=Worksheets(i).Name Next i End Sub
The above code inserts a new worksheet and names it Index.
It then loops through all the worksheets and creates a hyperlink for all the worksheets in the Index sheet.
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.
Термин Объекты Excel (понимаемый в широком смысле, как объектная модель Excel) включает в себя элементы, из которых состоит любая рабочая книга Excel. Это, например, рабочие листы (Worksheets), строки (Rows), столбцы (Columns), диапазоны ячеек (Ranges) и сама рабочая книга Excel (Workbook) в том числе. Каждый объект Excel имеет набор свойств, которые являются его неотъемлемой частью.
Например, объект Worksheet (рабочий лист) имеет свойства Name (имя), Protection (защита), Visible (видимость), Scroll Area (область прокрутки) и так далее. Таким образом, если в процессе выполнения макроса требуется скрыть рабочий лист, то достаточно изменить свойство Visible этого листа.
В Excel VBA существует особый тип объектов – коллекция. Как можно догадаться из названия, коллекция ссылается на группу (или коллекцию) объектов Excel. Например, коллекция Rows – это объект, содержащий все строки рабочего листа.
Доступ ко всем основным объектам Excel может быть осуществлён (прямо или косвенно) через объект Workbooks, который является коллекцией всех открытых в данный момент рабочих книг. Каждая рабочая книга содержит объект Sheets – коллекция, которая включает в себя все рабочие листы и листы с диаграммами рабочей книги. Каждый объект Worksheet состоит из коллекции Rows – в неё входят все строки рабочего листа, и коллекции Columns – все столбцы рабочего листа, и так далее.
В следующей таблице перечислены некоторые наиболее часто используемые объекты Excel. Полный перечень объектов Excel VBA можно найти на сайте Microsoft Office Developer (на английском).
Объект | Описание |
---|---|
Application | Приложение Excel. |
Workbooks | Коллекция всех открытых в данный момент рабочих книг в текущем приложении Excel. Доступ к какой-то конкретной рабочей книге может быть осуществлён через объект Workbooks при помощи числового индекса рабочей книги или её имени, например, Workbooks(1) или Workbooks(«Книга1»). |
Workbook | Объект Workbook – это рабочая книга. Доступ к ней может быть выполнен через коллекцию Workbooks при помощи числового индекса или имени рабочей книги (см. выше). Для доступа к активной в данный момент рабочей книге можно использовать ActiveWorkbook.
Из объекта Workbook можно получить доступ к объекту Sheets, который является коллекцией всех листов рабочей книги (рабочие листы и диаграммы), а также к объекту Worksheets, который представляет из себя коллекцию всех рабочих листов книги Excel. |
Sheets | Объект Sheets– это коллекция всех листов рабочей книги. Это могут быть как рабочие листы, так и диаграммы на отдельном листе. Доступ к отдельному листу из коллекции Sheets можно получить при помощи числового индекса листа или его имени, например, Sheets(1) или Sheets(«Лист1»). |
Worksheets | Объект Worksheets – это коллекция всех рабочих листов в рабочей книге (то есть, все листы, кроме диаграмм на отдельном листе). Доступ к отдельному рабочему листу из коллекции Worksheets можно получить при помощи числового индекса рабочего листа или его имени, например, Worksheets(1) или Worksheets(«Лист1»). |
Worksheet | Объект Worksheet – это отдельный рабочий лист книги Excel. Доступ к нему можно получить при помощи числового индекса рабочего листа или его имени (см. выше).
Кроме этого Вы можете использовать ActiveSheet для доступа к активному в данный момент рабочему листу. Из объекта Worksheet можно получить доступ к объектам Rows и Columns, которые являются коллекцией объектов Range, ссылающихся на строки и столбцы рабочего листа. А также можно получить доступ к отдельной ячейке или к любому диапазону смежных ячеек на рабочем листе. |
Rows | Объект Rows – это коллекция всех строк рабочего листа. Объект Range, состоящий из отдельной строки рабочего листа, может быть доступен по номеру этой строки, например, Rows(1). |
Columns | Объект Columns – это коллекция всех столбцов рабочего листа. Объект Range, состоящий из отдельного столбца рабочего листа, может быть доступен по номеру этого столбца, например, Columns(1). |
Range | Объект Range – это любое количество смежных ячеек на рабочем листе. Это может быть одна ячейка или все ячейки листа.
Доступ к диапазону, состоящему из единственной ячейки, может быть осуществлён через объект Worksheet при помощи свойства Cells, например, Worksheet.Cells(1,1). По-другому ссылку на диапазон можно записать, указав адреса начальной и конечной ячеек. Их можно записать через двоеточие или через запятую. Например, Worksheet.Range(«A1:B10») или Worksheet.Range(«A1», «B10») или Worksheet.Range(Cells(1,1), Cells(10,2)). Обратите внимание, если в адресе Range вторая ячейка не указана (например, Worksheet.Range(«A1») или Worksheet.Range(Cells(1,1)), то будет выбран диапазон, состоящий из единственной ячейки. |
Приведённая выше таблица показывает, как выполняется доступ к объектам Excel через родительские объекты. Например, ссылку на диапазон ячеек можно записать вот так:
Workbooks("Книга1").Worksheets("Лист1").Range("A1:B10")
Содержание
- Присваивание объекта переменной
- Активный объект
- Смена активного объекта
- Свойства объектов
- Методы объектов
- Рассмотрим несколько примеров
- Пример 1
- Пример 2
- Пример 3
Присваивание объекта переменной
В Excel VBA объект может быть присвоен переменной при помощи ключевого слова Set:
Dim DataWb As Workbook Set DataWb = Workbooks("Книга1.xlsx")
Активный объект
В любой момент времени в Excel есть активный объект Workbook – это рабочая книга, открытая в этот момент. Точно так же существует активный объект Worksheet, активный объект Range и так далее.
Сослаться на активный объект Workbook или Sheet в коде VBA можно как на ActiveWorkbook или ActiveSheet, а на активный объект Range – как на Selection.
Если в коде VBA записана ссылка на рабочий лист, без указания к какой именно рабочей книге он относится, то Excel по умолчанию обращается к активной рабочей книге. Точно так же, если сослаться на диапазон, не указывая определённую рабочую книгу или лист, то Excel по умолчанию обратится к активному рабочему листу в активной рабочей книге.
Таким образом, чтобы сослаться на диапазон A1:B10 на активном рабочем листе активной книги, можно записать просто:
Смена активного объекта
Если в процессе выполнения программы требуется сделать активной другую рабочую книгу, другой рабочий лист, диапазон и так далее, то для этого нужно использовать методы Activate или Select вот таким образом:
Sub ActivateAndSelect() Workbooks("Книга2").Activate Worksheets("Лист2").Select Worksheets("Лист2").Range("A1:B10").Select Worksheets("Лист2").Range("A5").Activate End Sub
Методы объектов, в том числе использованные только что методы Activate или Select, далее будут рассмотрены более подробно.
Свойства объектов
Каждый объект VBA имеет заданные для него свойства. Например, объект Workbook имеет свойства Name (имя), RevisionNumber (количество сохранений), Sheets (листы) и множество других. Чтобы получить доступ к свойствам объекта, нужно записать имя объекта, затем точку и далее имя свойства. Например, имя активной рабочей книги может быть доступно вот так: ActiveWorkbook.Name. Таким образом, чтобы присвоить переменной wbName имя активной рабочей книги, можно использовать вот такой код:
Dim wbName As String wbName = ActiveWorkbook.Name
Ранее мы показали, как объект Workbook может быть использован для доступа к объекту Worksheet при помощи такой команды:
Workbooks("Книга1").Worksheets("Лист1")
Это возможно потому, что коллекция Worksheets является свойством объекта Workbook.
Некоторые свойства объекта доступны только для чтения, то есть их значения пользователь изменять не может. В то же время существуют свойства, которым можно присваивать различные значения. Например, чтобы изменить название активного листа на «Мой рабочий лист«, достаточно присвоить это имя свойству Name активного листа, вот так:
ActiveSheet.Name = "Мой рабочий лист"
Методы объектов
Объекты VBA имеют методы для выполнения определённых действий. Методы объекта – это процедуры, привязанные к объектам определённого типа. Например, объект Workbook имеет методы Activate, Close, Save и ещё множество других.
Для того, чтобы вызвать метод объекта, нужно записать имя объекта, точку и имя метода. Например, чтобы сохранить активную рабочую книгу, можно использовать вот такую строку кода:
Как и другие процедуры, методы могут иметь аргументы, которые передаются методу при его вызове. Например, метод Close объекта Workbook имеет три необязательных аргумента, которые определяют, должна ли быть сохранена рабочая книга перед закрытием и тому подобное.
Чтобы передать методу аргументы, необходимо записать после вызова метода значения этих аргументов через запятую. Например, если нужно сохранить активную рабочую книгу как файл .csv с именем «Книга2», то нужно вызвать метод SaveAs объекта Workbook и передать аргументу Filename значение Книга2, а аргументу FileFormat – значение xlCSV:
ActiveWorkbook.SaveAs "Книга2", xlCSV
Чтобы сделать код более читаемым, при вызове метода можно использовать именованные аргументы. В этом случае сначала записывают имя аргумента, затем оператор присваивания «:=» и после него указывают значение. Таким образом, приведённый выше пример вызова метода SaveAs объекта Workbook можно записать по-другому:
ActiveWorkbook.SaveAs Filename:="Книга2", [FileFormat]:=xlCSV
В окне Object Browser редактора Visual Basic показан список всех доступных объектов, их свойств и методов. Чтобы открыть этот список, запустите редактор Visual Basic и нажмите F2.
Рассмотрим несколько примеров
Пример 1
Этот отрывок кода VBA может служить иллюстрацией использования цикла For Each. В данном случае мы обратимся к нему, чтобы продемонстрировать ссылки на объект Worksheets (который по умолчанию берётся из активной рабочей книги) и ссылки на каждый объект Worksheet отдельно. Обратите внимание, что для вывода на экран имени каждого рабочего листа использовано свойство Name объекта Worksheet.
'Пролистываем поочерёдно все рабочие листы активной рабочей книги 'и выводим окно сообщения с именем каждого рабочего листа Dim wSheet As Worksheet For Each wSheet in Worksheets MsgBox "Найден рабочий лист: " & wSheet.Name Next wSheet
Пример 2
В этом примере кода VBA показано, как можно получать доступ к рабочим листам и диапазонам ячеек из других рабочих книг. Кроме этого, Вы убедитесь, что если не указана ссылка на какой-то определённый объект, то по умолчанию используются активные объекты Excel. Данный пример демонстрирует использование ключевого слова Set для присваивания объекта переменной.
В коде, приведённом ниже, для объекта Range вызывается метод PasteSpecial. Этот метод передаёт аргументу Paste значение xlPasteValues.
'Копируем диапазон ячеек из листа "Лист1" другой рабочей книги (с именем Data.xlsx) 'и вставляем только значения на лист "Результаты" текущей рабочей книги (с именем CurrWb.xlsm) Dim dataWb As Workbook Set dataWb = Workbooks.Open("C:Data") 'Обратите внимание, что DataWb – это активная рабочая книга. 'Следовательно, следующее действие выполняется с объектом Sheets в DataWb. Sheets("Лист1").Range("A1:B10").Copy 'Вставляем значения, скопированные из диапазона ячеек, на рабочий лист "Результаты" 'текущей рабочей книги. Обратите внимание, что рабочая книга CurrWb.xlsm не является 'активной, поэтому должна быть указана в ссылке. Workbooks("CurrWb").Sheets("Результаты").Range("A1").PasteSpecial Paste:=xlPasteValues
Пример 3
Следующий отрывок кода VBA показывает пример объекта (коллекции) Columns и демонстрирует, как доступ к нему осуществляется из объекта Worksheet. Кроме этого, Вы увидите, что, ссылаясь на ячейку или диапазон ячеек на активном рабочем листе, можно не указывать этот лист в ссылке. Вновь встречаем ключевое слово Set, при помощи которого объект Range присваивается переменной Col.
Данный код VBA показывает также пример доступа к свойству Value объекта Range и изменение его значения.
'С помощью цикла просматриваем значения в столбце A на листе "Лист2", 'выполняем с каждым из них арифметические операции и записываем результат 'в столбец A активного рабочего листа (Лист1) Dim i As Integer Dim Col As Range Dim dVal As Double 'Присваиваем переменной Col столбец A рабочего листа "Лист2" Set Col = Sheets("Лист2").Columns("A") i = 1 'Просматриваем последовательно все ячейки столбца Col до тех пор 'пока не встретится пустая ячейка Do Until IsEmpty(Col.Cells(i)) 'Выполняем арифметические операции со значением текущей ячейки dVal = Col.Cells(i).Value * 3 - 1 'Следующая команда записывает результат в столбец A 'активного листа. Нет необходимости указывать в ссылке имя листа, 'так как это активный лист рабочей книги. Cells(i, 1).Value = dVal i = i + 1 Loop
Оцените качество статьи. Нам важно ваше мнение:
Apart from cells and ranges, working with worksheets is another area you should know about to use VBA efficiently in Excel.
Just like any object in VBA, worksheets have different properties and methods associated with it that you can use while automating your work with VBA in Excel.
In this tutorial, I will cover ‘Worksheets’ in detail and also show you some practical examples.
So let’s get started.
All the codes I mention in this tutorial need to be placed in the VB Editor. Go to the ‘Where to Put the VBA Code‘ section to know how it works.
If you’re interested in learning VBA the easy way, check out my Online Excel VBA Training.
Difference between Worksheets and Sheets in VBA
In VBA, you have two collections that can be a bit confusing at times.
In a workbook, you can have worksheets and as well as chart sheets. The example below has three worksheets and one chart sheet.
In Excel VBA:
- The ‘Worksheets’ collection would refer to the collection of all the worksheet objects in a workbook. In the above example, the Worksheets collection would consist of three worksheets.
- The ‘Sheets’ collection would refer to all the worksheets as well as chart sheets in the workbook. In the above example, it would have four elements – 3 Worksheets + 1 Chart sheet.
If you have a workbook that only has worksheets and no chart sheets, then ‘Worksheets’ and ‘Sheets’ collection is the same.
But when you have one or more chart sheets, the ‘Sheets’ collection would be bigger than the ‘Worksheets’ collection
Sheets = Worksheets + Chart Sheets
Now with this distinction, I recommend being as specific as possible when writing a VBA code.
So if you have to refer to worksheets only, use the ‘Worksheets’ collection, and if you have to refer to all sheets (including chart sheets), the use the ‘Sheets’ collection.
In this tutorial, I will be using the ‘Worksheets’ collection only.
Referencing a Worksheet in VBA
There are many different ways you can use to refer to a worksheet in VBA.
Understanding how to refer to worksheets would help you write better code, especially when you’re using loops in your VBA code.
Using the Worksheet Name
The easiest way to refer to a worksheet is to use its name.
For example, suppose you have a workbook with three worksheets – Sheet 1, Sheet 2, Sheet 3.
And you want to activate Sheet 2.
You can do that using the following code: Sub ActivateSheet() Worksheets("Sheet2").Activate End Sub
The above code asks VBA to refer to Sheet2 in the Worksheets collection and activate it.
Since we are using the exact sheet name, you can also use the Sheets collection here. So the below code would also do that same thing.
Sub ActivateSheet() Sheets("Sheet2").Activate End Sub
Using the Index Number
While using the sheet name is an easy way to refer to a worksheet, sometimes, you may not know the exact name of the worksheet.
For example, if you’re using a VBA code to add a new worksheet to the workbook, and you don’t know how many worksheets are already there, you would not know the name of the new worksheet.
In this case, you can use the index number of the worksheets.
Suppose you have the following sheets in a workbook:
The below code would activate Sheet2:
Sub ActivateSheet() Worksheets(2).Activate End Sub
Note that we have used index number 2 in Worksheets(2). This would refer to the second object in the collection of the worksheets.
Now, what happens when you use 3 as the index number?
It will select Sheet3.
If you’re wondering why it selected Sheet3, as it’s clearly the fourth object.
This happens because a chart sheet is not a part of the worksheets collection.
So when we use the index numbers in the Worksheets collection, it will only refer to the worksheets in the workbook (and ignore the chart sheets).
On the contrary, if you’re using Sheets, Sheets(1) would refer to Sheets1, Sheets(2) would refer to Sheet2, Sheets(3) would refer to Chart1 and Sheets(4) would refer to Sheet3.
This technique of using index number is useful when you want to loop through all the worksheets in a workbook. You can count the number of worksheets and then loop through these using this count (we will see how to do this later in this tutorial).
Note: The index number goes from left to right. So if you shift Sheet2 to the left of Sheet1, then Worksheets(1) would refer to Sheet2.
Using the Worksheet Code Name
One of the drawbacks of using the sheet name (as we saw in the section above) is that a user can change it.
And if the sheet name has been changed, your code wouldn’t work until you change the name of the worksheet in the VBA code as well.
To tackle this problem, you can use the code name of the worksheet (instead of the regular name that we have been using so far). A code name can be assigned in the VB Editor and doesn’t change when you change the name of the sheet from the worksheet area.
To give your worksheet a code name, follow the below steps:
- Click the Developer tab.
- Click the Visual Basic button. This will open the VB Editor.
- Click the View option in the menu and click on Project Window. This will make the Properties pane visible. If the Properties pane is already visible, skip this step.
- Click on the sheet name in the project explorer that you want to rename.
- In the Properties pane, change the name in the field in front of (Name). Note that you can’t have spaces in the name.
The above steps would change the name of your Worksheet in the VBA backend. In the Excel worksheet view, you can name the worksheet whatever you want, but in the backend, it will respond to both the names – the sheet name and the code name.
In the above image, the sheet name is ‘SheetName’ and the code name is ‘CodeName’. Even if you change the sheet name on the worksheet, the code name still remains the same.
Now, you can use either the Worksheets collection to refer to the worksheet or use the codename.
For example, both the line will activate the worksheet.
Worksheets("Sheetname").Activate CodeName.Activate
The difference in these two is that if you change the name of the worksheet, the first one wouldn’t work. But the second line would continue to work even with the changed name. The second line (using the CodeName) is also shorter and easier to use.
Referring to a Worksheet in a Different Workbook
If you want to refer to a worksheet in a different workbook, that workbook needs to be open while the code runs, and you need to specify the name of the workbook and the worksheet that you want to refer to.
For example, if you have a workbook with the name Examples and you want to activate Sheet1 in the Example workbook, you need to use the below code:
Sub SheetActivate() Workbooks("Examples.xlsx").Worksheets("Sheet1").Activate End Sub
Note that if the workbook has been saved, you need to use the file name along with the extension. If you’re not sure what name to use, take help from Project Explorer.
In case the workbook has not been saved, you don’t need to use the file extension.
Adding a Worksheet
The below code would add a worksheet (as the first worksheet – i.e., as the leftmost sheet in the sheet tab).
Sub AddSheet() Worksheets.Add End Sub
It takes the default name Sheet2 (or any other number based on how many sheets are already there).
If you want a worksheet to be added before a specific worksheet (say Sheet2), then you can use the below code.
Sub AddSheet() Worksheets.Add Before:=Worksheets("Sheet2") End Sub
The above code tells VBA to add a sheet and then uses the ‘Before’ statement to specify the worksheet before which the new worksheet should to be inserted.
Similarly, you can also add a sheet after a worksheet (say Sheet2), using the below code:
Sub AddSheet() Worksheets.Add After:=Worksheets("Sheet2") End Sub
If you want the new sheet to be added to the end of the sheets, you need to first know how many sheets are there. The following code first counts the number of sheets, and the adds the new sheet after the last sheet (to which we refer using the index number).
Sub AddSheet() Dim SheetCount As Integer SheetCount = Worksheets.Count Worksheets.Add After:=Worksheets(SheetCount) End Sub
Deleting a Worksheet
The below code would delete the active sheet from the workbook.
Sub DeleteSheet() ActiveSheet.Delete End Sub
The above code would show a warning prompt before deleting the worksheet.
If you don’t want to see the warning prompt, use the below code:
Sub DeleteSheet() Application.DisplayAlerts = False ActiveSheet.Delete Application.DisplayAlerts = True End Sub
When Application.DisplayAlerts is set to False, it will not show you the warning prompt. If you use it, remember to set it back to True at the end of the code.
Remember that you can’t undo this delete, so use the above code when you’re absolutely sure.
If you want to delete a specific sheet, you can do that using the following code:
Sub DeleteSheet() Worksheets("Sheet2").Delete End Sub
You can also use the code name of the sheet to delete it.
Sub DeleteSheet() Sheet5.Delete End Sub
Renaming the Worksheets
You can modify the name property of the Worksheet to change its name.
The following code will change the name of Sheet1 to ‘Summary’.
Sub RenameSheet() Worksheets("Sheet1").Name = "Summary" End Sub
You can combine this with the adding sheet method to have a set of sheets with specific names.
For example, if you want to insert four sheets with the name 2018 Q1, 2018 Q2, 2018 Q3, and 2018 Q4, you can use the below code.
Sub RenameSheet() Dim Countsheets As Integer Countsheets = Worksheets.Count For i = 1 To 4 Worksheets.Add after:=Worksheets(Countsheets + i - 1) Worksheets(Countsheets + i).Name = "2018 Q" & i Next i End Sub
In the above code, we first count the number of sheets and then use a For Next loop to insert new sheets at the end. As the sheet is added, the code also renames it.
Assigning Worksheet Object to a Variable
When working with worksheets, you can assign a worksheet to an object variable, and then use the variable instead of the worksheet references.
For example, if you want to add a year prefix to all the worksheets, instead of counting the sheets and the running the loop that many numbers of times, you can use the object variable.
Here is the code that will add 2018 as a prefix to all the worksheet’s names.
Sub RenameSheet() Dim Ws As Worksheet For Each Ws In Worksheets Ws.Name = "2018 - " & Ws.Name Next Ws End Sub
The above code declares a variable Ws as the worksheet type (using the line ‘Dim Ws As Worksheet’).
Now, we don’t need to count the number of sheets to loop through these. Instead, we can use ‘For each Ws in Worksheets’ loop. This will allow us to go through all the sheets in the worksheets collection. It doesn’t matter whether there are 2 sheets or 20 sheets.
While the above code allows us to loop through all the sheets, you can also assign a specific sheet to a variable.
In the below code, we assign the variable Ws to Sheet2 and use it to access all of Sheet2’s properties.
Sub RenameSheet() Dim Ws As Worksheet Set Ws = Worksheets("Sheet2") Ws.Name = "Summary" Ws.Protect End Sub
Once you set a worksheet reference to an object variable (using the SET statement), that object can be used instead of the worksheet reference. This can be helpful when you have a long complicated code and you want to change the reference. Instead of making the change everywhere, you can simply make the change in the SET statement.
Note that the code declares the Ws object as the Worksheet type variable (using the line Dim Ws as Worksheet).
Hide Worksheets Using VBA (Hidden + Very Hidden)
Hiding and Unhiding worksheets in Excel is a straightforward task.
You can hide a worksheet and the user would not see it when he/she opens the workbook. However, they can easily unhide the worksheet by right-clicking on any sheet tab.
But what if you don’t want them to be able to unhide the worksheet(s).
You can do this using VBA.
The code below would hide all the worksheets in the workbook (except the active sheet), such that you can not unhide it by right-clicking on the sheet name.
Sub HideAllExcetActiveSheet() Dim Ws As Worksheet For Each Ws In ThisWorkbook.Worksheets If Ws.Name <> ActiveSheet.Name Then Ws.Visible = xlSheetVeryHidden Next Ws End Sub
In the above code, the Ws.Visible property is changed to xlSheetVeryHidden.
- When the Visible property is set to xlSheetVisible, the sheet is visible in the worksheet area (as worksheet tabs).
- When the Visible property is set to xlSheetHidden, the sheet is hidden but the user can unhide it by right-clicking on any sheet tab.
- When the Visible property is set to xlSheetVeryHidden, the sheet is hidden and cannot be unhidden from worksheet area. You need to use a VBA code or the properties window to unhide it.
If you want to simply hide sheets, that can be unhidden easily, use the below code:
Sub HideAllExceptActiveSheet() Dim Ws As Worksheet For Each Ws In ThisWorkbook.Worksheets If Ws.Name <> ActiveSheet.Name Then Ws.Visible = xlSheetHidden Next Ws End Sub
The below code would unhide all the worksheets (both hidden and very hidden).
Sub UnhideAllWoksheets() Dim Ws As Worksheet For Each Ws In ThisWorkbook.Worksheets Ws.Visible = xlSheetVisible Next Ws End Sub
Related Article: Unhide All Sheets In Excel (at one go)
Hide Sheets Based on the Text in it
Suppose you have multiple sheets with the name of different departments or years and you want to hide all the sheets except the ones that have the year 2018 in it.
You can do this using a VBA INSTR function.
The below code would hide all the sheets except the ones with the text 2018 in it.
Sub HideWithMatchingText() Dim Ws As Worksheet For Each Ws In Worksheets If InStr(1, Ws.Name, "2018", vbBinaryCompare) = 0 Then Ws.Visible = xlSheetHidden End If Next Ws End Sub
In the above code, the INSTR function returns the position of the character where it finds the matching string. If it doesn’t find the matching string, it returns 0.
The above code checks whether the name has the text 2018 in it. If it does, nothing happens, else the worksheet is hidden.
You can take this a step further by having the text in a cell and using that cell in the code. This will allow you to have a value in the cell and then when you run the macro, all the sheets, except the one with the matching text in it, would remain visible (along with the sheets where you’re entering the value in the cell).
Sorting the Worksheets in an Alphabetical Order
Using VBA, you can quickly sort the worksheets based on their names.
For example, if you have a workbook that has sheets for different department or years, then you can use the below code to quickly sort these sheets in an ascending order.
Sub SortSheetsTabName() Application.ScreenUpdating = False Dim ShCount As Integer, i As Integer, j As Integer ShCount = Sheets.Count For i = 1 To ShCount - 1 For j = i + 1 To ShCount If Sheets(j).Name < Sheets(i).Name Then Sheets(j).Move before:=Sheets(i) End If Next j Next i Application.ScreenUpdating = True End Sub
Note that this code works well with text names and in most of the cases with years and numbers too. But it can give you the wrong results in case you have the sheet names as 1,2,11. It will sort and give you the sequence 1, 11, 2. This is because it does the comparison as text and considers 2 bigger than 11.
Protect/Unprotect All the Sheets at One Go
If you have a lot of worksheets in a workbook and you want to protect all the sheets, you can use the VBA code below.
It allows you to specify the password within the code. You will need this password to unprotect the worksheet.
Sub ProtectAllSheets() Dim ws As Worksheet Dim password As String password = "Test123" 'replace Test123 with the password you want For Each ws In Worksheets ws.Protect password:=password Next ws End Sub
The following code would unprotect all the sheets in one go.
Sub ProtectAllSheets() Dim ws As Worksheet Dim password As String password = "Test123" 'replace Test123 with the password you used while protecting For Each ws In Worksheets ws.Unprotect password:=password Next ws End Sub
Creating a Table of Contents of All Worksheets (with Hyperlinks)
If you have a set of worksheets in the workbook and you want to quickly insert a summary sheet which has the links to all the sheets, you can use the below code.
Sub AddIndexSheet() Worksheets.Add ActiveSheet.Name = "Index" For i = 2 To Worksheets.Count ActiveSheet.Hyperlinks.Add Anchor:=Cells(i - 1, 1), _ Address:="", SubAddress:=Worksheets(i).Name & "!A1", _ TextToDisplay:=Worksheets(i).Name Next i End Sub
The above code inserts a new worksheet and names it Index.
It then loops through all the worksheets and creates a hyperlink for all the worksheets in the Index sheet.
Where to Put the VBA Code
Wondering where the VBA code goes in your Excel workbook?
Excel has a VBA backend called the VBA editor. You need to copy and paste the code into the VB Editor module code window.
Here are the steps to do this:
- Go to the Developer tab.
- Click on the Visual Basic option. This will open the VB editor in the backend.
- In the Project Explorer pane in the VB Editor, right-click on any object for the workbook in which you want to insert the code. If you don’t see the Project Explorer go to the View tab and click on Project Explorer.
- Go to Insert and click on Module. This will insert a module object for your workbook.
- Copy and paste the code in the module window.
You May Also Like the Following Excel VBA Tutorials:
- Working with Workbooks using VBA.
- Using IF Then Else Statements in VBA.
- For Next Loop in VBA.
- Creating a User-Defined Function in Excel.
- How to Record a Macro in Excel.
- How to Run a Macro in Excel.
- Excel VBA Events – An Easy (and Complete) Guide.
- How to Create an Add-in in Excel.
- How to Save and Reuse Macro using Excel Personal Macro Workbook.
- Using Active Cell in VBA in Excel (Examples)
- How to Open Excel Files Using VBA (Examples)
Excel VBA Worksheets
Excel is a workbook. In that workbook, it contains worksheets or sheets. Understanding the concept of Worksheets in VBA is important because we all work with worksheets. In a normal Excel file, we call it sheets, but in VBA terminology, it is called a “Worksheet.” All the collections of a worksheet are called “Worksheets.”
In VBA, a Worksheet is an object. Therefore, there are two ways of referring to the worksheet, one using the “Worksheet” object and another using the “Sheets” object.
We know your question is what the difference between them is. We can see two sheets in Excel: regular worksheets and chart sheets.
The “worksheet” tab in excel considers only the worksheets in the workbook except for chart sheets. On the other hand, “Sheets” considers all the worksheets in the workbook, including the chart sheet. For example, look at the below image.
In the above, we have a total of 5 sheets. Of these 5 sheets, 3 are worksheets, and 2 are chart sheets.
Here, the “Worksheet” count is 3, and the “Sheets” count is 2.
Now, look at the below image.
All the sheets are worksheets, so the count of both “Worksheets” and “Sheets” is 3.
So, as part of the code, if you want to use worksheets, and objects, remember this point.
Table of contents
- Excel VBA Worksheets
- Syntax of VBA Worksheets
- How to use Worksheets Object in VBA?
- Example #1
- Example #2 – Select Worksheets by Name
- Example #3 – Problem with Worksheet Name
- Example #4 – Get the Count of Total Sheets in the Workbook
- Example #5 – Methods Using Worksheet Object
- Recommended Articles
Syntax of VBA Worksheets
As we said, the worksheet is an object variable. However, this has syntax too.
The index is nothing that is the worksheet number we are referring to. However, as you can see in the end, it is referred to as an Object.
For example, Worksheet(1).Select means to select the first worksheet of the workbook. It doesn’t matter what the worksheet’s name is; whatever the worksheet inserted first in the workbook will be selected.
We can also refer to the worksheet by its name. We need to mention the complete as it is a worksheet name in double quotes.
For example, Worksheet(“Sales Sheet”).Select means select the sheet named “Sales Sheet.” Here it doesn’t matter what the number of the worksheet it always selects is.
How to use Worksheets Object in VBA?
You can download this VBA Worksheet Object Template here – VBA Worksheet Object Template
Example #1
Assume you have a total of 5 sheets in your workbook. The name of those worksheets is “Worksheet 1”, “Worksheet 2”, “Worksheet 3”, “Chart Sheet 1”, and “Chart Sheet 2.”
If we use the numbering to select the worksheet, then we can use the number as the worksheet reference.
Worksheet(2). Select means it will select the second worksheet of the workbook.
Code:
Sub Worksheet_Example1() Worksheets(2).Select End Sub
We will run this code using the F5 key or manually and see the result.
Now, we will change the sheet number to 3.
Code:
Sub Worksheet_Example1() Worksheets(3).Select End Sub
Now, see what happens when you run the code manually or using the F5 key code.
If you look at the above image, it selected the 4th worksheet when we asked to select the 3rd one.
That is because we have used the Worksheet object, not the Sheets object. As we told earlier, the “Worksheets” object considers only worksheets, not chart sheets.
Use the Sheets object to select the third sheet of all the sheets in the workbook.
Code:
Sub Worksheet_Example1()
Sheets(3).Select
End Sub
Now, it will select the exact third sheet.
Example #2 – Select Worksheets by Name
Selecting the sheets by their name is an accurate way of referring to the sheet. For example, if we want to select the sheet “Worksheet 3,” you can use the code below.
Code:
Sub Worksheet_Example2() Worksheets("Worksheet 3").Select End Sub
It will select the exact sheet. It doesn’t matter where placed in the workbook.
But if you try to access the chart sheet with the “Worksheets” object, we will get a “Subscript out of range errorSubscript out of range is an error in VBA that occurs when we attempt to reference something or a variable that does not exist in the code. For example, if we do not have a variable named x but use the msgbox function on x, we will receive a subscript out of range error.read more.”
Code:
Sub Worksheet_Example2() Worksheets("Chart Sheet 1").Select End Sub
Run this code through the F5 key or manually and see the result.
Example #3 – Problem with Worksheet Name
There is one more problem with referring to the sheets by their name. If someone changes the worksheet’s name, we will get the “Subscript out of range error.”
To solve this issue go to the basic visual editor by pressing the ALT + F11 key.
Select the sheet name and press the F4 key to see the “Properties” window.
The window changes the worksheet’s name to your name in these properties.
One interesting thing is that even though we have changed the worksheet’s name from “Worksheet 1” to “WS1,” we can still see the same name in the workbook.
Now, we can refer to this sheet by the “WS1” name.
Code:
Sub Worksheet_Example2() Worksheets("WS1").Select End Sub
Now, it doesn’t matter who changes the name of the worksheet. Still, our code refers to the same sheet as long as it is not changing in the Visual Basic Editor.
Example #4 – Get the Count of Total Sheets in the Workbook
A worksheet is an object. We can use all the properties and methods associated with it. So what do we do with worksheets?
We insert worksheets. We rename worksheets. We delete worksheets and many other things we do with them.
Enter the object “Worksheets” and put a dot to see all the options with them.
To get the count of the worksheets, use VBA Count PropertyThe count function in VBA counts how many cells have values in them. Cells with numbers or text enclosed in double quotes are counted, as are those whose values are typed directly. However, cells that contain random data that Excel is unable to translate are not counted.read more.
Code:
Sub Worksheet_Example3() Dim i As Long i = Worksheets.Count MsgBox i End Sub
It will show the count of the worksheets.
Even though there are 5 sheets, we got the count as 3 because the other 2 sheets are chart sheets.
To get the overall count of sheets, use the “Sheets” object.
Code:
Sub Worksheet_Example3() Dim i As Long i = Sheets.Count MsgBox i End Sub
It will show the full count of the sheets.
Example #5 – Methods Using Worksheet Object
After entering the worksheet object, we can access all the associated properties and objects. For example, we can add a new sheet. We can delete, etc.
To Add New Sheet.
Worksheet.Add
To Delete Worksheet
Worksheet(“Sheet Name”).Delete
To Change the Name of the Worksheet
Worksheet(“Sheet Name”).Name = “New Name”
Recommended Articles
This article has been a guide to VBA Worksheets. Here, we learn how to use the VBA Worksheet object to find, select, and get the count of total worksheets in Excel, along with some simple to advanced examples. Below are some useful Excel articles related to VBA: –
- GetObject in VBA
- VBA Delete All Excel Files
- Excel VBA Worksheet Function
- VBA New Line