vba - 如何在进行邮件合并 (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
对此的任何帮助将不胜感激!
解决方案
[编辑] 更正了对象引用。添加了 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
推荐阅读
- shell - 设置视图时如何添加要执行的命令?
- typescript - 如何处理带有可选泛型参数的函数重载?
- java - 使用 JAVA 将字符串拆分为多个部分并存储到 CSV
- angular - 如何每1小时在页面中刷新数据,而当标签接收到焦点时
- php - 在 PHP Autoload 中添加快捷方式会导致 Laravel 发生冲突
- php - Symfony3中生成实体时出错如何解决
- c - 如何通知工作线程有一些工作要完成?
- java - 如何将 javafx 中 TextArea 的 isUndoable 属性设置为 true?
- python - Pygame 窗口打不开
- snowflake-cloud-data-platform - 雪花用户/角色管理