问题
I'm trying to mail merge from Excel to individual pdf files using VBA.
Here is a small example:
The word document "Testdoc.docx" only contains the mergefield << Name >>
Here is the VBA-code:
Sub Test()
Dim wdOutputName, wdInputName, PDFFileName As String
Dim x As Long
Dim nRows As Long
wdInputName = ThisWorkbook.Path & "\Testdoc.docx"
Const wdFormLetters = 0, wdOpenFormatAuto = 0
Const wdSendToNewDocument = 0, wdDefaultFirstRecord = 1, wdDefaultLastRecord = 3
nRows = Sheets(1).Range("A" & Rows.Count).End(xlUp).Row - 1
Dim wdDoc As Object
Set wdDoc = GetObject(wdInputName, "Word.document")
wdDoc.Application.Visible = False
For x = 1 To nRows
With wdDoc.MailMerge
.MainDocumentType = wdFormLetters
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
PDFFileName = ThisWorkbook.Path & "\Letter " & Sheets(1).Cells(x + 1, 1) & ".pdf"
wdDoc.Application.Visible = False
wdDoc.ExportAsFixedFormat PDFFileName, 17
Next x
wdDoc.Close SaveChanges:=False
Set wdDoc = Nothing
MsgBox "Succes"
End Sub
The problem:
It makes 3 individual pdf files and name them correctly, respectively: "Letter name1.pdf", "Letter name2.pdf" and "Letter name3.pdf".
However, it doesn't not merge the mergefields correctly. All documents still contain the mergefield. Whereas <<Name>>
should be replaced by respectively "name1", "name2" and "name3", but that's not the case.
Any ideas how to get it to work?
来源:https://stackoverflow.com/questions/64809611/merge-to-pdf-files-from-excel-vba-doesnt-export-cells-correctly