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

时间:2019-03-07 15:39:41

标签: vba ms-word mailmerge

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

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

2)我必须手动输入名称

3)代码运行

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

对此将提供任何帮助!

1 个答案:

答案 0 :(得分:-2)

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

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

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

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

在另存为前切换.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