如何通过Excel宏将带有选项“ .ExportAsFixedFormat”的Excel文件打印为PDF

时间:2018-11-14 03:53:14

标签: excel vba excel-vba pdf

我已经编写了一个代码,以使用页面设置参数将excel文件打印为.PDF文件,而且它也不需要提示对话框。

但是我需要知道是否需要使用以下代码,但目标路径不相同将.PDF文件命名为与excel文件名相同。例如:=如果excel文件名是“ 质量报告1411185623689 ”。此文件是由系统生成的,因此其名称每天都会更改。 我该如何解决?

 Sub Save_As_PDF()
With ActiveSheet.PageSetup
     .Orientation=xlLandscape
     .Zoom=16

End With
ActiveSheet.ExportAsFixedFormat _
 Type:=xlTypePDF, _
 FileName:="C\:Desktop\Reports\Same as excel file name", _
 Quality:=xlQualityStandard, _
 IncludeDocProperties:=False, _
 IgnorePrintAreas:=False, _
 OpenAfterPublish:=True

Exit Sub

1 个答案:

答案 0 :(得分:1)

未经测试,但是假设您要将PDF命名为与Excel文件相同(忽略文件扩展名),但是位于不同的文件夹中(例如,某个名为"C\:Desktop\Reports\"的文件夹/目录):

Option explicit

Sub SaveAsPDF()

Dim folderPath as string
folderPath = "C\:Desktop\Reports\" ' Change to whatever folder, but make sure it ends with a \

If len(dir$(folderPath, vbDirectory)) = 0 then
Msgbox("'" & folderPath & "' is not a valid/existing directory. Abandoning export. Code will stop running now.")
Exit sub
End if

Dim Filename as string
Filename = left$(Thisworkbook.name, instrrev(Thisworkbook.name, ".", -1, vbbinarycompare) -1) & ".pdf"

With ActiveSheet.PageSetup
     .Orientation=xlLandscape
     .Zoom=16
End With
ActiveSheet.ExportAsFixedFormat _
 Type:=xlTypePDF, _
 FileName:=folderPath & filename, _
 Quality:=xlQualityStandard, _
 IncludeDocProperties:=False, _
 IgnorePrintAreas:=False, _
 OpenAfterPublish:=True

Exit Sub