Select range of sheets in Excel VBA

谁都会走 提交于 2020-04-14 09:10:16

问题


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, i.e. 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.


回答1:


.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



回答2:


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.



来源:https://stackoverflow.com/questions/48639776/select-range-of-sheets-in-excel-vba

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!