我正在尝试将一些单独的Excel工作表保存为单独的PDF文件,并根据一些固定单元格和每个工作表的名称重命名每个文件,代码如下,但结果不符合我的预期,请你帮忙如果我的代码有问题,请查看我?
Option Explicit
Sub SheetsToPDFs()
Dim wks As Worksheet
ActiveWorkbook.Sheets(Array("Overall", "AGRM", "AICI", "AMUI", "ARMT")).Select
For Each wks In Worksheets
wks.Select
wks.ExportAsFixedFormat Type:=xlTypePDF, _
FileName:=Range("SavePath").Value & "\" & wks.Name & "_CYProductionReport_" & Range("ReportDate").Value, _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
Next wks
End Sub
答案 0 :(得分:2)
您正在设置一个数组或工作表,但之后并没有真正对它们做任何事情。在下文中,数组只是工作表的名称,With ... End With statement用于提供父工作表引用。
Sub SheetsToPDFs()
Dim w As Long, aSHTs As Variant
aSHTs = Array("Overall", "AGRM", "AICI", "AMUI", "ARMT")
For w = LBound(aSHTs) To UBound(aSHTs)
With Worksheets(aSHTs(w))
'the filename should NOT have a .PDF file extension!
Debug.Print Range("SavePath").Value & "\" & .Name & "_CYProductionReport_" & Range("ReportDate").Text
.ExportAsFixedFormat Type:=xlTypePDF, Quality:=xlQualityStandard, IncludeDocProperties:=True, _
Filename:=Range("SavePath").Value & "\" & .Name & "_CYProductionReport_" & Range("ReportDate").Text, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
End With
Next w
End Sub
答案 1 :(得分:1)
您不需要任何Select
语句。此外,假设您已选择了工作表数组,则不应迭代完整的Worksheets
集合。
同样使用.Text
属性,假设Range("ReportDate")
包含Date
类型,实际上是一个Long Integer。 .Text
属性将返回单元格中显示的内容,而不是基础整数日期值。
Option Explicit
Sub SheetsToPDFs()
Dim wks As Worksheet
Dim printSheets as Variant 'Array of worksheets
Dim rptDate as String
'Assign to the array
Set printSheets = ActiveWorkbook.Sheets(Array("Overall", "AGRM", "AICI", "AMUI", "ARMT"))
'Format the report date:
rptDate = Format(Range("ReportDate").Value, "YYYY-MM-DD") 'Modify as needed
'Iterating over the printSheets array:
For Each wks In printSheets
wks.ExportAsFixedFormat Type:=xlTypePDF, _
FileName:=Range("SavePath").Value & "\" & wks.Name & _
"_CYProductionReport_" & rptDate, _
Quality:=xlQualityStandard, _
IncludeDocProperties:=True, _
IgnorePrintAreas:=False, _
OpenAfterPublish:=False
Next
End Sub