【问题标题】:How to print excel file to pdf with the option ".ExportAsFixedFormat" via excel macro如何通过 excel 宏使用“.ExportAsFixedFormat”选项将 excel 文件打印为 pdf
【发布时间】:2018-11-14 03:53:13
【问题描述】:

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

但我需要知道是否需要使用以下代码将 .PDF 文件命名为与 excel 文件名相同但目标路径不同。例如:= if 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

【问题讨论】:

  • 您可以随意命名 PDF。你想给 PDF 起什么名字?会不会每次都不一样?它是生成名称的派生词吗?
  • 这是重复的。看到这个SO question
  • @alowflyingpig ,我非常感谢回答我卡住的问题。是的,我的系统生成的 excel 文件名每天都会变化,例如“质量报告 141256522356”,就像它的名称中包含一些数字。所以当系统生成这个文件时,这些数字每天都会变化。我需要打印与excel文件同名的pdf。

标签: excel vba pdf


【解决方案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

【讨论】:

  • 对不起,我的回答中有一个额外的.,导致语法无效。如果需要,请重试。
  • 在您的代码中,这部分以红色显示给我,并说 Syntax Error Filename = left$(Thisworkbook.name, instrrev(Thisworkbook.name, ".", -1, vbbinarycompare) -1) . & ".pdf" 我该如何解决这个问题?
  • & 之前去掉. - 或者只是将代码复制粘贴到我的答案中(我已经修复了它)然后再试一次。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-06-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-09-20
  • 1970-01-01
相关资源
最近更新 更多