Here's the code
Code
Sub MailMerge()
Dim wd As Object
Dim wdocSource As Object
Dim wdInputName As String
Dim strWorkbookName As String
' Prompt user to select the Word file to use for the mail merge
wdInputName = Application.GetOpenFilename("Word Documents (*.docx),*.docx", , "Select Word File for Mail Merge")
If wdInputName <> "" Then
On Error Resume Next
Set wd = GetObject(wdInputName, "Word.Application")
If wd Is Nothing Then
Set wd = CreateObject("Word.Application")
End If
On Error GoTo 0
Set wdocSource = wd.Documents.Open(wdInputName)
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 `Database$`"
With wdocSource.MailMerge
.Destination = wdSendToNewDocument
.SuppressBlankLines = True
With .DataSource
.FirstRecord = wdDefaultLastRecord
.LastRecord = wdDefaultLastRecord
End With
.Execute Pause:=False
End With
wd.Visible = True
wd.Quit
wdocSource.Close SaveChanges:=False
Set wdocSource = Nothing
Set wd = Nothing
Else
' User cancelled file selection, do nothing
Exit Sub
End If
End Sub
Display More