在VB中选择多个工作表

时间:2016-11-02 12:03:47

标签: excel vba excel-vba printing

我想选择多张纸来打印书中的所有纸张,除了一张之外,到目前为止,我的代码看起来像这样,通过宏记录:

Sub Print_All()
  '
  ' Print_All Macro

    Sheets(Array("Class List", "Blank1", "Blank2", "Blank3", "Blank4", "Blank5", "Blank6" _
        , "Blank7", "Blank8", "Blank9", "Blank10", "Blank11", "Blank12", "Blank13", "Blank14", _
        "Blank15", "Blank16", "Blank17", "Blank18", "Blank19", "Blank20", "Blank21", "Blank22" _
        , "Blank23", "Blank24")).Select
    Sheets("Blank2").Activate
    Sheets(Array("Blank25", "Blank26", "Blank27", "Blank28", "Blank29", "Blank30")). _
        Select Replace:=False
    Sheets(Array("Blank1", "Blank2", "Blank3", "Blank4", "Blank5", "Blank6", "Blank7", _
        "Blank8", "Blank9", "Blank10", "Blank11", "Blank12", "Blank13", "Blank14", "Blank15", _
        "Blank16", "Blank17", "Blank18", "Blank19", "Blank20", "Blank21", "Blank22", "Blank23" _
        , "Blank24", "Blank25")).Select
    Sheets("Blank2").Activate
    Sheets(Array("Blank26", "Blank27", "Blank28", "Blank29", "Blank30")).Select _
        Replace:=False
    Range("F5:N10").Select
    Selection.PrintOut Copies:=1, Collate:=True
End Sub

它工作正常但如果我想更改工作表的名称会出现问题。它在寻找空白时返回错误。 有没有办法选择工作表而不在代码中命名它们?

1 个答案:

答案 0 :(得分:1)

您始终可以不是通过名称来引用工作表,而是通过它们的个别来引用工作表,例如:新创建的工作簿中的Sheet1具有索引1,Sheet2 - 索引2,依此类推。

语法如下:yourWorkbook.Sheets(index as integer)

例如:

dim wbk as Workbook
set wbk = ActiveWorkbook

dim i as integer
wbk.Sheets(i).Select

编辑: 哦,请注意,有时会在工作簿中或在工作簿之外删除或移动工作表。给定工作表的权限不一定与他们在工作簿中的顺序相关。要检查您需要的纸张的缺陷,您可以尝试失败或使用循环如下

dim n as integer
for n = 1 to wbk.Sheets.count
    debug.print "index " & i, wbk.Sheets(i).name
next n