保存单独的Excel表单,以便通过VBA代码分离PDF文件

我试图保存一些单独的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 

你正在build立一个数组或者工作表,但是在之后没有对它们做任何事情。 在下面,该数组只是工作表的名称,由With … End With语句使用以提供父级工作表引用。

 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 

您不需要任何一个Select语句。 此外,假设您已经select了工作表数组,您不应该迭代完整的Worksheets集合。

同样使用.Text属性,假定Range("ReportDate")包含一个Datetypes,它实际上是一个Long Integer。 .Text属性将返回单元格中显示的内容,而不是基础的整数date值。

 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