View Single Post
 
Old 12-01-2021, 08:15 PM
user4829 user4829 is offline Windows 10 Office 2019
Novice
 
Join Date: Dec 2021
Posts: 6
user4829 is on a distinguished road
Default Automate mail merge to save each record individually using VBA

Hi,

I am trying to automate mail merge to save each record individually using VBA. I know there are a lot of guides and tutorials out there, I have tried a few and had no luck. The best success I've had so far is the code below, pulled from
HTML Code:
https://swissmacuser.ch/microsoft-word-mail-merge-into-single-documents/
.

This currently works to export a document from mail merge and save as individual file, it just appears to save the same document over the top of each other. E.g. I will end up with only one merged document at the end as the others were saved over during the process. I can see in preview mode when I run the macro, the file saving over itself and updating content.


Here is my code:

Sub SaveIndividualWordFiles()
Dim iRec As Integer
Dim docMail As Document
Dim docLetters As Document
Dim savePath As String

Set docMail = ActiveDocument
''There is a problem with the recordcount property returning -1
''http://msdn.microsoft.com/en-us/library/office/ff838901.aspx

savePath = ActiveDocument.Path & ""

ActiveDocument.MailMerge.DataSource.lastRecord = wdLastRecord
iRec = ActiveDocument.MailMerge.DataSource.ActiveRecord
ActiveDocument.MailMerge.DataSource.FirstRecord = wdFirstRecord

For i = 1 To iRec
With ActiveDocument.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = i
.lastRecord = i
'' This will be the file name
'' the test data source had unique surnames
'' in a field (column) called FileName
sFName = .DataFields("Title").Value
End With
.Execute Pause:=False
Set docLetters = ActiveDocument
End With

' Save generated document and close it after saving
docLetters.SaveAs FileName:=savePath & sFName & ".docx"
docLetters.Close False

docMail.MailMerge.DataSource.ActiveRecord = wdNextRecord
Next
End Sub

Reply With Quote