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

问题描述 投票:-1回答:1

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

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

任何有关这方面的帮助将不胜感激!

vba ms-word mailmerge
1个回答
-2
投票

[编辑]更正了对象参考。添加了SaveAs2

在OP中,尝试使用伪打印机保存为pdf。 SaveAs pdf格式与各种pdf伪打印机之间存在差异。是否有理由打印到PDF并保存该文件,而不是执行另存为并选择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
© www.soinside.com 2019 - 2024. All rights reserved.