简体   繁体   中英

Select range of sheets in Excel VBA

I'm trying to select a range of worksheets in an Excel macro, so that they can then be printed.

I want to print a range, ie Sheet2-Sheetx, where x is a variable.

I have tried recording a macro to do what I want, but it uses sheet names rather than sheet references, and of course doesn't support variables.

In this example, I selected three sheets, so x=3:

Sheets(Array("Data", "Data (2)", "Data (3)")).Select
ActiveWindow.SelectedSheets.PrintOut preview:=True

I would have thought this would be simple, but can't seem to figure it out.

Thanks in advance.

.Name is the property that you need to get the Worksheet's names like this:

WorkSheets(Array(Worksheets(1).Name, Worksheets(2).Name, Worksheets(3).Name)).Select

And if you want to do it fancy, with N as a variable, try like this:

Public Sub SelectN()

    Dim N           As Long: N = 2
    Dim cnt         As Long
    Dim arrOfWs     As Variant

    ReDim arrOfWs(N - 1)
    For cnt = 1 To N
        arrOfWs(cnt - 1) = Worksheets(cnt).Name
    Next cnt
    Worksheets(arrOfWs).Select

End Sub

Your code seems to work for me, I would however make it shorter:

Sheets(Array("Data", "Data (2)", "Data (3)")).Printout Preview: = -1

Check sheets' names spelling.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM