Excel vba get all sheets

Return to VBA Code Examples

The following macro loops through every sheet in a workbook and writes the tab name of each sheet sequentially to a sheet you choose. This could be handy for a quick list of every sheet in a workbook with many sheets.

List all Worksheets in a Workbook

To use the macro just replace the word Sheet1(it appears twice) in the code with the tab name where you would like the results. Make sure there isn’t any important information on the output tab because it clears the data their before writing to it.

Sub ListSheets()

Dim ws As Worksheet
Dim x As Integer

x = 1

Sheets("Sheet1").Range("A:A").Clear

For Each ws In Worksheets
     Sheets("Sheet1").Cells(x, 1) = ws.Name
     x = x + 1
Next ws

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!

alt text

Learn More!

vba-free-addin

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

If you have an Excel workbook that has hundreds of worksheets, and now you want to get a list of all the worksheet names, you can refer to this article. Here we will share 3 simple methods with you.

Sometimes, you may be required to generate a list of all worksheet names in an Excel workbook. If there are only few sheets, you can just use the Method 1 to list the sheet names manually. However, in the case that the Excel workbook contains a great number of worksheets, you had better use the latter 2 methods, which are much more efficient.

Method 1: Get List Manually

  1. First off, open the specific Excel workbook.
  2. Then, double click on a sheet’s name in sheet list at the bottom.
  3. Next, press “Ctrl + C” to copy the name.Copy Sheet Name
  4. Later, create a text file.
  5. Then, press “Ctrl + V” to paste the sheet name.Paste Sheet Name
  6. Now, in this way, you can copy each sheet’s name to the text file one by one.

Method 2: List with Formula

  1. At the outset, turn to “Formulas” tab and click the “Name Manager” button.
  2. Next, in popup window, click “New”.Name Manager
  3. In the subsequent dialog box, enter “ListSheets” in the “Name” field.
  4. Later, in the “Refers to” field, input the following formula:
=REPLACE(GET.WORKBOOK(1),1,FIND("]",GET.WORKBOOK(1)),"")

Customize New Name

  1. After that, click “OK” and “Close” to save this formula.
  2. Next, create a new worksheet in the current workbook.
  3. Then, enter “1” in Cell A1 and “2” in Cell A2.
  4. Afterwards, select the two cells and drag them down to input 2,3,4,5, etc. in Column A.Enter Sequential Numbers
  5. Later, put the following formula in Cell B1.
=INDEX(ListSheets,A1)

Enter Formula in Cell B1

  1. At once, the first sheet name will be input in Cell B1.
  2. Finally, just copy the formula down until you see the “#REF!” error.Copy Formula Down to List Sheet Names

Method 3: List via Excel VBA

  1. For a start, trigger Excel VBA editor according to “How to Run VBA Code in Your Excel“.
  2. Then, put the following code into a module or project.
Sub ListSheetNamesInNewWorkbook()
    Dim objNewWorkbook As Workbook
    Dim objNewWorksheet As Worksheet

    Set objNewWorkbook = Excel.Application.Workbooks.Add
    Set objNewWorksheet = objNewWorkbook.Sheets(1)

    For i = 1 To ThisWorkbook.Sheets.Count
        objNewWorksheet.Cells(i, 1) = i
        objNewWorksheet.Cells(i, 2) = ThisWorkbook.Sheets(i).Name
    Next i

    With objNewWorksheet
         .Rows(1).Insert
         .Cells(1, 1) = "INDEX"
         .Cells(1, 1).Font.Bold = True
         .Cells(1, 2) = "NAME"
         .Cells(1, 2).Font.Bold = True
         .Columns("A:B").AutoFit
    End With
End Sub

VBA Code - List Sheet Names

  1. Later, press “F5” to run this macro right now.
  2. At once, a new Excel workbook will show up, in which you can see the list of worksheet names of the source Excel workbook.Listed Sheet Names in New Excel Workbook

Comparison

Advantages Disadvantages
Method 1 Easy to operate Too troublesome if there are a lot of worksheets
Method 2 Easy to operate Demands you to type the index first
Method 3 Quick and convenient Users should beware of the external malicious macros
Easy even for VBA newbies

Excel Gets Corrupted

MS Excel is known to crash from time to time, thereby damaging the current files on saving. Therefore, it’s highly recommended to get hold of an external powerful Excel repair tool, such as DataNumen Outlook Repair. It’s because that self-recovery feature in Excel is proven to fail frequently.

Author Introduction:

Shirley Zhang is a data recovery expert in DataNumen, Inc., which is the world leader in data recovery technologies, including sql fix and outlook repair software products. For more information visit www.datanumen.com

Содержание

  1. Get Sheet Names
  2. How to use VBA procedures to generate a list of sheet names in an Excel workbook
  3. Account Information
  4. Share with Your Friends
  5. How to use VBA procedures to generate a list of sheet names in an Excel workbook
  6. Must-read Windows coverage
  7. How to enter and run code in VBA
  8. The bare bones VBA code
  9. How to generate a list of hyperlinks in Excel
  10. Microsoft Weekly Newsletter
  11. List Sheet Names with Formula – Excel & Google Sheets
  12. List Sheet Names Using Named Range and Formula
  13. Create Name Range for Sheet Names
  14. Using Formula to List Sheet Names
  15. Alternate Method
  16. VBA Get Sheet Name / Rename Sheet
  17. Get Sheet Name
  18. Get ActiveSheet Name
  19. Get Sheet Name by index Number
  20. Get Sheet Name by Code Name
  21. Rename Sheet
  22. Rename ActiveSheet
  23. VBA Coding Made Easy
  24. Rename Sheet by Name
  25. Rename Sheet by Sheet Index Number
  26. Rename Sheet by Code Name
  27. Check if Sheet Name Exists
  28. Copy Sheet and Rename
  29. VBA Code Examples Add-in

Get Sheet Names

How To Get Sheet Names Using VBA in Microsoft Excel

In case you want to find out a way which can get you all the names of the sheet that are visible i.e. not hidden.

In this article, we will learn how to get names of the visible sheets only, using VBA code.

Question): I have multiple sheets in one file & I have hidden the sheets which I do not want others to see; I want a code that will give me the name of all the visible sheets.

Let us consider we have 5 sheets & we intentionally hide a particular sheet.

To get name of the visible sheets, we need to follow the below steps:

  • Click on Developer tab
  • From Code group, select Visual Basic

Copy the below code in the standard module

Sub VisibleSheets()

Dim i As Integer, j As Integer: j = 1

Cells(1, 1).CurrentRegion.Cells.Clear

For i = 1 To Sheets.Count

If Sheets(i).Visible = -1 Then

Cells(j, 1) = Sheets(i).Name

j = j + 1

End If

Next

End Sub

  • First time when you run the code, you will get the names of all the sheets in current sheet in column A

  • If we hide Jan sheet then we will have following list of sheet names

In this way, we can get the name of all the visible sheets, using vba code.

Источник

How to use VBA procedures to generate a list of sheet names in an Excel workbook

Account Information

How to use VBA procedures to generate a list of sheet names in an Excel workbook

How to use VBA procedures to generate a list of sheet names in an Excel workbook

Use one or both of these simple Microsoft Excel macros to list all the sheets in an Excel workbook.


Image: Aajan Getty Images/iStockphoto

Must-read Windows coverage

Whether your Microsoft Excel workbook has three sheets or 50, knowing what you have is important. Some complex applications require detailed documentation that includes sheet names. For those times when a quick look isn’t good enough, and you must have a list, you have a couple of options: You can go the manual route, which would be tedious and need updating every time you made a change. Or you can run a quick VBA procedure. In this article, I’ll show you easily modified code that generates a list of sheet names and hyperlinks. There are other ways to generate a list, but I prefer the VBA method because it’s automated and easy to modify to suit individual requirements.

I’m using Microsoft 365 on a Windows 10 64-bit system, but you can use earlier versions. To save time, download the .xlsx, .xls and .cls files. Macros aren’t supported by the online version. This article assumes you have basic Excel skills and are familiar with VBA, but even a beginner should be able to follow the instructions to success.

How to enter and run code in VBA

If you’re new to VBA code, you might be wondering about the terms procedure and macro. You’ll see them used interchangeably when VBA is the language used. This isn’t true for all languages. In VBA, both a procedure and a macro are a named set of instructions that are preformed when called. Some developers refer to a sub procedure as a macro and a function procedure as a procedure because a procedure can accept arguments. Many use the term macro for everything. Some, like me, tend to use the term procedure for everything. Furthermore, Access has a macro feature that is separate from any VBA code. Don’t get too hung up on the terms.

To enter VBA code, press Alt + F11 to open the Visual Basic Editor. In the Project Explorer to the left, choose ThisWorkbook and enter the code. If you’re using a ribbon version, you must save the file as a macro-enabled file to use macros. You can also import the downloadable .cls file that contains the code. Or, you can work with either of the downloadable Excel workbooks. If you’re entering the code yourself, please don’t copy it from this web page. Instead, enter it manually or copy it to a text editor and then paste that code into a module.

When in the VBE, press F5 to run a procedure, but be sure to click inside the procedure you want to run. When in an Excel sheet, click the Developer tab, click Macros in the Code group, choose the procedure in the resulting dialog shown in Figure A, and then click Run.

Figure A

The bare bones VBA code

A simple list of sheet names is easy to generate using VBA thanks to the Worksheets collection. Listing A shows a simple For Each loop that cycles through this collection. For each sheet, the code uses the Name property to enter that name in column A, beginning at A1, in Sheet1.

Listing A

‘List all sheet names in column A of Sheet1.

‘Update to change location of list.

‘Generate a list of hyperlinks to each sheet in workbook in Sheet1.

For Each sh In Worksheets

ActiveCell.Offset(1, 0).Select ‘Move down a row.

When adapting this code, you might want to change the location of the list; do so by changing the first two lines accordingly. The For Each loop also offers possibilities for modifying. You might want to add header names or values to number the sheet names.

This code will list hidden and very hidden sheets, which you might not want. When that’s the case, you’ll need to check the Visible properties xlSheetVisible and xlSheetVeryHidden. In addition, because we’re actively selecting A1 on Sheet1, the cursor moves to that location. If you don’t want the active cell to change, use implicit selection statements. To learn more about implicit and explicit references, read Excel tips: How to select cells and ranges efficiently using VBA.

There are many modifications you might want to make. For example, instead of an ordinary list of text, you might want a list of hyperlinks.

How to generate a list of hyperlinks in Excel

It’s not unusual for a complex workbook to include a list of hyperlinks to each sheet in the workbook. The procedure you’ll use, shown in Listing B, is similar to Listing A, but this code uses the Name property to create a hyperlink.

Listing B

‘Generate list of hyperlinks to each sheet in workbook in Sheet1, A1.

‘Generate a list of hyperlinks to each sheet in workbook in Sheet1.

For Each sh In Worksheets

ActiveSheet.Hyperlinks.Add Anchor:=Selection, _

Address:=””, SubAddress:=”‘” & sh.Name & “‘” & “!A1”, _

ActiveCell.Offset(1, 0).Select ‘Moves down a row

The first two lines select cell A1 in Sheet1. Update these two statements to relocate the list. The For Each loop cycles through all the sheets, using the Name property to create a hyperlink for each sheet.

The Hyperlinks.Add property in the For Each uses the form

.Add Anchor, Address, [SubAddress], [ScreenTip], [TextToDisplay]

The parameter information is listed below:

  • Anchor: A Range or Shape object.
  • Address: The address of the hyperlink.
  • SubAddress: The subaddress of the hyperlink
  • ScreenTip: Information displayed when the mouse pointer pauses over the hyperlink.
  • TextToDisplay: The hyperlink text.

Our procedure’s SubAddress argument

SubAddress:=”‘” & sh.Name & “‘” & “!A1”

builds a string using the current sheet’s name and the cell reference A1. For instance, if the current sheet is Sheet1, this evaluates to ‘Sheet1’!A1. Subsequently, when you click this hyperlink, it takes you to cell A1 on Sheet1. As before, you can easily modify this procedure to reflect the way you want to use this list.

Both sub procedures are easy to use. Both can be easily modified to change the list’s position or to add more information to the simple list.

Microsoft Weekly Newsletter

Be your company’s Microsoft insider by reading these Windows and Office tips, tricks, and cheat sheets.

Источник

List Sheet Names with Formula – Excel & Google Sheets

Download the example workbook

This tutorial demonstrates how to list the sheet names of a workbook with a formula in Excel.

List Sheet Names Using Named Range and Formula

There is no built-in function in Excel that can list all the worksheets in a workbook. Instead you have two options:

If you want to use a formula, follow these steps:

  1. Create a named range “Worksheets”
  2. Use a formula to list out all sheet names.

Create Name Range for Sheet Names

To create a Named Range for the sheet names, in the Excel Ribbon: Formulas > Name Manager > New

Type “Worksheets” in the Name Box:

In the “Refers to” section of the dialog box, we will need to write the formula

This formula stores the names of all sheets (as an array in this format: “[workbook.xlsm].Overview”) in the workbook to the named range “Worksheets”.

The “GET.WORKBOOK” Function is a macro function, so your workbook has to be saved as a macro-enabled workbook (file format: .xlsm) for the sheet names to be updated each time the workbook is opened.

Note: When filling the Edit name dialog box, workbook should be selected as the scope of the name range.

Using Formula to List Sheet Names

Now we use a formula to list the sheet names. We’ll need the INDEX, MID, FIND, and ROWS Functions:

  • The formula above takes the “Worksheets” array and displays each sheet name based on its position.
  • The MID and FIND Functions extract the sheet names from the array (removing the workbook name).
  • Then the INDEX and ROW Functions display each value in that array.
  • Here, “Overview” is the first sheet in the workbooks and “Cleaning” is the last.

Click the link for more information on how the MID and FIND Functions get sheet names.

Alternate Method

You also have the option to create the list of sheet names within the Name Manager. Instead of

set your “Refers to” field to

Now there’s no need for MID, FIND, and ROWS in your formula. Your named range is already made up of only sheet names.

Use this simpler INDEX formula to list the sheets:

Источник

VBA Get Sheet Name / Rename Sheet

In this Article

This tutorial will cover interacting with Sheet names in VBA.

Get Sheet Name

Sheet names are stored in the Name property of the Sheets or Worksheets object. The Sheet Name is the “tab” name that’s visible at the bottom of Excel:

Get ActiveSheet Name

This will display the ActiveSheet name in a message box:

Get Sheet Name by index Number

This will display the first worksheet name in a message box:

This will display the name of the last worksheet in the workbook:

Get Sheet Name by Code Name

In the VBA Editor, there is an option to change the “code name” of a Sheet. The code name is not visible to the Excel user and can only be seen in the VBA Editor:

In VBA, when working with Sheets, you can reference the usual Tab name:

or the VBA code name:

Referencing the code name is desirable in case the Sheet tab name ever changes. If you allow you Excel user access to changing sheet names you should reference the code name in your VBA code so that a Sheet tab name mismatch doesn’t cause an error. Sheet code names are discussed in more detail here.

To get the Sheet name using the VBA Code name, do the following:

Rename Sheet

You can rename Sheets by adjusting the name property of the Sheets or Worksheets object.

Rename ActiveSheet

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!

Rename Sheet by Name

Rename Sheet by Sheet Index Number

Here we use 1 to rename the first Sheet in the Workbook.

Rename Sheet by Code Name

This code will rename a sheet using it’s VBA code name (discussed above):

Check if Sheet Name Exists

The function will return TRUE if the Sheet exists, or FALSE if it does not.

Copy Sheet and Rename

This example is from our article on Copying Sheets.

After copying and pasting a Sheet, the newly created sheet becomes the ActiveSheet. So to rename a copied Sheet, simply use ActiveSheet.Name:

Note: We added error handling to avoid errors if the Sheet name already exists.

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.

Источник

Author: Oscar Cronquist Article last updated on March 19, 2019

In this post, I am going to demonstrate how to automatically create a new sheet in the current workbook and list all open workbooks and their sheets using a VBA macro.

The image above shows the new worksheet, it contains the names of the workbooks and corresponding worksheets I have currently open.

Macro code

'Name macro
Sub ListWorkbooks()

'Declare variables and data types
Dim wb As Workbook
Dim ws As Worksheet
Dim i As Single, j As Single

'Create a new worksheet and save to object ws
Set ws = Sheets.Add

'Go through open workbooks
For j = 1 To Workbooks.Count

    'Save workbook name to cell A1 and downwards
    Range("A1").Cells(j, 1) = Workbooks(j).Name
    
    'Iterate through worksheets in given workbook
    For i = 1 To Workbooks(j).Sheets.Count
  
            'Save worksheet names to cell B1 and cells further right
            Range("A1").Cells(j, i + 1) = Workbooks(j).Sheets(i).Name

    'Continue with next worksheet
    Next i

'Continue with next workbook
Next j
End Sub

How to copy the macro to your workbook

  1. Press Alt+F11 to open the VB Editor.
  2. Press with right mouse button on on your workbook in the Project Explorer.
  3. Press with left mouse button on «Insert» and then «Module».
  4. Copy macro code.
  5. Press with left mouse button on in code module window to see the input prompt.
  6. Paste code to code module.
  7. Return to Excel.

How to run the macro

  1. Go to «Developer» tab on the ribbon.
  2. Press with left mouse button on «Macros» button.
  3. Select «ListWorkbooks» macro.
  4. Press with left mouse button on «Run» button.

test

test

test

test

test

Apply drop-down lists dynamically
This article demonstrates how to automatically create drop-down lists if adjacent data grows, there are two methods explained here. The […]

test

Auto resize columns as you type
Excel does not resize columns as you type by default as the image above demonstrates. You can easily resize all […]

test

Automate data entry [VBA]
This article demonstrates how to automatically enter data in cells if an adjacent cell is populated using VBA code. In […]

test

Basic data entry [VBA]
In this small tutorial, I am going to show you how to create basic data entry with a small amount […]

test

Calendar with scheduling [vba]
Here is my contribution to all excel calendars out there. My calendar is created in Excel 2007 and uses both […]

test

test

test

test

Consolidate sheets [vba]
Question: I have multiple worksheets in a workbook. Each worksheets is project specific. Each worksheet contains almost identical format. The […]

test

Copy a dynamic cell range [VBA]
In this blog post, I will demonstrate some VBA copying techniques that may be useful if you don’t know the […]

test

test

test

test

test

Create a Print button [VBA]
This article describes how to create a button and place it on an Excel worksheet then assign a macro to […]

test

test

test

test

test

Edit invoice data [VBA]
In a previos post:Excel vba: Save invoice data we added/copied data between sheets. This post describes how to overwrite existing […]

test

Excel calendar [VBA]
This workbook contains two worksheets, one worksheet shows a calendar and the other worksheet is used to store events. The […]

test

test

test

test

test

test

test

Hide specific columns programmatically
This article describes a macro that hides specific columns automatically based on values in two given cells. I am also […]

test

Hide specific worksheets programmatically
This article demonstrates techniques to hide and unhide worksheets programmatically. The image above shows the Excel window and the worksheet […]

test

test

test

test

test

test

test

test

test

test

test

test

How to quickly select blank cells
In this smaller example, column D (Category) has empty cells, shown in the picture above. If your column contains thousands of […]

test

test

test

How to use DIALOG BOXES
A dialog box is an excellent alternative to a userform, they are built-in to VBA and can save you time […]

test

How to use the Scroll Bar
This article demonstrates how to insert and use a scroll bar (Form Control) in Excel. It allows the user to […]

test

Identify missing numbers in a column
The image above shows an array formula in cell D6 that extracts missing numbers i cell range B3:B7, the lower […]

test

test

Locate a shape in a workbook
This article demonstrates how to locate a shape in Excel programmatically based on the value stored in the shape. The […]

test

Move a shape [VBA]
This article demonstrates how to move a shape, a black arrow in this case, however, you can use whatever shape […]

test

test

Normalize data [VBA]
To be able to use a Pivot Table the source data you have must be arranged in way that a […]

test

Open Excel files in a folder [VBA]
This tutorial shows you how to list excel files in a specific folder and create adjacent checkboxes, using VBA. The […]

test

test

test

test

test

test

test

test

test

Save invoice data [VBA]
This article demonstrates a macro that copies values between sheets. I am using the invoice template workbook. This macro copies […]

test

Search two related tables [VBA]
This article demonstrates a macro that automatically applies a filter to an Excel defined Table based on the result from […]

test

Select and view invoice [VBA]
This post demonstrates how to view saved invoices based on the invoice number using a userform. The userform appears when the […]

test

test

test

test

test

test

Toggle a macro on/off using a button
This article demonstrates how the user can run a macro by press with left mouse button oning on a button, […]

test

test

Working with COMBO BOXES [Form Controls]
This blog post demonstrates how to create, populate and change comboboxes (form control) programmatically. Form controls are not as flexible […]

test

Working with FILES
In this blog article, I will demonstrate basic file copying techniques using VBA (Visual Basic for Applications). I will also […]

test

Working with TEXT BOXES [Form Controls]
There are two different kinds of text boxes, Form controls and ActiveX Controls. Form controls can only be used on […]

Latest updated articles.

More than 300 Excel functions with detailed information including syntax, arguments, return values, and examples for most of the functions used in Excel formulas.

More than 1300 formulas organized in subcategories.

Excel Tables simplifies your work with data, adding or removing data, filtering, totals, sorting, enhance readability using cell formatting, cell references, formulas, and more.

Allows you to filter data based on selected value , a given text, or other criteria. It also lets you filter existing data or move filtered values to a new location.

Lets you control what a user can type into a cell. It allows you to specifiy conditions and show a custom message if entered data is not valid.

Lets the user work more efficiently by showing a list that the user can select a value from. This lets you control what is shown in the list and is faster than typing into a cell.

Lets you name one or more cells, this makes it easier to find cells using the Name box, read and understand formulas containing names instead of cell references.

The Excel Solver is a free add-in that uses objective cells, constraints based on formulas on a worksheet to perform what-if analysis and other decision problems like permutations and combinations.

An Excel feature that lets you visualize data in a graph.

Format cells or cell values based a condition or criteria, there a multiple built-in Conditional Formatting tools you can use or use a custom-made conditional formatting formula.

Lets you quickly summarize vast amounts of data in a very user-friendly way. This powerful Excel feature lets you then analyze, organize and categorize important data efficiently.

VBA stands for Visual Basic for Applications and is a computer programming language developed by Microsoft, it allows you to automate time-consuming tasks and create custom functions.

A program or subroutine built in VBA that anyone can create. Use the macro-recorder to quickly create your own VBA macros.

UDF stands for User Defined Functions and is custom built functions anyone can create.

A list of all published articles.

Excel VBA Tutorial about how to refer to, and work with, sheets and worksheets in macrosIn this VBA Tutorial, you learn how to refer to, and work with, sheets and worksheets in macros. This includes:

  1. How to refer to all sheets in a workbook.
  2. How to refer to all worksheets in a workbook.
  3. How to refer to the active sheet.
  4. How to refer to a sheet by its index number.
  5. How to refer to a worksheet by its index number.
  6. How to refer to a sheet by its name.
  7. How to refer to a worksheet by its name.
  8. How to refer to a sheet by its code name.
  9. How to refer to several sheets.
  10. How to refer to several worksheets.
  11. How to loop through all sheets in a workbook with the For Each… Next loop.
  12. How to loop through all worksheets in a workbook with the For Each… Next loop.
  13. How to loop through all sheets in a workbook with the For… Next loop.
  14. How to loop through all worksheets in a workbook with the For… Next loop.
  15. How to loop through all sheets in a workbook in reverse order.
  16. 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:

  1. Identify the workbook containing the sheets (Workbook).
  2. 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.

Results of executing macro that refers to all sheets in workbook

#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:

  1. Identify the workbook containing the worksheets (Workbook).
  2. 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.

Results of executing macro that refers to all worksheets in workbook

#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:

  1. Identify the workbook containing the sheet (Workbook). If you don’t identify Workbook, VBA works with the active workbook.
  2. 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).

Results of executing macro that refers to active sheet

#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:

  1. Identify the workbook containing the sheet (Workbook).
  2. 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).

Results of executing macro that refers to sheet by index number

#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:

  1. Identify the workbook containing the worksheet (Workbook).
  2. 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).

Results of executing macro that refers to worksheet by index number

#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:

  1. Identify the workbook containing the sheet (Workbook).
  2. 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.

Results of executing macro that refers to sheet by name

#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:

  1. Identify the workbook containing the worksheet (Workbook).
  2. 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.

Results of executing macro that refers to worksheet by name

#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).

Results of executing macro that refers to sheet by code name

#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:

  1. Identify the workbook containing the sheets (Workbook).
  2. Obtain an array with the index numbers or names of the sheets you refer to (Array(SheetList)).
  3. 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.

Results of executing macro that refers to several sheets

#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:

  1. Identify the workbook containing the worksheets (Workbook).
  2. Obtain an array with the index numbers or names of the worksheets you refer to (Array(WorksheetList)).
  3. 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).

Results of executing macro that refers to several worksheets

#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:

  1. Identify the workbook containing the sheets (Workbook).
  2. Identify the Sheets collection representing all sheets in Workbook (Sheets).
  3. Use an object variable to iterate through the Sheets in Workbook (Sheet).
  4. 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:

  1. Loops through each sheet in the workbook where the macro is stored (For Each iSheet In ThisWorkbook.Sheets | Next iSheet).
  2. 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.

Results of executing macro that loops through all sheets with For Each... Next

#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:

  1. Identify the workbook containing the worksheets (Workbook).
  2. Identify the Sheets collection representing all worksheets in Workbook (Worksheets).
  3. Use an object variable to iterate through the worksheets in Workbook (Worksheet).
  4. 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:

  1. Loops through each worksheet in the workbook where the macro is stored (For Each iWorksheet In ThisWorkbook.Worksheets | Next iWorksheet).
  2. 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.

Results of executing macro that loops through all worksheets with For Each... Next

#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:

  1. Identify the workbook containing the sheets (Workbook).
  2. Identify the Sheets collection representing all sheets in Workbook (Sheets).
  3. Count the number of sheets in the Sheets collection (Count).
  4. 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:

  1. Loops through each sheet in the workbook where the macro is stored (For iCounter = 1 To ThisWorkbook.Sheets.Count | Next iCounter).
  2. 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.

Results of executing macro that loops through all sheets with For... Next

#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:

  1. Identify the workbook containing the worksheets (Workbook).
  2. Identify the Sheets collection representing all worksheets in Workbook (Worksheets).
  3. Count the number of worksheets in the Sheets collection (Count).
  4. 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:

  1. Loops through each worksheet in the workbook where the macro is stored (For iCounter = 1 To ThisWorkbook.Worksheets.Count | Next iCounter).
  2. 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.

Results of executing macro that loops through all worksheets with For... Next

#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:

  1. Identify the workbook containing the sheets (Workbook).
  2. Identify the Sheets collection representing all sheets in Workbook (Sheets).
  3. Count the number of sheets in the Sheets collection (Count).
  4. 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:

  1. 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).
  2. 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.

Results of executing macro that loops through all sheets 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:

  1. Identify the workbook containing the worksheets (Workbook).
  2. Identify the Sheets collection representing all worksheets in Workbook (Worksheets).
  3. Count the number of worksheets in the Sheets collection (Count).
  4. 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:

  1. 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).
  2. 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.

Results of executing macro that loops through all worksheets 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.

Image: Aajan Getty Images/iStockphoto

Whether your Microsoft Excel workbook has three sheets or 50, knowing what you have is important. Some complex applications require detailed documentation that includes sheet names. For those times when a quick look isn’t good enough, and you must have a list, you have a couple of options: You can go the manual route, which would be tedious and need updating every time you made a change. Or you can run a quick VBA procedure. In this article, I’ll show you easily modified code that generates a list of sheet names and hyperlinks. There are other ways to generate a list, but I prefer the VBA method because it’s automated and easy to modify to suit individual requirements.

SEE: 69 Excel tips every user should master (TechRepublic)

I’m using Microsoft 365 on a Windows 10 64-bit system, but you can use earlier versions. To save time, download the .xlsx, .xls and .cls files. Macros aren’t supported by the online version. This article assumes you have basic Excel skills and are familiar with VBA, but even a beginner should be able to follow the instructions to success.

How to enter and run code in VBA

If you’re new to VBA code, you might be wondering about the terms procedure and macro. You’ll see them used interchangeably when VBA is the language used. This isn’t true for all languages. In VBA, both a procedure and a macro are a named set of instructions that are preformed when called. Some developers refer to a sub procedure as a macro and a function procedure as a procedure because a procedure can accept arguments. Many use the term macro for everything. Some, like me, tend to use the term procedure for everything. Furthermore, Access has a macro feature that is separate from any VBA code. Don’t get too hung up on the terms.

SEE: Windows 10: Lists of vocal commands for speech recognition and dictation (free PDF) (TechRepublic)

To enter VBA code, press Alt + F11 to open the Visual Basic Editor. In the Project Explorer to the left, choose ThisWorkbook and enter the code. If you’re using a ribbon version, you must save the file as a macro-enabled file to use macros. You can also import the downloadable .cls file that contains the code. Or, you can work with either of the downloadable Excel workbooks. If you’re entering the code yourself, please don’t copy it from this web page. Instead, enter it manually or copy it to a text editor and then paste that code into a module.

When in the VBE, press F5 to run a procedure, but be sure to click inside the procedure you want to run. When in an Excel sheet, click the Developer tab, click Macros in the Code group, choose the procedure in the resulting dialog shown in Figure A, and then click Run.

Figure A

The bare bones VBA code

A simple list of sheet names is easy to generate using VBA thanks to the Worksheets collection. Listing A shows a simple For Each loop that cycles through this collection. For each sheet, the code uses the Name property to enter that name in column A, beginning at A1, in Sheet1.

Listing A

Sub ListSheetNames()

‘List all sheet names in column A of Sheet1.

‘Update to change location of list.

Sheets(“Sheet1”).Activate

ActiveSheet.Cells(1, 1).Select

‘Generate a list of hyperlinks to each sheet in workbook in Sheet1.

For Each sh In Worksheets

ActiveCell = sh.Name

ActiveCell.Offset(1, 0).Select ‘Move down a row.

Next

End Sub

When adapting this code, you might want to change the location of the list; do so by changing the first two lines accordingly. The For Each loop also offers possibilities for modifying. You might want to add header names or values to number the sheet names.

This code will list hidden and very hidden sheets, which you might not want. When that’s the case, you’ll need to check the Visible properties xlSheetVisible and xlSheetVeryHidden. In addition, because we’re actively selecting A1 on Sheet1, the cursor moves to that location. If you don’t want the active cell to change, use implicit selection statements. To learn more about implicit and explicit references, read Excel tips: How to select cells and ranges efficiently using VBA.

There are many modifications you might want to make. For example, instead of an ordinary list of text, you might want a list of hyperlinks.

How to generate a list of hyperlinks in Excel

It’s not unusual for a complex workbook to include a list of hyperlinks to each sheet in the workbook. The procedure you’ll use, shown in Listing B, is similar to Listing A, but this code uses the Name property to create a hyperlink.

Listing B

Sub ListSheetNamesAsHyperlinks()

‘Generate list of hyperlinks to each sheet in workbook in Sheet1, A1.

Sheets(“Sheet1”).Activate

ActiveSheet.Cells(1, 1).Select

‘Generate a list of hyperlinks to each sheet in workbook in Sheet1.

For Each sh In Worksheets

ActiveSheet.Hyperlinks.Add Anchor:=Selection, _

Address:=””, SubAddress:=”‘” & sh.Name & “‘” & “!A1”, _

TextToDisplay:=sh.Name

ActiveCell.Offset(1, 0).Select ‘Moves down a row

Next

End Sub

The first two lines select cell A1 in Sheet1. Update these two statements to relocate the list. The For Each loop cycles through all the sheets, using the Name property to create a hyperlink for each sheet.

The Hyperlinks.Add property in the For Each uses the form

.Add Anchor, Address, [SubAddress], [ScreenTip], [TextToDisplay]

The parameter information is listed below:

  • Anchor: A Range or Shape object.
  • Address: The address of the hyperlink.
  • SubAddress: The subaddress of the hyperlink
  • ScreenTip: Information displayed when the mouse pointer pauses over the hyperlink.
  • TextToDisplay: The hyperlink text.

Our procedure’s SubAddress argument

SubAddress:=”‘” & sh.Name & “‘” & “!A1”

builds a string using the current sheet’s name and the cell reference A1. For instance, if the current sheet is Sheet1, this evaluates to ‘Sheet1’!A1. Subsequently, when you click this hyperlink, it takes you to cell A1 on Sheet1. As before, you can easily modify this procedure to reflect the way you want to use this list.

Both sub procedures are easy to use. Both can be easily modified to change the list’s position or to add more information to the simple list.

Like this post? Please share to your friends:
  • Excel vba listobject listrows
  • Excel vba function private
  • Excel vba listobject add
  • Excel vba function in a cell
  • Excel vba function calls