我的 Excel 工作簿中有一个导出按钮,可以选择要导出为合并 PDF 的工作表。我最初对工作表进行了硬编码。例如:
Sheets(Array("Volume Report","Notes","Invoice01")).Select
并且有效。我试图通过从命名范围动态构建列表来喜欢它,当我将它们添加到工作簿时,该范围会填充新工作表。
我能够构建字符串,它返回的字符串值如果手动替换可以工作,但是当作为变量传递时我得到
Runtime Error '9': Subscript out of Range
我不确定为什么手动传递字符串有效但动态分配它却不行。对于完成预期任务的任何帮助,我们表示赞赏。
VBA代码:
Sub ExportAsPDF()
Dim wb As Workbook
Dim currentSheet As Worksheet
Dim filePath As String
Dim sheetNames As String
Dim cell As Range
Set wb = ActiveWorkbook
Set currentSheet = ActiveSheet
' Build the file path
filePath = wb.Path & "\" & "0_" & Range("Notes_Revision").Value & ") " & Range("Notes_JobName").Value & " - VR - " & Range("Notes_Author").Value & ".pdf"
' Manually build a string of sheet names from Ref_PrintRange
For Each cell In Range("Ref_PrintRange")
If sheetNames = "" Then
sheetNames = cell.Value
Else
sheetNames = sheetNames & Chr(34) & ", " & Chr(34) & cell.Value
End If
Next cell
' Select the specified sheets for export
Sheets(Array(sheetNames)).Select
' Export the selected sheets as PDF
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=filePath, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, IgnorePrintAreas:=False, _
OpenAfterPublish:=False
' Reselect the original sheet
currentSheet.Select
End Sub
提前谢谢您。
无需构建数组:
...
Dim first As Boolean
...
first = True
For Each cell In Range("Ref_PrintRange")
WorkSheets(cell.Value).Select First
first = False 'next Select's add to the current sheet selection
Next cell
https://learn.microsoft.com/en-us/office/vba/api/excel.worksheet.select