首页 > 解决方案 > 如何在进行邮件合并 (VBA) 时自动另存为 PDF

问题描述

当我尝试运行以下代码时,会发生以下情况:

1) 它会打开一个“将 PDF 文件另存为”窗口

2) 我必须手动输入名称

3)代码运行

我想自动化第 1 步和第 2 步,以便代码在没有我手动输入的情况下运行,并将其保存为whatever.pdf 在任何路径中。

我尝试使用 ExportAsFixedFormat,但问题是它只将第一页保存为 pdf,而其余 100 多条正在通过邮件合并的记录没有被保存。最重要的是,它仍会从步骤 1 中打开该对话框窗口。

ActiveDocument.ExportAsFixedFormat OutputFilename:=whatever.pdf, _
                                   ExportFormat:=wdExportFormatPDF, etc. 

编码:

Sub DoMailMerge()

Set myMerge = ActiveDocument.MailMerge
If myMerge.State = wdMainAndSourceAndHeader Or _
 myMerge.State = wdMainAndDataSource Then
 With myMerge.DataSource
 .FirstRecord = 1
 .LastRecord = 3
 End With
End If
With myMerge
 .Destination = wdSendToPrinter
 .Execute
End With

End Sub

对此的任何帮助将不胜感激!

标签: vbams-wordmailmerge

解决方案


[编辑] 更正了对象引用。添加了 SaveAs2

在 OP 中,尝试使用伪打印机另存为 pdf。SaveAs pdf 格式与各种 pdf 伪打印机之间存在差异。是否有理由打印到 PDF 并保存该文件,而不是执行另存为并选择 PDF 格式?

With myMerge
    .Destination = wdSendToNewDocument
    .Execute
End With
ActiveDocument.SaveAs2 "path & filename", wdFormatPDF  

有时需要以下内容来使脚本保存的提示静音。上面测试的方法,没有提示,所以可能不需要。

.DisplayAlerts在 SaveAs 之前关闭

Application.DisplayAlerts = wdAlertsNone
ActiveDocument.SaveAs2 "path & filename", wdFormatPDF
Application.DisplayAlerts = wdAlertsAll

或者

Dim tempDisplayAlerts As Long
tempDisplayAlerts = Application.DisplayAlerts  
Application.DisplayAlerts = wdAlertsNone
ActiveDocument.SaveAs2 "path & filename", wdFormatPDF    
Application.DisplayAlerts = tempDisplayAlerts

推荐阅读