VBA: Qualify Worksheets for dynamic range

后端 未结 3 861
走了就别回头了
走了就别回头了 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条回答
  •  旧时难觅i
    2021-01-28 22:05

    I wouldn't use a number as a variable name. You can loop through the worksheets collection in two ways - the first is marginally more efficient I believe but doubt you'll notice the difference.

    As you say there is rarely any need to actually activate a sheet.

    Sub x()
    
    Dim ws As Worksheet, i As Long
    
    'option 1
    For Each ws In ActiveWorkbook.Worksheets
        ws.Activate
        ws.Range("A1") = 1 'no need to activate first
    Next ws
    
    'option 2
    For i = 1 To ActiveWorkbook.Worksheets.Count
        Worksheets(i).Activate
    Next i
    
    End Sub
    

提交回复
热议问题