I have copied a macro (credits: MailMerge Excel to Word individual files) into Excel where I can mail-merge data from Excel into Word Letter automatically and save the individual files as a pdf in the folder.
Unfortunately my PDFs do not contain any content of the Excel list after using the macro, but stick to the mail merge field name. This applies to all my created files.
Additionally, I would like to use the first line as controller, so I can decide which line is merged (e.g. with an "x" in the first line).
Can someone help me in both cases? Especially my first problem feels like a small mistake, but after hours of searching I gave up.. :-(
Thank you for your help.
Sub RunMailMerge()
Dim wdOutputName, wdInputName, PDFFileName As String
Dim x As Integer
Dim nRows As Integer
wdInputName = ThisWorkbook.Path & "\Letter.docx"
Const wdFormLetters = 0, wdOpenFormatAuto = 0
Const wdSendToNewDocument = 0, wdDefaultFirstRecord = 1, wdDefaultLastRecord = 3
'This will get you the number of records "-1" accounts for header
nRows = Sheets("Overview").Range("B" & Rows.Count).End(xlUp).Row - 1
' open the mail merge layout file
Dim wdDoc As Object
Set wdDoc = GetObject(wdInputName, "Word.document")
wdDoc.Application.Visible = False
With wdDoc.MailMerge
.MainDocumentType = wdFormLetters
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
For x = 1 To nRows
With wdDoc.MailMerge.DataSource
.ActiveRecord = x
If .ActiveRecord > .LastRecord Then Exit For
End With
' show and save output file
'cells(x+1,2)references the first cells starting in row 2 and increasing by 1 row with each loop
PDFFileName = ThisWorkbook.Path & "\Letter - " & Sheets("Overview").Cells(x + 1, 2) & ".pdf"
wdDoc.Application.Visible = False
wdDoc.ExportAsFixedFormat PDFFileName, 17 ' This line saves a .pdf-version of the mail merge
Next x
' cleanup
wdDoc.Close SaveChanges:=False
Set wdDoc = Nothing
MsgBox "Your pdf('s) has now been saved!"
End Sub
Execute
method), but then you go back to working with the merge document "template". And that still has the merge fields in it. There are various ways to break up a mail merge result document, the one I use is described at homepage.swissonline.ch/cindymeister/MergFram.htm under "Save each merged letter as a separate file". If that works for you I can put it in an answer, here... – Cindy Meister