VBA: Qualify Worksheets for dynamic range

后端 未结 3 862
走了就别回头了
走了就别回头了 2021-01-28 21:22

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:

3条回答
  •  故里飘歌
    2021-01-28 21:55

    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:

    1. Sheet 2 A1 has "First sheet named "2" "
    2. Sheet 1 A1 has "Second Sheet named "1" "
    3. Sheet 3 A1 has "Third sheet named "3" "

    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.

提交回复
热议问题