I am just getting started with VBA.
I have a workbook containing many numbered sheets (1,2,3,4 etc).
I now have read that Qualifying a Worksheet as per below:
Worksheets have an Index which is the order they are currently in within the workbook. So the leftmost worksheet is Worksheet(1). This is not necessarily the same as the name of the e.g. Worksheet("Sheet1") or Worksheet("1").
Say I have sheets "2" ,"1", "3", in that order in the workbook:
Then run the following:
Option Explicit
Public Sub test()
Dim arr(), i As Long
arr = Array("1", "2", "3") '<== Sheet names
Debug.Print "Looping by name: "
For i = LBound(arr) To UBound(arr) '<== Looping by name
Debug.Print ThisWorkbook.Worksheets(arr(i)).Range("A1").Value
Next i
Debug.Print String(40, Chr$(61))
Debug.Print vbNewLine
Debug.Print "Looping by sheet index: "
For i = 1 To ThisWorkbook.Worksheets.Count '<== Looping by index (order from left to right)
Debug.Print ThisWorkbook.Worksheets(i).Range("A1").Value
Next i
End Sub
You get:
Note: You can also For Each
over the Worksheet collection which will loop in the same order as by Index skipping any Chart sheet objects.