问题
I would like to print specific worksheets from my Excel workbook to a single printout. There are additional sheets in my workbook that should not print.
The name of the first worksheet to be printed will be constant ("Recipe"). The names of the other worksheets to be printed will vary (they will all have the prefix "Pie" and different suffixes). The number of sheets to be printed will vary from project to project.
For example,
In project #1 the workbook will include the following worksheets: "Recipe", "Pie - Apple", "Pie - Pumpkin", "Ingredients", and "Tools".
In project #2 the workbook will include the following worksheets: "Recipe", "Pie - Custard", "Pie - Apple", "Pie - Key Lime", "Pie - Blueberry", "Ingredients", and "Tools".
I would like to print the "Recipe" worksheet and every worksheet that starts with "Pie" to a single printout. The following code allows me to unitize the desired worksheets while weeding out the rest:
Sub PrintArrayOfWorksheets()
Dim PrintCollection
PrintCollection = Array("Recipe", "Pie - Apple", "Pie - Pumpkin")
ThisWorkbook.Worksheets(PrintCollection).PrintOut
End Sub
This code works; however, it requires me to manually enter the elements of the array for each project. Please recommend a method of automatically updating the array to include the worksheets that meet the criteria above. Or, please recommend some other method entirely.
I've tried a couple different unsuccessful ideas, and I can share those if requested.
Kind regards,
Tony
回答1:
I have added a piece of code in yours that dynamically populates your array with the name of the sheets that fits the requirements.
Sub PrintArrayOfWorksheets()
Dim PrintCollection() As String
Dim WS As Worksheet
Dim i As Integer
ReDim PrintCollection(0 To 0)
i = 0
'Dynamically populates array
For Each WS In ActiveWorkbook.Worksheets
If LCase(WS.Name) = "recipe" Or LCase(Left(WS.Name, 3)) = "pie" Then
ReDim Preserve PrintCollection(0 To i)
PrintCollection(UBound(PrintCollection)) = WS.Name
i = i + 1
End If
Next
ThisWorkbook.Worksheets(PrintCollection).PrintOut
End Sub
回答2:
You mean like this?
Option Explicit
Sub Sample()
Dim ws As Worksheet
Dim MyAr
Dim sName As String
For Each ws In ThisWorkbook.Worksheets
If ws.Name = "Recipe" Or UCase(Left(ws.Name, 3)) = "PIE" Then
If sName = "" Then
sName = ws.Name
Else
sName = sName & "\" & ws.Name
End If
End If
If sName <> "" Then
MyAr = Split(sName, "\")
End If
Next ws
ThisWorkbook.Worksheets(MyAr).PrintOut
End Sub
来源:https://stackoverflow.com/questions/19962686/print-variable-array-of-specific-worksheets-to-a-single-printout