Using a code I found on here posted by user dandarii, I can mailmerge a word.doc. When that mail merge is done I'd like to mailmerge a separate word.doc with the same record. I do not want to have to merge the two word.docs to one word.doc
Was thinking about Creating a separate module but got confused. Was thinking of maybing a wdDoc and a wdDoc1?
With wdApp
.Visible = False
Set wdDoc = .Documents.Open(filePath & firstDoc)
'Added Code
strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name
wdDoc.MailMerge.MainDocumentType = wdFormLetters
wdDoc.MailMerge.OpenDataSource _
Name:=strWorkbookName, _
AddToRecentFiles:=False, _
Revert:=False, _
Format:=wdOpenFormatAuto, _
Connection:="Data Source=" & strWorkbookName & ";Mode=Read", _
SQLStatement:="SELECT * FROM [Sheet1$]"
With wdDoc.MailMerge
.Destination = wdSendToNewDocument
With .DataSource
.FirstRecord = loopRow - 1
.LastRecord = loopRow - 1
.ActiveRecord = loopRow - 1
End With
.Execute Pause:=False
End With
wdApp.Visible = False
Set TargetDoc = wdApp.ActiveDocument
TargetDoc.SaveAs2 Filename:=newFilePath & "\" & newFolderName & "- firstDoc.docx"
wdDoc.Close SaveChanges:=False```
If I'm following the requirement correctly, I think it would make sense to break this up into two procedures: one to handle the loop (not visible in the code in the question), the other to handle mail merge. Something like the code snippets below.
"Top-level" procedure that handles the loop and everything Excel (code extract, based on content in question):
With wdApp
.Visible = False
Set wdDoc = .Documents.Open(filePath & firstDoc)
Set wdDoc1 = .Documents.Open(filePath & otherDoc)
'Added Code
strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name
ExecuteMailMerge wdDoc, strWorkbookName, loopRow, _
newFilePath, newFolderName, firstDoc
ExecuteMailMerge wdDoc1, strWorkbookName, loopRow, _
newFilePath, newFolderName, otherDoc
Procedure to handle mail merge:
Sub ExecuteMailMerge(wdDoc As Object, strWorkbookName as String, loopRow as Long, _
newFilePath as String, newFolderName as String, docName as String)
With wdDoc.MailMerge
.MainDocumentType = wdFormLetters
.OpenDataSource _
Name:=strWorkbookName, _
AddToRecentFiles:=False, _
Revert:=False, _
Format:=wdOpenFormatAuto, _
Connection:="Data Source=" & strWorkbookName & ";Mode=Read", _
SQLStatement:="SELECT * FROM [Sheet1$]"
.Destination = wdSendToNewDocument
With .DataSource
.FirstRecord = loopRow - 1
.LastRecord = loopRow - 1
.ActiveRecord = loopRow - 1
End With
.Execute Pause:=False
End With
Set TargetDoc = wdApp.ActiveDocument
TargetDoc.SaveAs2 Filename:=newFilePath & "\" & newFolderName & "- " & docName & ".docx"
wdDoc.Close SaveChanges:=False
End Sub