Home / VBA / How to COUNT Sheets using VBA in Excel
In Excel, if you have many sheets, you can use a VBA code to count them quickly instead of manually counting or using any formula. So, in the post, we will see different ways to do count sheets from a workbook.
Count Sheets from the Active Workbook
Following is the code that you need to use to count the sheet from the active workbook.
ThisWorkbook.Sheets.Count
In this code, first, you have the referred to the active workbook using the “ThisWorkbook” and refer to all the sheet, in the end, use the count method to count all the sheets. And if you want to count the worksheets instead of sheets, then use the following code.
ThisWorkbook.Worksheets.Count
Helpful Links: Run a Macro – Macro Recorder – Visual Basic Editor – Personal Macro Workbook
Count Sheets from a Different Workbook
You can use the name of the workbook to refer to and then count the sheets from it. Let’s say you want to count the sheets from the workbook “Book1”.
Here’s the code.
Workbooks("sample-file.xlsx").Sheets.Count
This code gives you the count of the sheets that you have in the workbook “sample-file.xlsx“. There is one thing that you need to take this workbook needs to be open.
Count Sheets from All the Open Workbooks
You might have more than one workbook that is open at the same time, and you can count all the sheets from all those workbooks.
Sub vba_loop_all_sheets()
Dim wb As Workbook
Dim i As Long
For Each wb In Application.Workbooks
If wb.Name <> "PERSONAL.XLSB" Then
i = i + wb.Sheets.Count
End If
Next wb
MsgBox "Total sheets in all the open workbooks: " & i
End Sub
Count Sheets from a Closed Workbook
Now here we have a code that refers to the workbook that is saved on my system’s desktop. When I run this code it opens that workbook at the backend and counts the sheets from it and then adds that count to cell A1.
Sub vba_count_sheets()
Dim wb As Workbook
Application.DisplayAlerts = False
Set wb = Workbooks.Open("C:UsersDellDesktopsample-file.xlsx")
ThisWorkbook.Sheets(1).Range("A1").Value _
= wb.Sheets.Count
wb.Close SaveChanges:=True
Application.DisplayAlerts = True
End Sub
We have turned OFF the display alerts to open and close the file at the backend.
More Tutorials on VBA Worksheets
- Back to VBA Worksheet / VBA Tutorial
There are some simple things that are not possible for you to do with in-built functions and functionalities in Excel, but can easily be done using VBA.
Counting the total number of sheets in the active workbook or any other workbook on your system is an example of such a task.
In this tutorial, I’ll show you some simple VBA code that you can use to count the total number of sheets in an Excel workbook.
Count All Sheets in the Workbook
There are multiple ways I can use VBA to give me the total count of sheets in a workbook.
In the following sections, I will show you three different methods, and you can choose which one to use:
- Using the VBA code in a module (to get sheet count as a message box)
- Using Immediate window
- Using a Custom Formula (which will give you the sheet count in a cell in the worksheet)
VBA Code to Show Sheet Count in a Message Box
Below is the VBA code to get the total number of sheets in the current workbook shown in a message box:
Sub SheetCount() MsgBox ThisWorkbook.Sheets.Count End Sub
In the above code, I have used Sheets, which will count all the sheets (be it worksheets or chart sheets). In case you only want to count the total number of worksheets, use Worksheets instead of Sheets. In most cases, people only use worksheets, using Sheets works fine. In layman terms, Sheets = Worksheets + Chart Sheets
Below are the steps to put this code in the VBA Backend:
- Click the Develope tab in the ribbon (don’t see the Developer tab – click here to know how to get it)
- Click on Visual Basic icon
- In the Visual Basic Editor that opens, click on ‘Insert’ option in the menu
- Click on Module. This will insert a new module for the workbook
- Copy and Paste the above VBA code in the code window of the module
- Place the cursor anywhere in the code and press the F5 key (or click the green play button in the toolbar)
The above steps would run the code and you will see a message box that shows the total number of worksheets in the workbook.
Note: If you want to keep this code and reuse it in the future in the same workbook, you need to save the Excel file as a macro-enabled file (with a .XLSM extension). You will see this option when you try to save this file.
Getting Sheet Count Result in Immediate Window
The Immediate window gives you the result right there with a single line of code.
Below are the steps to get the count of sheets in the workbook using the immediate window:
- Click the Develope tab in the ribbon (don’t see the Developer tab – click here to know how to get it)
- Click on Visual Basic icon
- In the VB Editor that opens, you might see the Immediate Window already. If you don’t, click the ‘View’ option in the menu and then click on Immediate Window (or use the keyboard shortcut – Control + G)
- Copy and paste the following line of code: ? ThisWorkbook.Sheets.Count
- Place the cursor at the end of the code line and hit enter.
When you hit enter in Step 5, it executes the code and you get the result in the next line in the immediate window itself.
Formula to Get Sheet Count in the Worksheet
If you want to get the sheet count in a cell in any worksheet, using the formula method is the best way.
In this method, I will create a custom formula that will give me the total number of sheets in the workbook.
Below is the code that will do this:
Function SheetCount()
SheetCount = ThisWorkbook.Sheets.Count
End Function
You need to place this code in the module (just like the way I showed in the ” VBA Code to Show Sheet Count in a Message Box” section)
Once you have the code in the module, you can get the sheet count by using the below formula in any cell in the workbook:
=SheetCount()
Pro Tip: If you need to get the sheet count value often, I would recommend copying and pasting this formula VBA code in the Personal Macro Workbook. When you save a VBA code in the Personal Macro Workbook, it can be used on any Excel file on your system. In short, VBA codes in PMW are always available to you on your system.
Count All Sheets in Another Workbook (Open or Closed)
In the above example, I showed you how to count the number of sheets in the active workbook (the one where you’re working and where you added the VBA codes).
You can also tweak the code a little to get the sheet count in other workbooks (whether open or closed).
Sheet Count in Another Open Workbook
Suppose I want to know the sheet count of an already open workbook – Example.xlsx
The below VBA code with do this:
Sub SheetCount() MsgBox Workbooks("Example.xlsx").Sheets.Count End Sub
And in case you want to get the result in the immediate window, you can use the below code.
? Workbooks("Example.xlsx").Sheets.Count
Sheet Count from a Closed Workbook
In case you need to get the sheet count of a file that’s closed, you either need to open it and then use the above codes, or you can use VBA to first open the file, then count the sheets in it, and then close it.
The first step would be to get the full file location of the Excel file. In this example, my file location is “C:UserssumitOneDriveDesktopTestExample File.xlsx”
You can get the full file path by right-clicking on the file and then clicking on the Copy Path option (or click on the Properties option).
Below are the VBA codes to get the sheet count from the closed workbook:
Sub SheetCount()
Application.DisplayAlerts = False
Set wb = Workbooks.Open("C:UserssumitOneDriveDesktopTestExample File.xlsx")
ShCount = wb.Sheets.Count
wb.Close SaveChanges:=True
Application.DisplayAlerts = True
MsgBox ShCount
End Sub
The above code first opens the workbook, then counts the total number of sheets in it, and then closes the workbook.
Since the code needs to do some additional tasks (apart from counting the sheets), it has some extra lines of code in it.
The Application.DisplayAlerts = False part of the code makes sure that the process of opening a file, counting the sheets, and then closing the file is not visible to the user. This line stops the alerts of the Excel application. And at the end of the code, we set it back to True, so things get back to normal and we see the alerts from thereon.
Count All Sheets that Have a Specific Word In It
One useful scenario of counting sheets would be when you have a lot of sheets in a workbook, and you only want to count the number of sheets that have a specific word in them.
For example, suppose you have a large workbook that has sheets for multiple departments in your company, and you only want to know the sheet count of the sales department sheets.
Below is the VBA code that will only give you the number of sheets that have the word ‘Sales’ in it
Sub SheetCount()
Dim shCount As Long
For Each sh In ThisWorkbook.Worksheets
If InStr(1, sh.Name, "Sales", vbBinaryCompare) > 0 Then
shCount = shCount + 1
End If
Next sh
MsgBox shCount
End Sub
Note that the code is case-sensitive, so ‘Sales’ and ‘sales’ would be considered different words.
The above uses an IF condition to check the name of each sheet, and if the name of the sheet contains the specified word (which is checked using the INSTR function), it counts it, else it doesn’t.
So these are some simple VBA codes that you can use to quickly get a count of sheets in any workbook.
I hope you found this tutorial useful!
Other Excel tutorials you may also find useful:
- How to Insert New Worksheet in Excel (Easy Shortcuts)
- How to Group Worksheets in Excel
- How to Get the Sheet Name in Excel? Easy Formula
- How to Sort Worksheets in Excel using VBA (alphabetically)
- How to Delete Sheets in Excel (Shortcuts + VBA)
- How to Rename a Sheet in Excel (4 Easy Ways + Shortcut)
- Excel Tabs/Sheets Not Showing – How to Fix?
In this post, you’ll learn how to count numbers of sheets in a Excel Workbook using Excel VBA.
To run the Excel VBA, You will need do the following first,
- Under the Developer tab, Click Visual basics
- Click on the insert option and click the module
- Enter the codes and run it.
To count the total number of sheets in a workbook using the Excel VBA command:
Code:
Put this in a module:
Public Sub CountSheets() MsgBox Application.Sheets.Count End Sub
Count Sheets from the Active Workbook
To count the sheet from the active workbook:
Code
ThisWorkbook.Sheets.Count
To count the worksheets instead of sheets, then use the following code.
Code
ThisWorkbook.Worksheets.Count
Count Sheets from a Different Workbook
To count sheets from a different Workbook(excel file)
Code
Workbooks("Name of the file.xlsx").Sheets.Count
Count Sheets from All the Open Workbooks
To count sheets from all the open workbooks
Code
Sub vba_loop_all_sheets() Dim wb As Workbook Dim i As Long For Each wb In Application.Workbooks If wb.Name <> "Book1.XLSB" Then i = i + wb.Sheets.Count End If Next wb MsgBox "Total sheets in all the open workbooks: " & i End Sub
Содержание
- VBA-Урок 3. Коллекция Sheets
- Как посчитать количество листов в книге
- Как добавить лист в книгу
- Как скрыть лист
- VBA – Count the Sheets in a Workbook
- Application.Sheets.Count – Count Worksheets
- VBA Coding Made Easy
- VBA Code Examples Add-in
- VBA Code Generator
- AutoMacro: VBA Add-in with Hundreds of Ready-To-Use VBA Code Examples & much more!
- What is AutoMacro?
- Count Sheets in Excel (using VBA)
- Count All Sheets in the Workbook
- VBA Code to Show Sheet Count in a Message Box
- Getting Sheet Count Result in Immediate Window
- Formula to Get Sheet Count in the Worksheet
- Count All Sheets in Another Workbook (Open or Closed)
- Sheet Count in Another Open Workbook
- Sheet Count from a Closed Workbook
- Count All Sheets that Have a Specific Word In It
- How to COUNT Sheets using VBA in Excel
- Count Sheets from the Active Workbook
- Count Sheets from a Different Workbook
- Count Sheets from All the Open Workbooks
- Count Sheets from a Closed Workbook
- How to Count the Number of Sheets in a Workbook
- Count the Number of Sheets with Define Name
- Count the Number of Sheets with VBA Macro
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 вы можете убрать или отобразить необходимый лист.
Источник
VBA – Count the Sheets in a Workbook
Application.Sheets.Count – Count Worksheets
If you ever need to count the number of sheets in a workbook, use the VBA command: Application.Sheets.Count
Put this in a module:
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!
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.
(No installation required!)
VBA Code Generator
AutoMacro: VBA Add-in with Hundreds of Ready-To-Use VBA Code Examples & much more!
What is AutoMacro?
AutoMacro is an add-in for VBA that installs directly into the Visual Basic Editor. It comes loaded with code generators, an extensive code library, the ability to create your own code library, and many other time-saving tools and utilities that add much needed functionality to the outdated VBA Editor.
Источник
Count Sheets in Excel (using VBA)
There are some simple things that are not possible for you to do with in-built functions and functionalities in Excel, but can easily be done using VBA.
Counting the total number of sheets in the active workbook or any other workbook on your system is an example of such a task.
In this tutorial, I’ll show you some simple VBA code that you can use to count the total number of sheets in an Excel workbook.
This Tutorial Covers:
Count All Sheets in the Workbook
There are multiple ways I can use VBA to give me the total count of sheets in a workbook.
In the following sections, I will show you three different methods, and you can choose which one to use:
- Using the VBA code in a module (to get sheet count as a message box)
- Using Immediate window
- Using a Custom Formula (which will give you the sheet count in a cell in the worksheet)
VBA Code to Show Sheet Count in a Message Box
Below is the VBA code to get the total number of sheets in the current workbook shown in a message box:
In the above code, I have used Sheets, which will count all the sheets (be it worksheets or chart sheets). In case you only want to count the total number of worksheets, use Worksheets instead of Sheets. In most cases, people only use worksheets, using Sheets works fine. In layman terms, Sheets = Worksheets + Chart Sheets
Below are the steps to put this code in the VBA Backend:
- Click the Develope tab in the ribbon (don’t see the Developer tab – click here to know how to get it)
- In the Visual Basic Editor that opens, click on ‘Insert’ option in the menu
- Click on Module. This will insert a new module for the workbook
- Copy and Paste the above VBA code in the code window of the module
- Place the cursor anywhere in the code and press the F5 key (or click the green play button in the toolbar)
The above steps would run the code and you will see a message box that shows the total number of worksheets in the workbook.
Note: If you want to keep this code and reuse it in the future in the same workbook, you need to save the Excel file as a macro-enabled file (with a .XLSM extension). You will see this option when you try to save this file.
Getting Sheet Count Result in Immediate Window
The Immediate window gives you the result right there with a single line of code.
Below are the steps to get the count of sheets in the workbook using the immediate window:
- Click the Develope tab in the ribbon (don’t see the Developer tab – click here to know how to get it)
- Click on Visual Basic icon
- In the VB Editor that opens, you might see the Immediate Window already. If you don’t, click the ‘View’ option in the menu and then click on Immediate Window (or use the keyboard shortcut – Control + G)
- Copy and paste the following line of code: ? ThisWorkbook.Sheets.Count
- Place the cursor at the end of the code line and hit enter.
When you hit enter in Step 5, it executes the code and you get the result in the next line in the immediate window itself.
Formula to Get Sheet Count in the Worksheet
If you want to get the sheet count in a cell in any worksheet, using the formula method is the best way.
In this method, I will create a custom formula that will give me the total number of sheets in the workbook.
Below is the code that will do this:
You need to place this code in the module (just like the way I showed in the ” VBA Code to Show Sheet Count in a Message Box” section)
Once you have the code in the module, you can get the sheet count by using the below formula in any cell in the workbook:
Pro Tip: If you need to get the sheet count value often, I would recommend copying and pasting this formula VBA code in the Personal Macro Workbook. When you save a VBA code in the Personal Macro Workbook, it can be used on any Excel file on your system. In short, VBA codes in PMW are always available to you on your system.
Count All Sheets in Another Workbook (Open or Closed)
In the above example, I showed you how to count the number of sheets in the active workbook (the one where you’re working and where you added the VBA codes).
You can also tweak the code a little to get the sheet count in other workbooks (whether open or closed).
Sheet Count in Another Open Workbook
Suppose I want to know the sheet count of an already open workbook – Example.xlsx
The below VBA code with do this:
And in case you want to get the result in the immediate window, you can use the below code.
Sheet Count from a Closed Workbook
In case you need to get the sheet count of a file that’s closed, you either need to open it and then use the above codes, or you can use VBA to first open the file, then count the sheets in it, and then close it.
The first step would be to get the full file location of the Excel file. In this example, my file location is “C:UserssumitOneDriveDesktopTestExample File.xlsx”
You can get the full file path by right-clicking on the file and then clicking on the Copy Path option (or click on the Properties option).
Below are the VBA codes to get the sheet count from the closed workbook:
The above code first opens the workbook, then counts the total number of sheets in it, and then closes the workbook.
Since the code needs to do some additional tasks (apart from counting the sheets), it has some extra lines of code in it.
The Application.DisplayAlerts = False part of the code makes sure that the process of opening a file, counting the sheets, and then closing the file is not visible to the user. This line stops the alerts of the Excel application. And at the end of the code, we set it back to True, so things get back to normal and we see the alerts from thereon.
Count All Sheets that Have a Specific Word In It
One useful scenario of counting sheets would be when you have a lot of sheets in a workbook, and you only want to count the number of sheets that have a specific word in them.
For example, suppose you have a large workbook that has sheets for multiple departments in your company, and you only want to know the sheet count of the sales department sheets.
Below is the VBA code that will only give you the number of sheets that have the word ‘Sales’ in it
Note that the code is case-sensitive, so ‘Sales’ and ‘sales’ would be considered different words.
The above uses an IF condition to check the name of each sheet, and if the name of the sheet contains the specified word (which is checked using the INSTR function), it counts it, else it doesn’t.
So these are some simple VBA codes that you can use to quickly get a count of sheets in any workbook.
I hope you found this tutorial useful!
Other Excel tutorials you may also find useful:
Источник
How to COUNT Sheets using VBA in Excel
In Excel, if you have many sheets, you can use a VBA code to count them quickly instead of manually counting or using any formula. So, in the post, we will see different ways to do count sheets from a workbook.
Count Sheets from the Active Workbook
Following is the code that you need to use to count the sheet from the active workbook.
In this code, first, you have the referred to the active workbook using the “ThisWorkbook” and refer to all the sheet, in the end, use the count method to count all the sheets. And if you want to count the worksheets instead of sheets, then use the following code.
Count Sheets from a Different Workbook
You can use the name of the workbook to refer to and then count the sheets from it. Let’s say you want to count the sheets from the workbook “Book1”.
This code gives you the count of the sheets that you have in the workbook “sample-file.xlsx“. There is one thing that you need to take this workbook needs to be open.
Count Sheets from All the Open Workbooks
You might have more than one workbook that is open at the same time, and you can count all the sheets from all those workbooks.
Count Sheets from a Closed Workbook
Now here we have a code that refers to the workbook that is saved on my system’s desktop. When I run this code it opens that workbook at the backend and counts the sheets from it and then adds that count to cell A1.
We have turned OFF the display alerts to open and close the file at the backend.
Источник
How to Count the Number of Sheets in a Workbook
This post will guide you how to count the number of sheets in a workbook in Excel. How do I count the number of worksheets in a workbook with VBA Macro in Excel.
- Count the Number of Sheets with Define Name
- Count the Number of Sheets with VBA Macro
- Video: Count the Number of Sheets
Count the Number of Sheets with Define Name
If you want to count the number of worksheets in a given workbook in Excel, you can use the Defined Name and a Formula to achieve it. Just do the following steps:
#1 go to Formula tab, click Define Name command under Defined Names group, and the New Name dialog will open.
#2 type one defined name in the Name text box, such as: countWorksheets, and then type the formula =GET.WORKBOOK(1)&T(NOW()) into the text box of Refers to. Click Ok button.
#3 Type the following formula based on the COUNTA function and the INDEX function to get the number of worksheets in the current workbook. And press Enter key in your keyboard, you will get the number of worksheets in your workbook.
Count the Number of Sheets with VBA Macro
You can also use an Excel VBA Macro to get the number of worksheets in the current workbook. Just do the following steps:
#1 open your excel workbook and then click on “Visual Basic” command under DEVELOPER Tab, or just press “ALT+F11” shortcut.
#2 then the “Visual Basic Editor” window will appear.
#3 click “Insert” ->”Module” to create a new module.
#4 paste the below VBA code into the code window. Then clicking “Save” button.
#5 back to the current worksheet, then run the above excel macro. Click Run button.
#6 let’s see the result:
Video: Count the Number of Sheets
Источник
Return to VBA Code Examples
Application.Sheets.Count – Count Worksheets
If you ever need to count the number of sheets in a workbook, use the VBA command: Application.Sheets.Count
Put this in a module:
Public Sub CountMySheets()
MsgBox Application.Sheets.Count
End Sub
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!
<<Return to VBA Examples
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.
(No installation required!)
Free Download
This post will guide you how to count the number of sheets in a workbook in Excel. How do I count the number of worksheets in a workbook with VBA Macro in Excel.
- Count the Number of Sheets with Define Name
- Count the Number of Sheets with VBA Macro
- Video: Count the Number of Sheets
Count the Number of Sheets with Define Name
If you want to count the number of worksheets in a given workbook in Excel, you can use the Defined Name and a Formula to achieve it. Just do the following steps:
#1 go to Formula tab, click Define Name command under Defined Names group, and the New Name dialog will open.
#2 type one defined name in the Name text box, such as: countWorksheets, and then type the formula =GET.WORKBOOK(1)&T(NOW()) into the text box of Refers to. Click Ok button.
#3 Type the following formula based on the COUNTA function and the INDEX function to get the number of worksheets in the current workbook. And press Enter key in your keyboard, you will get the number of worksheets in your workbook.
=COUNTA(INDEX(CountWorksheets,0))
Count the Number of Sheets with VBA Macro
You can also use an Excel VBA Macro to get the number of worksheets in the current workbook. Just do the following steps:
#1 open your excel workbook and then click on “Visual Basic” command under DEVELOPER Tab, or just press “ALT+F11” shortcut.
#2 then the “Visual Basic Editor” window will appear.
#3 click “Insert” ->”Module” to create a new module.
#4 paste the below VBA code into the code window. Then clicking “Save” button.
Sub CountWorkSheets() MsgBox "The number of worksheets in the current workbook is : " & Application.Sheets.Count End Sub
#5 back to the current worksheet, then run the above excel macro. Click Run button.
#6 let’s see the result:
Video: Count the Number of Sheets
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