进行邮件合并(VBA)时,如何自动保存为PDF



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

1)它打开一个"保存pdf文件为"窗口

2)我必须手动输入名称

3)代码运行

我想自动化步骤1和2,以便代码在没有我的任何手动输入的情况下运行,并将其保存为任何路径中的white.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

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

[编辑]校正对象引用。添加了saveas2

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

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

有时需要以下内容来保持脚本保存的静音提示。对于上述测试方法,没有提示,因此可能不需要。

在saveas之前切换 .DisplayAlerts

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

最新更新