Office Word使用VBA拆分邮件合并文件

将当前邮件合并文件拆分为单独的word和pdf,文件名称以数据源中的“姓名”字段重命名。

Sub MailMergeToPdfBasic()
Dim masterDoc As Document
Dim singleDoc As Document
Dim lastRecordNum As Long
Dim saveDir As String
Dim saveName As String

' 保存路径
saveDir = "C:\Users\JIAHE\Desktop\Output\"

Set masterDoc = ActiveDocument
masterDoc.MailMerge.DataSource.ActiveRecord = wdLastRecord
lastRecordNum = masterDoc.MailMerge.DataSource.ActiveRecord
masterDoc.MailMerge.DataSource.ActiveRecord = wdFirstRecord
Do While lastRecordNum > 0
masterDoc.MailMerge.Destination = wdSendToNewDocument
masterDoc.MailMerge.DataSource.FirstRecord = masterDoc.MailMerge.DataSource.ActiveRecord
masterDoc.MailMerge.DataSource.LastRecord = masterDoc.MailMerge.DataSource.ActiveRecord
masterDoc.MailMerge.Execute False
' 文件名称
saveName = masterDoc.MailMerge.DataSource.DataFields("姓名")
Set singleDoc = ActiveDocument
singleDoc.SaveAs2 _
FileName:=saveDir & saveName & ".docx", _
FileFormat:=wdFormatXMLDocument
singleDoc.ExportAsFixedFormat _
OutputFileName:=saveDir & saveName & ".pdf", _
ExportFormat:=wdExportFormatPDF
singleDoc.Close False
If masterDoc.MailMerge.DataSource.ActiveRecord >= lastRecordNum Then
lastRecordNum = 0
Else
masterDoc.MailMerge.DataSource.ActiveRecord = wdNextRecord
End If
Loop
End Sub

参考