There was a previous question on stackoverflow:
"Is it possible to start MAIL MERGE from excel macro (by clicking a button on sheet)
I have excel sheet with data and want to export it to new word doc."
This was answered Sep 29 '09 at 12:39 by dendarii 772.
We had this need too because we wanted to simplify life for volunteers with limited computer skills.
Unfortunately dendarii's code, modified with a suitable path, exits with run time error 4198 at the .OpenDataSource statement.
Cindy Meister writing on Microsoft Office for Developer's Form> ..>Word 2010 VBA suggested 4198 errors could be due to synchronicity problems. I gave it go with no success.
Andrew Poulson writing on Mr Excel encourages a contributor Snecz to compare his VBA mail merge .OpenDataSource statement against a Word macro recording. What do contributors think? My .OpenDataSource line seems standard. My Excel datasource file has a line of headers followed by two lines of data elements.
We have Office 2010.
I would be very grateful for any suggestions as to how to fix 4198 and if anyone knows of general diagnostic procedures. We are two people working for a charitable organisation. Any help welcome!
Sub RunMerge()
Dim wd As Object
Dim wdocSource As Object
Dim strWorkbookName As String
On Error Resume Next
Set wd = GetObject(, "Word.Application")
If wd Is Nothing Then
Set wd = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wdocSource = wd.Documents.Open("C:\Users\george\Desktop\VBA Project\Mergeletter.docx")
strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name
wdocSource.MailMerge.MainDocumentType = wdFormLetters
wdocSource.MailMerge.OpenDataSource _
Name:=strWorkbookName, _
AddToRecentFiles:=False, _
Revert:=False, _
Format:=wdOpenFormatAuto, _
Connection:="Data Source=" & strWorkbookName & ";Mode=Read", _
SQLStatement:="SELECT * FROM `Sheet1$`"
With wdocSource.MailMerge
.Destination=wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultFirstRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
wd.Visible = True
wdocSource.Close SaveChanges:=False
Set wdocSource = Nothing
Set wd = Nothing
End Sub