vba Excel 按名称打印工作表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/778170/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 09:44:42  来源:igfitidea点击:

Excel Print Worksheets by Name

excelvbaexcel-vbaprintingworksheet

提问by Caveatrob

I've got an Excel 2007 Spreadsheet and I'd like to write a VBA procedure to print particular worksheets by name. How do I do this?

我有一个 Excel 2007 电子表格,我想编写一个 VBA 程序来按名称打印特定的工作表。我该怎么做呢?

For example, I'd like to print "FirstSheet","ThirdSheet",and "FourthSheet"but not "SecondSheet".

例如,我想打印"FirstSheet","ThirdSheet","FourthSheet",但不"SecondSheet".

回答by Mauro Guzo

If you know the sheet name simply call the PrintOutfunction like this:

如果您知道工作表名称,只需PrintOut像这样调用函数:

Sheets("Name").PrintOut

For small amounts of sheets it is quite more easy by this way!

对于少量床单,通过这种方式更容易!

回答by Dan Donoghue

Don't need to loop to do this, one line of code will suffice:

不需要循环来做到这一点,一行代码就足够了:

Sheets(Array("FirstSheet", "ThirdSheet", "FourthSheet")).PrintOut Copies:=1

回答by Tomalak

Public Sub PrintByName(Names As Variant)

  Dim s As Worksheet
  Dim i As Integer

  If IsArray(Names) Then
    For Each s In ActiveWorkbook.Worksheets
      For i = 0 To UBound(Names)
        If StrComp(s.Name, Names(i), vbTextCompare) = 0 Then
          s.PrintOut
        End If
      Next i
    Next s
  End If

End Sub

Call like:

像这样调用:

PrintByName Array("FirstSheet", "ThirdSheet", "FourthSheet")

The nested loop is not optimal, in regards to runtime performance. With the limited number of sheets an Excel workbook can contain, I think this is negligible. However, using a Collectionto contain the desired sheet names instead of an Arraywould be better.

就运行时性能而言,嵌套循环不是最佳的。由于 Excel 工作簿可以包含的工作表数量有限,我认为这是可以忽略不计的。但是,使用 aCollection来包含所需的工作表名称而不是 anArray会更好。

回答by jgallant

Something similar to the following should work:

类似于以下内容应该可以工作:

Dim sh As Worksheet
For Each sh In ActiveWorkbook.Worksheets
        If (sh.Name = "Sheet1") Then
           sh.PrintOut
        End If
Next sh