Vba excel sheets by name

I have the name of a worksheet stored as a string in a variable. How do I perform some operation on this worksheet?

I though I would do something like this:

nameOfWorkSheet = "test"
ActiveWorkbook.Worksheets(nameOfWorkSheet).someOperation()

How do I get this done?

asked Mar 9, 2012 at 3:51

Jonson Bylvaklov's user avatar

4

There are several options, including using the method you demonstrate, With, and using a variable.

My preference is option 4 below: Dim a variable of type Worksheet and store the worksheet and call the methods on the variable or pass it to functions, however any of the options work.

Sub Test()
  Dim SheetName As String
  Dim SearchText As String
  Dim FoundRange As Range

  SheetName = "test"      
  SearchText = "abc"

  ' 0. If you know the sheet is the ActiveSheet, you can use if directly.
  Set FoundRange = ActiveSheet.UsedRange.Find(What:=SearchText)
  ' Since I usually have a lot of Subs/Functions, I don't use this method often.
  ' If I do, I store it in a variable to make it easy to change in the future or
  ' to pass to functions, e.g.: Set MySheet = ActiveSheet
  ' If your methods need to work with multiple worksheets at the same time, using
  ' ActiveSheet probably isn't a good idea and you should just specify the sheets.

  ' 1. Using Sheets or Worksheets (Least efficient if repeating or calling multiple times)
  Set FoundRange = Sheets(SheetName).UsedRange.Find(What:=SearchText)
  Set FoundRange = Worksheets(SheetName).UsedRange.Find(What:=SearchText)

  ' 2. Using Named Sheet, i.e. Sheet1 (if Worksheet is named "Sheet1"). The
  ' sheet names use the title/name of the worksheet, however the name must
  ' be a valid VBA identifier (no spaces or special characters. Use the Object
  ' Browser to find the sheet names if it isn't obvious. (More efficient than #1)
  Set FoundRange = Sheet1.UsedRange.Find(What:=SearchText)

  ' 3. Using "With" (more efficient than #1)
  With Sheets(SheetName)
    Set FoundRange = .UsedRange.Find(What:=SearchText)
  End With
  ' or possibly...
  With Sheets(SheetName).UsedRange
    Set FoundRange = .Find(What:=SearchText)
  End With

  ' 4. Using Worksheet variable (more efficient than 1)
  Dim MySheet As Worksheet
  Set MySheet = Worksheets(SheetName)
  Set FoundRange = MySheet.UsedRange.Find(What:=SearchText)

  ' Calling a Function/Sub
  Test2 Sheets(SheetName) ' Option 1
  Test2 Sheet1 ' Option 2
  Test2 MySheet ' Option 4

End Sub

Sub Test2(TestSheet As Worksheet)
    Dim RowIndex As Long
    For RowIndex = 1 To TestSheet.UsedRange.Rows.Count
        If TestSheet.Cells(RowIndex, 1).Value = "SomeValue" Then
            ' Do something
        End If
    Next RowIndex
End Sub

answered Mar 9, 2012 at 5:29

Ryan's user avatar

The best way is to create a variable of type Worksheet, assign the worksheet and use it every time the VBA would implicitly use the ActiveSheet.

This will help you avoid bugs that will eventually show up when your program grows in size.

For example something like Range("A1:C10").Sort Key1:=Range("A2") is good when the macro works only on one sheet. But you will eventually expand your macro to work with several sheets, find out that this doesn’t work, adjust it to ShTest1.Range("A1:C10").Sort Key1:=Range("A2")… and find out that it still doesn’t work.

Here is the correct way:

Dim ShTest1 As Worksheet
Set ShTest1 = Sheets("Test1")
ShTest1.Range("A1:C10").Sort Key1:=ShTest1.Range("A2")

answered Sep 22, 2014 at 18:02

stenci's user avatar

stencistenci

8,11014 gold badges63 silver badges101 bronze badges

To expand on Ryan’s answer, when you are declaring variables (using Dim) you can cheat a little bit by using the predictive text feature in the VBE, as in the image below. screenshot of predictive text in VBE

If it shows up in that list, then you can assign an object of that type to a variable. So not just a Worksheet, as Ryan pointed out, but also a Chart, Range, Workbook, Series and on and on.

You set that variable equal to the object you want to manipulate and then you can call methods, pass it to functions, etc, just like Ryan pointed out for this example. You might run into a couple snags when it comes to collections vs objects (Chart or Charts, Range or Ranges, etc) but with trial and error you’ll get it for sure.

answered Mar 9, 2012 at 16:02

j boschiero's user avatar

j boschieroj boschiero

4801 gold badge3 silver badges13 bronze badges

Содержание

  1. VBA: Finding a sheet by name across workbooks and copy a sheet next to it
  2. 1 Answer 1
  3. Related
  4. Hot Network Questions
  5. Subscribe to RSS
  6. Excel VBA Video Training / EXCEL DASHBOARD REPORTS
  7. Sheets Tab Name
  8. Index Number
  9. Sheets Code Name
  10. One Draw back
  11. Excel VBA Video Training / EXCEL DASHBOARD REPORTS
  12. Reference excel worksheet by name?
  13. 3 Answers 3
  14. Refer to sheet using codename
  15. 5 Answers 5
  16. 10 ways to reference Excel workbooks and sheets using VBA
  17. Account Information
  18. Share with Your Friends
  19. 10 ways to reference Excel workbooks and sheets using VBA
  20. What’s hot at TechRepublic
  21. 1: Reference the active workbook
  22. Figure A
  23. 2: Reference the workbook that’s currently running code
  24. Figure B
  25. 3: Reference workbooks in the Workbooks collection
  26. Figure C
  27. 4: Explicitly reference a workbook
  28. 5: Reference workbooks by index
  29. 6: Reference the active sheet
  30. 7: Reference Worksheet objects
  31. 8: Explicitly reference sheets
  32. 9: Reference sheets by index
  33. 10: Refer to a sheet’s code name property
  34. Figure D
  35. Figure E
  36. Also see
  37. Daily Tech Insider Newsletter

VBA: Finding a sheet by name across workbooks and copy a sheet next to it

I am kind of lost with the workbook reference and nesting if condition. What I want to achieve is,

  1. Find a workbook which has a sheet name say «EMPLOYEE».
  2. Check is there any sheet name say «COMPANY» in the above workbook, Delete if exist.
  3. Copy sheet «COMPANY» from the Active workbook (not active sheet) to the above workbook.

I am reaching so far but not sure how to copy the non-active-sheet «COMPANY» from the active workbook to the workbook which we find in point 1.

Any suggestion will be much appreciated.

1 Answer 1

By Active workbook do you mean the one with the code module running the operation? If that is the case, then ThisWorkbook can be used to reference it as the parent of the Company worksheet you wish to copy to the workbook you just deleted a Company worksheet from.

I find ThisWorkbook to be more definitive than ActiveWorkbook particularly in operations like this where the focus may (by default) be changed to the workbook receiving the copy of the Company worksheet.

Alternately, you can assign a worksheet object reference to the Company worksheet you wish to copy across and use that reference repeatedly as you progress through the workbooks collection.

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.3.17.43323

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Excel VBA Video Training / EXCEL DASHBOARD REPORTS

Back to: Excel VBA . Got any Excel/VBA Questions? Free Excel Help

Sheets Tab Name

If you have ever recorded a macro in Excel that references a specific sheet in the Workbook you will know that the code will only continue to work if the Sheet name(s) remain the same. For example, code like; Sheets(«Budget»).Select will no longer work should the Budget Sheet be re-named. This is because the macro recorder generates such code based on the Sheets tab name, the name we see when in Excel. If it makes you feel better, many VBA coders also use the Sheet tab names over two much better ways, as they know no better.

Index Number

A sheets Index number is determined by its position in the Workbook. The left most sheet will always have an Index number of 1, the next on the right will be 2 and so on. Excel VBA allows us to specify any Sheet by using it’s Index number, but unfortunately this method is not used by Excel when we record a macro. It uses the Sheets Tab name like; Sheets(«Budget»).Select If this sheet was the third from the left we could use: Sheets(3).Select. This is often a better option than using the sheet tab name, but still has potential problems. By this I mean, the sheets position in the Workbook could change if we add, remove or move sheets.

Sheets Code Name

This is the method used by savvy VBA coders. Each Sheet in a Workbook is given a unique CodeName that does not change even when that sheet is moved, renamed or other sheets are added. Each sheets CodeName can only be seen by going into the Visual Basic Editor (Tools>Macro>Visual Basic Editor Alt+F11) and then displaying the Project Explorer (View>Project Explorer Ctl+R)

In the screen shot above, the CodeName for the sheet with a tab name of Budget is Sheet3. A sheets CodeName is always the name not inside the parenthesis when looking in the Project Explorer. We can reference this sheet with VBA code in the Workbook by using: Sheet3.Select as apposed to Sheets(«Budget»).Select or Sheets(3).Select

If your Workbook is already full of VBA code, recorded or written, that does not use the CodeName you can change it on a Project level (all code in all Modules in the Workbook) by going to Edit>Replace while in the VBE (Visual Basic Editor).

One Draw back

The only times you cannot use a sheets CodeName is when you reference a Sheet that is in a different Workbook to the one that the code resides.

Special! Free Choice of Complete Excel Training Course OR Excel Add-ins Collection on all purchases totaling over $64.00. ALL purchases totaling over $150.00 gets you BOTH! Purchases MUST be made via this site . Send payment proof to [email protected] 31 days after purchase date.

Instant Download and Money Back Guarantee on Most Software

Excel VBA Video Training / EXCEL DASHBOARD REPORTS

Excel Trader Package Technical Analysis in Excel With $139.00 of FREE software!

Microsoft ® and Microsoft Excel ® are registered trademarks of Microsoft Corporation. OzGrid is in no way associated with Microsoft

Источник

Reference excel worksheet by name?

I have the name of a worksheet stored as a string in a variable. How do I perform some operation on this worksheet?

I though I would do something like this:

How do I get this done?

3 Answers 3

There are several options, including using the method you demonstrate, With, and using a variable.

My preference is option 4 below: Dim a variable of type Worksheet and store the worksheet and call the methods on the variable or pass it to functions, however any of the options work.

The best way is to create a variable of type Worksheet , assign the worksheet and use it every time the VBA would implicitly use the ActiveSheet .

This will help you avoid bugs that will eventually show up when your program grows in size.

For example something like Range(«A1:C10»).Sort Key1:=Range(«A2») is good when the macro works only on one sheet. But you will eventually expand your macro to work with several sheets, find out that this doesn’t work, adjust it to ShTest1.Range(«A1:C10»).Sort Key1:=Range(«A2») . and find out that it still doesn’t work.

Here is the correct way:

To expand on Ryan’s answer, when you are declaring variables (using Dim) you can cheat a little bit by using the predictive text feature in the VBE, as in the image below.

If it shows up in that list, then you can assign an object of that type to a variable. So not just a Worksheet, as Ryan pointed out, but also a Chart, Range, Workbook, Series and on and on.

You set that variable equal to the object you want to manipulate and then you can call methods, pass it to functions, etc, just like Ryan pointed out for this example. You might run into a couple snags when it comes to collections vs objects (Chart or Charts, Range or Ranges, etc) but with trial and error you’ll get it for sure.

Источник

Refer to sheet using codename

I get a «type mismatch» error in this code:

My sheet’s CodeName is ‘sheet1’ .

Can someone please help me remove the error?

5 Answers 5

1) Refer to sheet by Index:

The `Index’ is dependent on the «order of sheets in the workbook». If you shuffle your sheets order, this may not refer to the same sheet any more!

2) Refer to sheet by Name:

This is the .Name property of a worksheet, and is the name visible in the Excel worksheet tab and in brackets in the VBA Project Explorer.

3) Refer to sheet by CodeName:

You suggested you actually wanted to use the .CodeName property of a worksheet. This cannot be reference within brackets like the above two examples, but does exist contrary to some answers above! It is assigned automatically to a sheet on creation, and is «Sheet» then the next unused number in the previously created CodeNames.

The advantage of using CodeName is that it doesn’t depend on the sheet order (unlike the Index ) and it doesn’t change if a user changes the Name simply by renaming the sheet in Excel.

The disadvantage is the code can be more convoluted or ambiguous. Since CodeName is read-only [1] this cannot be improved, but does ensure the above advantages! See the referenced documentation for more details.

First way of using it: directly.

Second way of using it: indirectly, may offer more clarity or flexibility, shows how to use the CodeName property of a worksheet.

By looping over sheets and reading the CodeName property, you can first find either the Index or Name property of your desired sheet. Then your can use this to reference the sheet.

Источник

10 ways to reference Excel workbooks and sheets using VBA

Account Information

10 ways to reference Excel workbooks and sheets using VBA

10 ways to reference Excel workbooks and sheets using VBA

Excel offers myriad options for referring to workbooks and sheets in your VBA code. See which methods make sense in which situations.

We may be compensated by vendors who appear on this page through methods such as affiliate links or sponsored partnerships. This may influence how and where their products appear on our site, but vendors cannot pay to influence the content of our reviews. For more info, visit our Terms of Use page.

Referencing workbooks and sheets programmatically generates a lot of confusion because there are so many possibilities. No method is superior; they all have their place. The purpose at hand will define which referencing method is the most efficient.

Note: This article is also available as a PDF download.

What’s hot at TechRepublic

1: Reference the active workbook

VBA’s ActiveWorkbook property refers to the workbook with the focus. The active workbook may or may not contain the code that’s referencing the active workbook, which is an important distinction. It’s perfectly acceptable to use this property to reference the active workbook from code inside the active workbook. However, it’s invaluable when referencing the active workbook remotely.

For example, after passing data to an active workbook, you’d probably want to save that workbook, which is a simple task for the ActiveWorkbook property. The following procedures use the ActiveWorkbook property to close the active workbook:

Of course, you could just as easily combine all three into a Select Case statement and use a single function to pass a conditional argument that specifies which save to execute.

Figure A

Figure A

Use the ActiveWorkbook property to return the active workbook’s full path and filename.

2: Reference the workbook that’s currently running code

VBA’s ThisWorkbook property is similar to the ActiveWorkbook property, but whereas ActiveWorkbook evaluates the workbook with the focus, ThisWorkbook refers to the workbook that’s running the current code. This added flexibility is great because the active workbook isn’t always the workbook that’s running code.

Figure B

As you can see, HumanResources.xls is the active workbook, but the function is in a workbook named 0908002.xls.

Figure B

Take advantage of ThisWorkbook’s flexibility when you need to refer to the workbook running code when the active workbook isn’t the workbook running code.

3: Reference workbooks in the Workbooks collection

The Workbooks collection contains all the open Workbook objects. Using the Workbooks property, you can refer to open workbooks. For instance, the following subprocedure populates a list box in a user form with the names of all open workbooks:

The resulting user form, shown in Figure C, displays a list of open workbooks. By referencing the Workbooks collection, you can reference all the open workbooks without hard-coding a single workbook name.

Figure C

Use the Workbooks collection to reference open workbooks.

Listing all the open workbooks is an easy enough task, thanks to the Workbooks collection. However, opening all of the workbooks in a specified folder is a bit harder, as you can see in the following subprocedure:

This task isn’t a referencing one in the true sense, but it shows the power of the Workbooks collection. In this case, the code doesn’t cycle through the Workbooks collection; it just takes advantage of one of the collection’s methods — specifically, the Open method. Closing all the open workbooks is a bit easier than opening them, as the following procedure shows:

To see a collection’s many methods and properties, press F2 in the VBE to launch the Object Browser.

4: Explicitly reference a workbook

If you know the name of the workbook you want to reference, an explicit reference might be the most efficient method. Although an explicit reference is easy, it does require a stable situation. If the name of the workbook changes, but the possibilities are known, you can still use an explicit reference by passing the workbook’s name. For example, the following subprocedure activates an open workbook, as determined by the passed argument, wbname:

To execute it, you simply pass the name of the workbook you want to activate as follows:

(You must include the .xls extension.)

The following function also uses the Workbooks property to determine whether a specific workbook is currently open:

If wbname is open, the function returns True. When not open, the function returns False. These procedures also rely on the Workbooks property, but instead of cycling through the collection, they specify a workbook by name.

5: Reference workbooks by index

Perhaps the least stable method for referencing a workbook is to use its index value. Excel assigns index values to workbooks as you open them. The first workbook opened has an index value of 1, the second workbook opened has an index value of 2, and so on.

Index values pose a special problem because they change when you delete a Workbook object from the collection; index values slip down a notch, accordingly. For example, suppose you have three open workbooks with the following index values:

If a particular task depends on all three workbooks always being open, using the index values can generate mistakes. For instance, the statement

activates HumanResources.xls as long as it’s open. If you close HumanResources.xls, ExcelStatisticalFunctions and 0908002.xls both move down a notch: ExcelStatisticalFunctions becomes 2 and 0908002.xls becomes 1. As a result, the above statement activates 0908002.xls, not HumanResources. That may or may not be what you want. Using index values to reference workbooks isn’t wrong, but you must understand its inherent behaviors to avoid errors that can be difficult to troubleshoot.

6: Reference the active sheet

If you don’t specify an object qualifier, the ActiveSheet property defaults to the active sheet in the active workbook. For instance, to retrieve the name of the active sheet, you’d use a function similar to the following:

This property is read-only; you can’t use it to activate a sheet.

7: Reference Worksheet objects

The Worksheets collection contains all the sheet objects in a workbook. Using a simple For Each loop, you can cycle through the collection. For example, the following code populates a list box control with the names of all the sheets in the active workbook:

The Sheets and Worksheets collections both contain Worksheet objects, but the Sheets collection contains both worksheets and chart sheets.

8: Explicitly reference sheets

Use the Worksheets property to explicitly reference a sheet. For example, use this type of reference to delete a specific sheet as follows:

9: Reference sheets by index

Index values come in handy when you don’t care about specific sheets, but only their number or order. Granted, that’s not going to be a common task, but occasionally, referencing by index values can come in handy. The following procedure adds and deletes sheets based on the number of sheets you want:

Use caution when executing this function because it deletes the first Sheet object in the collection, even if that sheet contains content. It simply adds and deletes sheets, depending on the value you pass. This function is useful when creating new workbooks programmatically.

10: Refer to a sheet’s code name property

Code that refers to a Worksheet object by the name on the sheet’s tab runs the risk of generating an error. That’s because you must remember to update the code when you change the sheet’s name. Not only is that a lot of trouble, users are apt to change a sheet’s name. One way to safeguard code that refers to specific sheets by name is to use the CodeName property.

The code name is the sheet’s default name , which Excel assigns when you create it — Sheet1, Sheet2, and so on. Changing the sheet’s name, as displayed on the sheet’s tab, does not change its code name, as you can see in Figure D. The names in parentheses are the sheet names (as shown on the sheet tabs). Notice that the default names, the code names, remain the same even if you change the sheet’s name.

Figure D

A sheet’s code name property is stable; its sheet name is subject to change.

To change a sheet’s code name, use the (Name) property, as shown in Figure E. You must use the Visual Basic Editor (VBE), as you can’t change this property programmatically. There are two similar properties, so don’t confuse them. The Name property (without parentheses) toward the bottom of the properties list represents the name Excel displays on the sheet tab. (Code name values must start with a letter character.)

Figure E

Change the code name using the VBE.

Also see

  • How to add a drop-down list to an Excel cell (TechRepublic)
  • How to become a cloud engineer: A cheat sheet (TechRepublic)
  • 50 time-saving tips to speed your work in Microsoft Office (free PDF) (TechRepublic download)
  • Cost comparison calculator: G Suite vs. Office 365 (Tech Pro Research)
  • Microsoft Office has changed, how you use it should too (ZDNet)
  • Best cloud services for small businesses (CNET)
  • Best to-do list apps for managing tasks on any platform (Download.com)
  • More must-read Microsoft-related coverage (TechRepublic on Flipboard)

Affiliate disclosure: TechRepublic may earn a commission from the products and services featured on this page.

Daily Tech Insider Newsletter

Stay up to date on the latest in technology with Daily Tech Insider. We bring you news on industry-leading companies, products, and people, as well as highlighted articles, downloads, and top resources. You’ll receive primers on hot tech topics that will help you stay ahead of the game.

Источник

Return to VBA Code Examples

In this Article

  • Get Sheet Name
    • Get ActiveSheet Name
    • Get Sheet Name by index Number
    • Get Sheet Name by Code Name
  • Rename Sheet
    • Rename ActiveSheet
    • Rename Sheet by Name
    • Rename Sheet by Sheet Index Number
    • Rename Sheet by Code Name
  • Check if Sheet Name Exists
  • Copy Sheet and Rename

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:

vba sheet tab name

Get ActiveSheet Name

This will display the ActiveSheet name in a message box:

MsgBox ActiveSheet.Name

Get Sheet Name by index Number

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

MsgBox Sheets(1).Name

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

MsgBox Sheets(Sheets.Count).Name

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:

vba sheet code name

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

Sheets("TabName").Activate

or the VBA code name:

CodeName.Activate

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:

MsgBox CodeName.Name

Rename Sheet

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

Rename ActiveSheet

ActiveSheet.Name = "NewName"

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

Rename Sheet by Name

Sheets("OldSheet").Name = "NewName"

Rename Sheet by Sheet Index Number

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

Sheets(1).Name = "NewName"

Rename Sheet by Code Name

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

Component.Name = "NewName"

VBA Programming | Code Generator does work for you!

Check if Sheet Name Exists

We created a function to test if a Sheet with a particular name already exists.

'Test if a Range Exists on a Sheet.
'Leave range blank to test if sheet exists
'Inputs:
' WhatSheet - String Name of Sheet (ex "Sheet1")
' WhatRange (Optional, Default = "A1") - String Name of Range (ex "A1")
Function RangeExists(WhatSheet As String, Optional ByVal WhatRange As String = "A1") As Boolean
    Dim test As Range
    On Error Resume Next
    Set test = ActiveWorkbook.Sheets(WhatSheet).Range(WhatRange)
    RangeExists = Err.Number = 0
    On Error GoTo 0
End Function

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

Use the function like so:

Sub Test_SheetExists()
    MsgBox RangeExists("setup")
End Sub

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:

Sub CopySheetRename2()

    Sheets("Sheet1").Copy After:=Sheets(Sheets.Count)
    On Error Resume Next
    ActiveSheet.Name = "LastSheet"
    On Error GoTo 0

End Sub

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

  • #2

Hi, kilowatt,

it’s a bit confusing to me

do you want to check if a certain sheet already exists and if it exists it should be deleted ?
or did you have something else in mind ?

kind regards,
Erik

  • #3

Yes I need to find the sheet within a variable amount of sheets and then delete it if it exists.

  • #4

something like this might be usefull

Code:

Sub test()
    Dim x As Object, sh_name As String
    sh_name = "test"
    On Error Resume Next
    Set x = ActiveWorkbook.Sheets(sh_name)
      If Err <> 9 Then
      Sheets(sh_name).Delete
      End If
    On Error GoTo 0
    ' do your stuff
End Sub

  • #5

That works just as it should. Thank you.

However I have run into another problem as a result of deleting this sheet. If you know how to do it this way it would be better I think.

Here is what I do:

1. Initialize an arrary
2. Populate the arrary with values from a database
3. Cycle through the array and create a worksheet for every name in the arrary. This is where the value «Encyclopedia» comes from.

Here’s my problem now:

After I delete the sheet using your code I reference the array in sequential order to do a few other things and it chokes because «Encyclopedia» is not longer a valid worksheet.

If it possible to cycle through the array after it’s created and check to see if «Encyclopedia» exists and then delete it out of the array without leaving an empty spot in the array?

Example:

Arrary position 1=Fiction 2=Encyclopedia 3=Reference

Delete the value for position number 2 and then have the arrary read

Arrary position 1=Fiction 2=Reference

  • #6

After I delete the sheet using your code I reference the array in sequential order to do a few other things and it chokes because «Encyclopedia» is not longer a valid worksheet.

I thought you deleted the sheet to replace it with another version !?

can you clarify a bit more
I’m not sure at all what you’re asking now …

can you post the relevant part of your code ?
(please use the «code» button to display your code)

kind regards,
Erik

  • #7

Sorry it’s kind of hard to explain because some of the coding is in our own softwares language. But I’ll give it a whirl.

This code declares the array and then cycles through the array assigning the values to the corresponding location in the arrary. Then cycles through the new arrary to create the worksheets in the workbook.

Code:

Dim Title As String
Dim Temp As String
Dim First As String
Dim Names(10)
Dim i as Integer
Dim strDate as Integer

strDate = Format(Now(), "yyyy")
i=0

Title = "<gateway field name=NAME database=RLC>"
cells(3,4).value = "No. of Items " & strDate-13 & " and older"
cells(3,5).value = "No. of Items " & strDate-12 & " and newer"
cells(6,4).value = "(" & strDate-6 & " and older for encyclopedias)"
cells(6,5).value = "(" & strDate-5 & " and newer for encyclopedias)"

Sheets("Sheet1").Name = Title
First = Title
Temp = Title

<gateway cycle start=1 count=<gateway docs>>
Title = "<gateway field name=NAME database=RLC>"
Names(i) = Title
i=i+1
Cells(1, 1).Value = Title & " Collection Worksheet"
Cells(4, 1).Value = Title
Cells(25, 1).Value = Title
Sheets(Temp).Name = Title
Worksheets(First).Copy before:=Sheets("ExpSheet1")
Temp = First & " (2)"
<gateway endcycle>

Everything that is <gateway …> is our software’s code.

When this finishes running I get the following:

Names(0) = Non Fiction
Names(1) = Fiction
Names(2) = Perodical
Names(3) = Professional
Names(4) = Encyclopedia
Names(5) = Reference
Names(6) = Visual

As a result of the above code I end up with a workbook with 7 worksheets in it all named with one of the above values. Encylopedia can show up anywhere in the list or not at all.

The report I am working on right now happens to have the value Encyclopedia so I was wanting to delete the worksheet. The problem is that if I delete the worksheet when I reference the array later the array still has the value Encylcopedia in it.

So it it possible to cycle through the array before creating all the worksheets and removing the value Encyclopedia without leaving a sequencing gap in the arrary.

I run code after this that selects the first worksheet and then fills in a bunch of data and then goes to the next one and does the same thing.

If you need more info let me know.

  • #8

or I don’t understand what you are trying to do
or you make things more complicated then they should be

Yes I need to find the sheet within a variable amount of sheets and then delete it if it exists.

I thought you were asking to delete a sheet before you inserted another one with the same name
your last reponse is confusing now :confused: for me at least

let’s take a simple example
one workbook 3 sheets named «a», «b», «c»
what do you want to do now with those sheets ?

I run code after this that selects the first worksheet and then fills in a bunch of data and then goes to the next one and does the same thing.

what’s the problem ?
you can easily retrieve the remaining worksheetnames to see if you’re working with the right ones …

if this post is also confusing, I would suggest you start over from scratch as if we didn’t write anything here

kind regards,
Erik

  • #9

Yes, that is the right way to go. Prevention rather than cure.

Code:

Option Explicit
Option Base 0
    Sub removeAName(FromArr, RemoveWhat)
        Dim I As Long, J As Long
        On Error Resume Next
        I = Application.WorksheetFunction.Match(RemoveWhat, FromArr, 0) - 1
        If Err.Number <> 0 Then Exit Sub
        On Error GoTo 0
        For J = I To UBound(FromArr) - 1
            FromArr(J) = FromArr(J + 1)
            Next J
        ReDim Preserve FromArr(UBound(FromArr) - 1)
        End Sub
Sub testIt()
    Dim Names()
    ReDim Names(6)
    Names(0) = "Non Fiction"
    Names(1) = "Fiction"
    Names(2) = "Perodical"
    Names(3) = "Professional"
    Names(4) = "Encyclopedia"
    Names(5) = "Reference"
    Names(6) = "Visual"
    removeAName Names, "Perodical"
    Debug.Print Names(2) & ", " & UBound(Names)
    removeAName Names, "Encyclopedia"
    Debug.Print Names(3) & ", " & UBound(Names)
    End Sub

kilowatt said:

{snip}

So it it possible to cycle through the array before creating all the worksheets and removing the value Encyclopedia without leaving a sequencing gap in the arrary.

{snip}

  • #10

Thanks for all the help here guys I’ve been able to use your code to solve my problem.

Have a much larger problem to deal with now!!

Thanks again,

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.

Понравилась статья? Поделить с друзьями:
  • Vba excel range по номерам ячеек
  • Vba excel range количество строк
  • Vba excel range записать
  • Vba excel hyperlink cells
  • Vba excel http запросы