在Excel VBA中选择工作表范围

在Excel VBA中选择工作表范围

问题描述:

我正在尝试在Excel宏中选择一系列工作表,以便随后进行打印.

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

我要打印一个范围,即Sheet2-Sheetx,其中x是变量.

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.

在此示例中,我选择了三张纸,所以x = 3:

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.

谢谢.

.Name是您需要获取的属性 工作表的名称如下:

.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

如果想花大价钱,以N作为变量,请尝试如下操作:

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