Excel sheet or worksheet

I use the terms Sheet and Worksheet interchangeably when talking about Excel, I think most users do.  Google also appears to think they are the same thing; If I search for “How to loop through Sheets with Excel VBA”, all the results returned on the first page refer to Worksheets.

Yet, Sheets and Worksheets from a VBA perspective are definitely not the same.  Unfortunately, most of the VBA code I write doesn’t really consider the differences… bad habits, I know.  Hopefully, by writing this post it will inspire me to correct my bad habits, and prevent you from creating bad habits.

In essence, all Worksheets are Sheets, but not all Sheets are Worksheets.  There are different types of Sheets:

  • Worksheet – the sheet with the gridlines and cells
  • Chart – the sheet which contains a single chart
  • DialogSheet – an Excel 5 dialog sheet.  These are effectively defunct as they have been replaced by VBA UserForms
  • Macro sheets – A sheet containing Excel 4 macros. These were replaced by VBA in 1995.
  • International Macro sheet – A sheet containing an internationally compatible Excel 4 macro (also replaced in 1995).

Since DialogSheets, and both forms of Macro sheets were replaced in the 90’s, we can pretty much ignore them.  That leaves just two types of sheets we are likely to encounter: Charts and Worksheets.

So, in summary, when we refer to Sheets in VBA, we are talking about Charts and Worksheets.  And when we refer to Worksheets, we are excluding Charts.

What type of sheet is it?

Different sheet types have their own properties.  For example, on a Worksheet you can select cells, but you can’t on a Chart sheet, because there are no cells.  So, if we want to perform certain actions on the active sheet, we need to know which type of sheet we are on.

Sub TypeOfActiveSheet()

MsgBox TypeName(ActiveSheet)

End Sub

Running the code above will generate a message box with either “Worksheet” or “Chart” depending on the type of sheet.

Objects and collections

Understanding objects and collections will help us master the use of Charts, Worksheets and Sheets.

Worksheet – A Worksheet is an object which refers to a single worksheet.  Each worksheet is a member of the Worksheets and Sheets collection objects.

Worksheets – Worksheets is a collection object which contains all the individual Worksheet objects in a workbook.

Chart – A Chart is an object which refers to a single chart. The chart:

  • Can be contained within a Chart Object for a chart contained on the face of the worksheet (outside the scope of this post).
  • Can be a member of the Charts and Sheets collection objects.

Charts – Charts is a collection object which contains all the individual Chart sheet objects within a workbook.  This should not be confused with the ChartObjects object, which is the collection of charts contained on the face of the worksheet.

Sheets – Sheets is a collection object which contains all the individual Worksheet and Chart sheet objects in a workbook.

Looping through Sheets, Worksheets and Charts

When using the For Each loop, we are looping through each object within a collection.

Example 1 – Looping through each Worksheet in the Worksheets collection

The VBA code below will loop through each Worksheet in the Worksheets collection.

Sub LoopThroughWorksheets()

'Create an instance of the Worksheet object called "ws"
Dim ws As Worksheet

'Loop through each Worksheet object in the Worksheets collection
For Each ws In ActiveWorkbook.Worksheets

    MsgBox ws.Name

Next ws

End Sub

Example 2 – Looping through each Chart in the Charts collection

The following code will loop through each Chart in the Charts collection.

Sub LoopThroughCharts()

'Create an instance of the Chart object called "cht"
Dim cht As Chart

'Loop through each Chart object in the Charts collection
For Each cht In ActiveWorkbook.Charts

    MsgBox cht.Name

Next cht

End Sub

Example 3 – Looping through each Object in the Sheets collection

To loop through every sheet, we cannot declare a Sheet object, because it doesn’t exist.  The example below loops through every object (i.e. it will include Chart and Worksheet objects) contained within the Sheets collection.

Sub LoopThroughSheets()

'Create a variable to hold any object called "obj"
Dim obj As Object

'Loop through each Object in the Sheets collection
For Each obj In ActiveWorkbook.Sheets

    MsgBox obj.Name

Next obj

End Sub

Example 4 – Looping through every Sheet in the Sheets collection

As an alternative to Example 3, we could count the sheets, then loop using a For loop.

Sub LoopThroughSheets()

Dim i As Integer

'Count all sheets and loop through each
For i = 1 To Sheets.Count

    MsgBox Sheets(i).Name

Next i

End Sub

This method of looping by counting the objects will work equally well with Charts and Worksheets.


Headshot Round

About the author

Hey, I’m Mark, and I run Excel Off The Grid.

My parents tell me that at the age of 7 I declared I was going to become a qualified accountant. I was either psychic or had no imagination, as that is exactly what happened. However, it wasn’t until I was 35 that my journey really began.

In 2015, I started a new job, for which I was regularly working after 10pm. As a result, I rarely saw my children during the week. So, I started searching for the secrets to automating Excel. I discovered that by building a small number of simple tools, I could combine them together in different ways to automate nearly all my regular tasks. This meant I could work less hours (and I got pay raises!). Today, I teach these techniques to other professionals in our training program so they too can spend less time at work (and more time with their children and doing the things they love).


Do you need help adapting this post to your needs?

I’m guessing the examples in this post don’t exactly match your situation. We all use Excel differently, so it’s impossible to write a post that will meet everybody’s needs. By taking the time to understand the techniques and principles in this post (and elsewhere on this site), you should be able to adapt it to your needs.

But, if you’re still struggling you should:

  1. Read other blogs, or watch YouTube videos on the same topic. You will benefit much more by discovering your own solutions.
  2. Ask the ‘Excel Ninja’ in your office. It’s amazing what things other people know.
  3. Ask a question in a forum like Mr Excel, or the Microsoft Answers Community. Remember, the people on these forums are generally giving their time for free. So take care to craft your question, make sure it’s clear and concise.  List all the things you’ve tried, and provide screenshots, code segments and example workbooks.
  4. Use Excel Rescue, who are my consultancy partner. They help by providing solutions to smaller Excel problems.

What next?
Don’t go yet, there is plenty more to learn on Excel Off The Grid.  Check out the latest posts:

Содержание

  1. Worksheets and Workbooks in Excel
  2. Worksheet Details
  3. Worksheet Names
  4. Workbook Details
  5. VBA Sheets – The Ultimate Guide
  6. Sheets Vs. Worksheets
  7. Referencing Sheets
  8. ActiveSheet
  9. Sheet Name
  10. Sheet Index Number
  11. Sheet Index Number – Last Sheet in Workbook
  12. Sheet “Code Name”
  13. VBA Coding Made Easy
  14. Referencing Sheets in Other Workbooks
  15. Activate vs. Select Sheet
  16. Activate a Sheet
  17. Select a Sheet
  18. Select Multiple Sheets
  19. Worksheet Variable
  20. Loop Through All Sheets in Workbook
  21. Worksheet Protection
  22. Workbook Protection
  23. Worksheet Protection
  24. Protect Worksheet
  25. Unprotect Worksheet
  26. Worksheet Visible Property
  27. Unhide Worksheet
  28. Hide Worksheet
  29. Very Hide Worksheet
  30. Worksheet-Level Events
  31. Worksheet Activate Event
  32. Worksheet Change Event
  33. Worksheet Cheat Sheet
  34. VBA Worksheets Cheatsheet
  35. VBA Code Examples Add-in

Worksheets and Workbooks in Excel

Learn about worksheets and spreadsheets in Excel and Google Sheets

A worksheet or sheet is a single page in a file created with an electronic spreadsheet program such as Microsoft Excel or Google Sheets. A workbook is the name given to an Excel file and contains one or more worksheets. When you open an electronic spreadsheet program, it loads an empty workbook file consisting of one or more blank worksheets for you to use.

Instructions in this article apply to Excel for Microsoft 365, Excel 2019, 2016, 2013, and 2010; Excel for Mac, Excel Online, and Google Sheets.

Worksheet Details

You use worksheets to store, manipulate, and display data.

The primary storage unit for data in a worksheet is a rectangular-shaped cell arranged in a grid pattern in every sheet. Individual cells of data are identified and organized using the vertical column letters and horizontal row numbers of a worksheet, which create a cell reference, such as A1, D15, or Z467.

Worksheet specifications for current versions of Excel include:

  • 1,048,576 rows per worksheet
  • 16,384 columns per worksheet
  • 17,179,869,184 cells per worksheet
  • A limited number of sheets per file based on the amount of memory available on the computer

For Google Sheets:

  • 256 columns per sheet
  • 400,000 cells for all worksheets in a file
  • 200 worksheets per spreadsheet file

Worksheet Names

In both Microsoft Excel and Google Sheets, each worksheet has a name. By default, the worksheets are named Sheet1, Sheet2, Sheet3, and so on, but you can change these names.

Workbook Details

  • Add worksheets to a workbook using the context menu or the New Sheet/Add Sheet icon (+) next to the current sheet tabs.
  • Delete or hide individual worksheets in a workbook.
  • Rename individual worksheets and change worksheet tab colors to make it easier to identify single sheets in a workbook using the context menu.
  • Select the sheet tab at the bottom of the screen to change to another worksheet.

In Excel, use the following shortcut key combinations to switch between worksheets:

  • Ctrl+PgUp (page up): Move to the right
  • Ctrl+PgDn (page down): Move to the left

In Google Sheets, the shortcut key combinations to switch between worksheets are:

  • Ctrl+Shift+PgUp: Move to the right
  • Ctrl+Shift+PgDn: Move to the left

Get the Latest Tech News Delivered Every Day

Источник

VBA Sheets – The Ultimate Guide

In this Article

This is the ultimate guide to working with Excel Sheets / Worksheets in VBA.

At the bottom of this guide, we’ve created a cheat sheet of common commands for working with sheets.

Sheets Vs. Worksheets

There are two ways to reference Sheets using VBA. The first is with the Sheets object:

The other is with the Worksheets object:

99% of the time, these two objects are identical. In fact, if you’ve searched online for VBA code examples, you’ve probably seen both objects used. Here is the difference:

The Sheets Collection contains Worksheets AND Chart Sheets.

So use Sheets if you want to include regular Worksheets AND Chart Sheets. Use Worksheets if you want to exclude Chart Sheets. For the rest of this guide we will use Sheets and Worksheets interchangeably.

Referencing Sheets

There are several different ways to reference Sheets:

  • ActiveSheet
  • Sheet Tab Name
  • Sheet Index Number
  • Sheet Code Name

ActiveSheet

The ActiveSheet is the Sheet that’s currently active. In other words, if you paused your code and looked at Excel, it’s the sheet that is visible. The below code example will display a MessageBox with the ActiveSheet name.

Sheet Name

You are probably most familiar with referencing Sheets by their Tab Name:

This is the sheet name that’s visible to Excel users. Enter it into the sheets object, as a string of text, surrounded by quotations.

Sheet Index Number

The Sheet Index number is the sheet position in the workbook. 1 is the first sheet. 2 is the second sheet etc.:

Sheet Index Number – Last Sheet in Workbook

To reference the last Sheet in the workbook, use Sheets.Count to get the last Index Number and activate that sheet:

Sheet “Code Name”

The Sheet Code Name is it’s Object name in VBA:

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

Referencing Sheets in Other Workbooks

It’s also easy to reference Sheets in other Workbooks. To do so, you need to use the Workbooks Object:

Important: The Workbook must be open before you can reference its Sheets.

Activate vs. Select Sheet

In another article we discuss everything about activating and selecting sheets. The short version is this:

When you Activate a Sheet it becomes the ActiveSheet. This is the sheet you would see if you looked at your Excel program. Only one sheet may be activate at a time.

Activate a Sheet

When you select a Sheet, it also becomes the ActiveSheet. However, you can select multiple sheets at once. When multiple sheets are selected at once, the “top” sheet is the ActiveSheet. However, you can toggle the ActiveSheet within selected sheets.

Select a Sheet

Select Multiple Sheets

Use an array to select multiple sheets at once:

Worksheet Variable

Assigning a worksheet to an object variable allows you to reference the worksheet by it’s variable name. This can save a lot of typing and make your code easier to read. There are also many other reasons you might want to use variables.

To declare a worksheet variable:

Assign a worksheet to a variable:

Now you can reference the worksheet variable in your code:

Loop Through All Sheets in Workbook

Worksheet variables are useful when you want to loop through all the worksheets in a workbook. The easiest way to do this is:

This code will loop through all worksheets in the workbook, displaying each worksheet name in a message box. Looping through all the sheets in a workbook is very useful when locking / unlocking or hiding / unhiding multiple worksheets at once.

Worksheet Protection

Workbook Protection

Workbook protection locks the workbook from structural changes like adding, deleting, moving, or hiding worksheets.

You can turn on workbook protection using VBA:

or disable workbook protection:

Note: You can also protect / unprotect without a password by omitting the Password argument:

Worksheet Protection

Worksheet-level protection prevents changes to individual worksheets.

Protect Worksheet

Unprotect Worksheet

There are a variety of options when protecting worksheets (allow formatting changes, allow user to insert rows, etc.) We recommend using the Macro Recorder to record your desired settings.

We discuss worksheet protection in more detail here.

Worksheet Visible Property

You might already know that worksheets can be hidden:

There are actually three worksheet visibility settings: Visible, Hidden, and VeryHidden. Hidden sheets can be unhidden by any regular Excel user – by right-clicking in the worksheet tab area (shown above). VeryHidden sheets can only be unhidden with VBA code or from within the VBA Editor. Use the following code examples to hide / unhide worksheets:

Unhide Worksheet

Hide Worksheet

Very Hide Worksheet

Worksheet-Level Events

Events are triggers that can cause “Event Procedures” to run. For example, you can cause code to run every time any cell on a worksheet is changed or when a worksheet is activated.

Worksheet event procedures must be placed in a worksheet module:

There are numerous worksheet events. To see a complete list, go to a worksheet module , select “Worksheet” from the first drop-down. Then selecting an event procedure from the second drop-down to insert it into the module.

Worksheet Activate Event

Worksheet activate events run each time the worksheet is opened.

This code will select cell A1 (resetting the view area to the top-left of the worksheet) each time the worksheet is opened.

Worksheet Change Event

Worksheet change events run whenever a cell value is changed on the worksheet. Read our tutorial about Worksheet Change Events for more information.

Worksheet Cheat Sheet

Below you will find a cheat sheet containing common code examples for working with sheets in VBA

VBA Worksheets Cheatsheet

VBA worksheets Cheatsheet

Description Code Example
Referencing and Activating Sheets
Tab Name Sheets(«Input»).Activate
VBA Code Name Sheet1.Activate
Index Position Sheets(1).Activate
Select Sheet
Select Sheet Sheets(«Input»).Select
Set to Variable Dim ws as Worksheet
Set ws = ActiveSheet
Name / Rename ActiveSheet.Name = «NewName»
Next Sheet ActiveSheet.Next.Activate
Loop Through all Sheets Dim ws as Worksheet

For each ws in Worksheets
Msgbox ws.name
Next ws Loop Through Selected Sheets Dim ws As Worksheet

For Each ws In ActiveWindow.SelectedSheets
MsgBox ws.Name
Next ws Get ActiveSheet MsgBox ActiveSheet.Name Add Sheet Sheets.Add Add Sheet and Name Sheets.Add.Name = «NewSheet» Add Sheet With Name From Cell Sheets.Add.Name = range(«a3»).value Add Sheet After Another Sheets.Add After:=Sheets(«Input») Add Sheet After and Name Sheets.Add(After:=Sheets(«Input»)).Name = «NewSheet» Add Sheet Before and Name Sheets.Add(Before:=Sheets(«Input»)).Name = «NewSheet» Add Sheet to End of Workbook Sheets.Add After:=Sheets(Sheets.Count) Add Sheet to Beginning of Workbook Sheets.Add(Before:=Sheets(1)).Name = «FirstSheet» Add Sheet to Variable Dim ws As Worksheet
Set ws = Sheets.Add Copy Worksheets Move Sheet to End of Workbook Sheets(«Sheet1»).Move After:=Sheets(Sheets.Count) To New Workbook Sheets(«Sheet1»).Copy Selected Sheets To New Workbook ActiveWindow.SelectedSheets.Copy Before Another Sheet Sheets(«Sheet1»).Copy Before:=Sheets(«Sheet2») Before First Sheet Sheets(«Sheet1»).Copy Before:=Sheets(1) After Last Sheet Sheets(«Sheet1»).Copy After:=Sheets(Sheets.Count) Copy and Name Sheets(«Sheet1»).Copy After:=Sheets(Sheets.Count)
ActiveSheet.Name = «LastSheet» Copy and Name From Cell Value Sheets(«Sheet1»).Copy After:=Sheets(Sheets.Count)
ActiveSheet.Name = Range(«A1»).Value To Another Workbook Sheets(«Sheet1»).Copy Before:=Workbooks(«Example.xlsm»).Sheets(1) Hide / Unhide Sheets Hide Sheet Sheets(«Sheet1»).visible = False
or
Sheets(«Sheet1»).visible = xlSheetHidden Unhide Sheet Sheets(«Sheet1»).Visible = True
or
Sheets(«Sheet1»).Visible = xlSheetVisible Very Hide Sheet Sheets(“Sheet1”).Visible = xlSheetVeryHidden Delete or Clear Sheets Delete Sheet Sheets(«Sheet1»).Delete Delete Sheet (Error Handling) On Error Resume Next
Sheets(«Sheet1»).Delete
On Error GoTo 0 Delete Sheet (No Prompt) Application.DisplayAlerts = False
Sheets(«Sheet1»).Delete
Application.DisplayAlerts = True Clear Sheet Sheets(«Sheet1»).Cells.Clear Clear Sheet Contents Only Sheets(«Sheet1»).Cells.ClearContents Clear Sheet UsedRange Sheets(«Sheet1»).UsedRange.Clear Protect or Unprotect Sheets Unprotect (No Password) Sheets(«Sheet1»).Unprotect Unprotect (Password) Sheets(«Sheet1»).Unprotect «Password» Protect (No Password) Sheets(«Sheet1»).Protect Protect (Password) Sheets(«Sheet1»).Protect «Password» Protect but Allow VBA Access Sheets(«Sheet1»).Protect UserInterfaceOnly:=True Unprotect All Sheets Dim ws As Worksheet

For Each ws In Worksheets
ws.Unprotect «password»
Next ws

VBA Code Examples Add-in

Easily access all of the code examples found on our site.

Simply navigate to the menu, click, and the code will be inserted directly into your module. .xlam add-in.

Источник

In this article you will be learning about sheets vs worksheets in excel VBA and how to use of these functions when manipulating spreadsheets.

Table of Contents

  • Difference between Worksheets and Sheets in VBA
  • Sheets
    • Looping through each Object in the Sheets collection
    • Looping through every Sheet in the Sheets collection
  • Worksheets
    • Referencing a Worksheet in VBA
      • Using the Worksheet Name
      • Using the Index Number
      • Using the Worksheet Code Name
      • Referring to a Worksheet in a Different Workbook
    • Adding a Worksheet
    • Deleting a Worksheet
      • Delete a specific worksheet.
    • Renaming the Worksheets
    • Adding Multiple Sheets
    • Assigning Worksheet Object to a Variable
    • Hide Worksheets Using VBA
    • To unhide the sheets
    • Hide Sheets Based on the Text in it
    • Sorting the Worksheets in an Alphabetical Order
    • Creating a Table of Contents of All Worksheets with Hyperlinks

Difference between Worksheets and Sheets in VBA

In VBA, you have two collections that can be a bit confusing at times. In a workbook, you can have worksheets and as well as chart sheets.

In Excel VBA:

  • The ‘Worksheets’ collection would refer to the collection of all the worksheet objects in a workbook.
  • The ‘Sheets’ collection would refer to all the worksheets as well as chart sheets in the workbook.

To run the VBA code in Excel, perform the following first

  •   Under the developer tab, click visual basic
  •   Click the insert option and choose a module
  •   Enter your codes and click run.

Now we know, ‘sheets’ is the collection of worksheets and chart sheets.

Looping through each Object in the Sheets collection

To loop through every sheet,

Code:

Sub UsingObject()

Dim obj As Object

For Each obj In ActiveWorkbook.Sheets

    MsgBox obj.Name

Next obj

End Sub

Looping through every Sheet in the Sheets collection

We can also count the sheets, then loop using a For loop.

Code

Sub UsingCount()

Dim i As Integer

For i = 1 To Sheets.Count

    MsgBox Sheets(i).Name

Next i

End Sub

This method of looping by counting the objects will work equally well with Charts and Worksheets.

Worksheets

When you have to work with worksheets only, use the ‘Worksheets’ collection, and when you have to refer to all sheets, then use the ‘Sheets’ collection.

Let’s see worksheets in detail.

Referencing a Worksheet in VBA

You can refer a worksheet in the following methods.

Using the Worksheet Name

This is the easiest way to refer to a worksheet.

When you are working with a workbook with three worksheets namely Sheet 1, Sheet 2, Sheet 3 (which is common in any excel file) and you want to activate Sheet 3.

Use the following code:

Code:

Sub ActivateSheet()

Worksheets("Sheet3").Activate

End Sub

You can also use the sheets collection method to activate the sheets, as we are using the name of the sheet as the key point.

Use this code

Code:

Sub ActivateSheet()

Sheets("Sheet3").Activate

End Sub

Using the Index Number

The difficult part of using the name of the sheet to refer them is you need to know the exact name of the sheet or the program doesn’t work.

In this case, you can use the index number of the worksheets. The indexing starts from 1 in the collection of sheets.

Use this code to activate Sheet3:

Code

Sub ActivateSheet()

Worksheets(3).Activate

End Sub

Important: A chart sheet is not a part of the worksheets collection.

This is because when we use the index numbers in the Worksheet collection, it will only refer to the worksheets in the workbook.

Note: Indexing goes from left to right. So if you shift Sheet3 to the left of Sheet2, then Worksheets (2) would refer to Sheet3.

Using the Worksheet Code Name

You can use the code name of the worksheet to refer to a worksheet.  This code name can be assigned in the VB Editor and it won’t change when you change the name of the worksheet.

To give your worksheet a code name, follow these steps:

  • Under the Developer tab, click the Visual Basic option.
  •  This will open the VB Editor.
  • Now, Click the View option in the menu and click on Project Window.
  • Click on the sheet name in the project explorer that you want to rename.
  • In the Properties pane, change the name in the field in front of (Name).

Note: Don’t include spaces in the name.

This would change the name of your Worksheet in the VBA, i.e., the code name. Therefore, when you change the worksheet name it doesn’t affect the code in your VBA.

Now, you can use either the Worksheets collection to refer to the worksheet or use the codename.

The following code uses both worksheet collection method and name of the sheet method.

Code

Worksheets("Sheet3").Activate

SH3.Activate

(I have code named my sheet as SH3)

Referring to a Worksheet in a Different Workbook

If you need to access a worksheet in a different workbook,

Code

Sub SheetActivate()

Workbooks("Examples.xlsx").Worksheets("Sheet1").Activate

End Sub

Adding a Worksheet

When you need to add a worksheet

Code

Sub AddSheet()

Worksheets.Add

End Sub

Deleting a Worksheet

When you want to delete a worksheet:

Code

Sub DeleteSheet()

ActiveSheet.Delete

End Sub

Click ok on the warning prompt. The worksheet gets deleted.

To avoid the warning prompt, use the below code:

Code

Sub DeleteSheet()

Application.DisplayAlerts = False

ActiveSheet.Delete

Application.DisplayAlerts = True

End Sub

Note: You can’t undo this delete option. So be sure.

Delete a specific worksheet.

If you want to delete a specific sheet,

Code

Sub DeleteSheet()

Worksheets("Sheet3").Delete

End Sub

You can also use the code name of the sheet to delete it.

Sub DeleteSheet()

SH3.Delete

End Sub

Renaming the Worksheets

When you want to rename the sheets using VBA code:

Sub RenameSheet()

Worksheets("Sheet1").Name = "Naming sheet"

End Sub

Code

Adding Multiple Sheets

When you need to add multiple sheets

Code

Sub RenameSheet()

Dim Countsheets As Integer

Countsheets = Worksheets.Count

For i = 1 To 4

Worksheets.Add after:=Worksheets(Countsheets + i – 1)

Worksheets(Countsheets + i).Name = "Multiple Sheets 1" & i

Next i

End Sub

Assigning Worksheet Object to a Variable

You can assign a worksheet to an object variable, and then use the variable instead of the worksheet references.

Code

Sub RenameSheet()

Dim Ws As Worksheet

For Each Ws In Worksheets

Ws.Name = "Assigning Variable " & Ws.Name

Next Ws

End Sub

Hide Worksheets Using VBA

You can hide and unhide worksheets using VBA. Normally when a worksheet is hidden, you can easily unhide the worksheet by right-clicking on any sheet tab.

But if you don’t want to unhide the worksheet in this method, you can do this using VBA.

The code below would hide all the worksheets in the workbook (except the active sheet), such that you cannot unhide it by right-clicking on the sheet name.

Code

Sub HideAllExcetActiveSheet()

Dim Ws As Worksheet

For Each Ws In ThisWorkbook.Worksheets

If Ws.Name <> ActiveSheet.Name Then Ws.Visible = xlSheetVeryHidden

Next Ws

End Sub

If you want to hide sheets that can be unhidden easily, use the below code.

Code

Sub HideAllExceptActiveSheet()

Dim Ws As Worksheet

For Each Ws In ThisWorkbook.Worksheets

If Ws.Name <> ActiveSheet.Name Then Ws.Visible = xlSheetHidden

Next Ws

End Sub

To unhide the sheets

Code:

Sub UnhideAllWoksheets()

Dim Ws As Worksheet

For Each Ws In ThisWorkbook.Worksheets

Ws.Visible = xlSheetVisible

Next Ws

End Sub

Hide Sheets Based on the Text in it

You can hide sheets based on the text in it. You can do this using the VBA INSTR function.

The below code would hide all the sheets except the ones with the text 2020 in it.

Code:

Sub HideWithMatchingText()

Dim Ws As Worksheet

For Each Ws In Worksheets

If InStr(1, Ws.Name, "2020", vbBinaryCompare) = 0 Then

Ws.Visible = xlSheetHidden

End If

Next Ws

End Sub

Sorting the Worksheets in an Alphabetical Order

Using VBA, you can quickly sort the worksheets based on their names.

Use the below code to quickly sort sheets in an ascending order.

Code

Sub SortSheetsTabName()

Application.ScreenUpdating = False

Dim ShCount As Integer, i As Integer, j As Integer

ShCount = Sheets.Count

For i = 1 To ShCount – 1

For j = i + 1 To ShCount

If Sheets(j).Name < Sheets(i).Name Then

Sheets(j).Move before:=Sheets(i)

End If

Next j

Next i

Application.ScreenUpdating = True

End Sub

Creating a Table of Contents of All Worksheets with Hyperlinks

To create a table of contents of all worksheets:

Code

Sub AddIndexSheet()

Worksheets.Add

ActiveSheet.Name = "Index"

For i = 2 To Worksheets.Count

ActiveSheet.Hyperlinks.Add Anchor:=Cells(i – 1, 1), _

Address:="", SubAddress:=Worksheets(i).Name & "!A1", _

TextToDisplay:=Worksheets(i).Name

Next i

End Sub

The above code inserts a new worksheet and names it Index.

It then loops through all the worksheets and creates a hyperlink for all the worksheets in the Index sheet.

  • #2

The SHEETS object is a parent object for:
Worksheets
Chart Sheets

If a workbook has 3 worksheets and 1 chart sheet, in VBA:
Sheets.Count will include both types. 4
Worksheets.Count will include only worksheets. 3

Does that help?

  • #3

Awesome Ron, now I understand! Thank you for taking the time to explain it.

  • #4

The SHEETS object is a parent object for:
Worksheets
Chart Sheets

A parent object for Sheets/Worksheets collection is Workbook.

  • #5

Almost 1:30am here……Worksheets…..for me to hide from my boss in the morning!

Sheets……for me, any minute soon, with a pillow and duvet of course lol

:LOL:

  • #6

A parent object for Sheets/Worksheets collection is Workbook.

True, I used the wrong word…
Sheets is a collection of Charts and Worksheets.

  • #7

Not really relevant, as you probably will never encounter it.

Sheets collection contains all types of sheets. Although today we only use 2 types of Sheets, Worksheets and Chart Sheets, there used to be 3 more types of Sheets, like Dialog Sheets or Macro Sheets. You may still have in your company old excel files that use them. In that case if you check the Sheets collection you’ll seem them all there.

In conclusion

Sheets — collection of the Sheets of all types
Worksheets — collection of Sheets of type Worksheet
Charts — collection of Sheets of type Chart Sheet

  • #8

/! In VBA you should use Worksheets() instead of Sheets() when referencing a sheet from another sheet in a formula. This solved some issues i had, maybe you need to be specific about the sheet type this way.

Not really relevant, as you probably will never encounter it.

Sheets collection contains all types of sheets. Although today we only use 2 types of Sheets, Worksheets and Chart Sheets, there used to be 3 more types of Sheets, like Dialog Sheets or Macro Sheets. You may still have in your company old excel files that use them. In that case if you check the Sheets collection you’ll seem them all there.

In conclusion

Sheets — collection of the Sheets of all types
Worksheets — collection of Sheets of type Worksheet
Charts — collection of Sheets of type Chart Sheet

In this Article

  • Sheets Vs. Worksheets
  • Referencing Sheets
    • ActiveSheet
    • Sheet Name
    • Sheet Index Number
    • Sheet “Code Name”
    • Referencing Sheets in Other Workbooks
  • Activate vs. Select Sheet
    • Activate a Sheet
    • Select a Sheet
    • Select Multiple Sheets
  • Worksheet Variable
  • Loop Through All Sheets in Workbook
  • Worksheet Protection
    • Workbook Protection
    • Worksheet Protection
    • Protect Worksheet
    • Unprotect Worksheet
  • Worksheet Visible Property
    • Unhide Worksheet
    • Hide Worksheet
    • Very Hide Worksheet
  • Worksheet-Level Events
    • Worksheet Activate Event
    • Worksheet Change Event
  • Worksheet Cheat Sheet
  • VBA Worksheets Cheatsheet

This is the ultimate guide to working with Excel Sheets / Worksheets in VBA.

At the bottom of this guide, we’ve created a cheat sheet of common commands for working with sheets.

Sheets Vs. Worksheets

There are two ways to reference Sheets using VBA. The first is with the Sheets object:

Sheets("Sheet1").Activate

The other is with the Worksheets object:

Worksheets("Sheet1").Activate

99% of the time, these two objects are identical. In fact, if you’ve searched online for VBA code examples, you’ve probably seen both objects used. Here is the difference:

The Sheets Collection contains Worksheets AND Chart Sheets.

vba sheets worksheets

So use Sheets if you want to include regular Worksheets AND Chart Sheets. Use Worksheets if you want to exclude Chart Sheets. For the rest of this guide we will use Sheets and Worksheets interchangeably.

Referencing Sheets

There are several different ways to reference Sheets:

  • ActiveSheet
  • Sheet Tab Name
  • Sheet Index Number
  • Sheet Code Name

ActiveSheet

The ActiveSheet is the Sheet that’s currently active. In other words, if you paused your code and looked at Excel, it’s the sheet that is visible. The below code example will display a MessageBox with the ActiveSheet name.

MsgBox ActiveSheet.Name

Sheet Name

You are probably most familiar with referencing Sheets by their Tab Name:

vba sheet tab name

Sheets("TabName").Activate

This is the sheet name that’s visible to Excel users. Enter it into the sheets object, as a string of text, surrounded by quotations.

Sheet Index Number

The Sheet Index number is the sheet position in the workbook. 1 is the first sheet. 2 is the second sheet etc.:

vba sheet index position

Sheets(1).Activate

Sheet Index Number – Last Sheet in Workbook

To reference the last Sheet in the workbook, use Sheets.Count to get the last Index Number and activate that sheet:

Sheets(Sheets.Count).Activate

Sheet “Code Name”

The Sheet Code Name is it’s Object name in VBA:

vba sheet code name

CodeName.Activate

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Referencing Sheets in Other Workbooks

It’s also easy to reference Sheets in other Workbooks. To do so, you need to use the Workbooks Object:

Workbooks("VBA_Examples.xlsm").Worksheets("Sheet1").Activate

Important: The Workbook must be open before you can reference its Sheets.

Activate vs. Select Sheet

In another article we discuss everything about activating and selecting sheets. The short version is this:

When you Activate a Sheet it becomes the ActiveSheet. This is the sheet you would see if you looked at your Excel program. Only one sheet may be activate at a time.

Activate a Sheet

Sheets("Sheet1").Activate

When you select a Sheet, it also becomes the ActiveSheet. However, you can select multiple sheets at once. When multiple sheets are selected at once, the “top” sheet is the ActiveSheet. However, you can toggle the ActiveSheet within selected sheets.

VBA Programming | Code Generator does work for you!

Select a Sheet

Sheets("Sheet1").Select

Select Multiple Sheets

Use an array to select multiple sheets at once:

Worksheets(Array("Sheet2", "Sheet3")).Select

Worksheet Variable

Assigning a worksheet to an object variable allows you to reference the worksheet by it’s variable name. This can save a lot of typing and make your code easier to read. There are also many other reasons you might want to use variables.

To declare a worksheet variable:

Dim ws as worksheet

Assign a worksheet to a variable:

Set ws = Sheets("Sheet1")

Now you can reference the worksheet variable in your code:

ws.Activate

Loop Through All Sheets in Workbook

Worksheet variables are useful when you want to loop through all the worksheets in a workbook. The easiest way to do this is:

Dim ws as Worksheet

For Each ws in Worksheets
  MsgBox ws.name
Next ws

This code will loop through all worksheets in the workbook, displaying each worksheet name in a message box. Looping through all the sheets in a workbook is very useful when locking / unlocking or hiding / unhiding multiple worksheets at once.

Worksheet Protection

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Workbook Protection

vba protect workbook

Workbook protection locks the workbook from structural changes like adding, deleting, moving, or hiding worksheets.

You can turn on workbook protection using VBA:

ActiveWorkbook.Protect Password:="Password"

or disable workbook protection:

ActiveWorkbook.UnProtect Password:="Password"

Note: You can also protect / unprotect without a password by omitting the Password argument:

ActiveWorkbook.Protect

Worksheet Protection

Worksheet-level protection prevents changes to individual worksheets.

Protect Worksheet

Worksheets("Sheet1").Protect "Password"

Unprotect Worksheet

Worksheets("Sheet1").Unprotect "Password"

There are a variety of options when protecting worksheets (allow formatting changes, allow user to insert rows, etc.)  We recommend using the Macro Recorder to record your desired settings.

We discuss worksheet protection in more detail here.

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Worksheet Visible Property

You might already know that worksheets can be hidden:

vba hide sheet

There are actually three worksheet visibility settings: Visible, Hidden, and VeryHidden. Hidden sheets can be unhidden by any regular Excel user – by right-clicking in the worksheet tab area (shown above).  VeryHidden sheets can only be unhidden with VBA code or from within the VBA Editor.  Use the following code examples to hide / unhide worksheets:

Unhide Worksheet

Worksheets("Sheet1").Visible = xlSheetVisible

Hide Worksheet

Worksheets("Sheet1").visible = xlSheetHidden

Very Hide Worksheet

Worksheets("Sheet1").Visible = xlSheetVeryHidden

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Worksheet-Level Events

Events are triggers that can cause “Event Procedures” to run. For example, you can cause code to run every time any cell on a worksheet is changed or when a worksheet is activated.

Worksheet event procedures must be placed in a worksheet module:

vba worksheet module

There are numerous worksheet events. To see a complete list, go to a worksheet module, select “Worksheet” from the first drop-down. Then selecting an event procedure from the second drop-down to insert it into the module.

vba worksheet events

Worksheet Activate Event

Worksheet activate events run each time the worksheet is opened.

Private Sub Worksheet_Activate()
  Range("A1").Select
End Sub

This code will select cell A1 (resetting the view area to the top-left of the worksheet) each time the worksheet is opened.

Worksheet Change Event

Worksheet change events run whenever a cell value is changed on the worksheet. Read our tutorial about Worksheet Change Events for more information.

Worksheet Cheat Sheet

Below you will find a cheat sheet containing common code examples for working with sheets in VBA

VBA Worksheets Cheatsheet

VBA worksheets Cheatsheet

Description Code Example
Referencing and Activating Sheets
Tab Name Sheets(«Input»).Activate
VBA Code Name Sheet1.Activate
Index Position Sheets(1).Activate
Select Sheet
Select Sheet Sheets(«Input»).Select
Set to Variable Dim ws as Worksheet
Set ws = ActiveSheet
Name / Rename ActiveSheet.Name = «NewName»
Next Sheet ActiveSheet.Next.Activate
Loop Through all Sheets Dim ws as Worksheet

For each ws in Worksheets
Msgbox ws.name
Next ws

Loop Through Selected Sheets Dim ws As Worksheet

For Each ws In ActiveWindow.SelectedSheets
MsgBox ws.Name
Next ws

Get ActiveSheet MsgBox ActiveSheet.Name
Add Sheet Sheets.Add
Add Sheet and Name Sheets.Add.Name = «NewSheet»
Add Sheet With Name From Cell Sheets.Add.Name = range(«a3»).value
Add Sheet After Another Sheets.Add After:=Sheets(«Input»)
Add Sheet After and Name Sheets.Add(After:=Sheets(«Input»)).Name = «NewSheet»
Add Sheet Before and Name Sheets.Add(Before:=Sheets(«Input»)).Name = «NewSheet»
Add Sheet to End of Workbook Sheets.Add After:=Sheets(Sheets.Count)
Add Sheet to Beginning of Workbook Sheets.Add(Before:=Sheets(1)).Name = «FirstSheet»
Add Sheet to Variable Dim ws As Worksheet
Set ws = Sheets.Add
Copy Worksheets
Move Sheet to End of Workbook Sheets(«Sheet1»).Move After:=Sheets(Sheets.Count)
To New Workbook Sheets(«Sheet1»).Copy
Selected Sheets To New Workbook ActiveWindow.SelectedSheets.Copy
Before Another Sheet Sheets(«Sheet1»).Copy Before:=Sheets(«Sheet2»)
Before First Sheet Sheets(«Sheet1»).Copy Before:=Sheets(1)
After Last Sheet Sheets(«Sheet1»).Copy After:=Sheets(Sheets.Count)
Copy and Name Sheets(«Sheet1»).Copy After:=Sheets(Sheets.Count)
ActiveSheet.Name = «LastSheet»
Copy and Name From Cell Value Sheets(«Sheet1»).Copy After:=Sheets(Sheets.Count)
ActiveSheet.Name = Range(«A1»).Value
To Another Workbook Sheets(«Sheet1»).Copy Before:=Workbooks(«Example.xlsm»).Sheets(1)
Hide / Unhide Sheets
Hide Sheet Sheets(«Sheet1»).visible = False
or
Sheets(«Sheet1»).visible = xlSheetHidden
Unhide Sheet Sheets(«Sheet1»).Visible = True
or
Sheets(«Sheet1»).Visible = xlSheetVisible
Very Hide Sheet Sheets(“Sheet1”).Visible = xlSheetVeryHidden
Delete or Clear Sheets
Delete Sheet Sheets(«Sheet1»).Delete
Delete Sheet (Error Handling) On Error Resume Next
Sheets(«Sheet1»).Delete
On Error GoTo 0
Delete Sheet (No Prompt) Application.DisplayAlerts = False
Sheets(«Sheet1»).Delete
Application.DisplayAlerts = True
Clear Sheet Sheets(«Sheet1»).Cells.Clear
Clear Sheet Contents Only Sheets(«Sheet1»).Cells.ClearContents
Clear Sheet UsedRange Sheets(«Sheet1»).UsedRange.Clear
Protect or Unprotect Sheets
Unprotect (No Password) Sheets(«Sheet1»).Unprotect
Unprotect (Password) Sheets(«Sheet1»).Unprotect «Password»
Protect (No Password) Sheets(«Sheet1»).Protect
Protect (Password) Sheets(«Sheet1»).Protect «Password»
Protect but Allow VBA Access Sheets(«Sheet1»).Protect UserInterfaceOnly:=True
Unprotect All Sheets Dim ws As Worksheet

For Each ws In Worksheets
ws.Unprotect «password»
Next ws

Понравилась статья? Поделить с друзьями:
  • Excel sheet not show
  • Excel row one hidden
  • Excel row not to move
  • Excel row index vba
  • Excel round all numbers