Public Function WordMerge(strQuery As String, _
strDataDoc As String, _
strMergeFile As String, _
Optional blnSuppressBlankLines As Boolean = True)
' Merges data from query into Word document
' Accepts: Name of Access query providing data for merge - String.
' Path to Word data file created from query - String.
' Path to Word document to be used for merge - String.
' Optional setting to suppress or show blank lines
' if data missing ( Default = True ) - Boolean
Dim dbs As DAO.Database, rst As DAO.Recordset
Dim qdf As DAO.QueryDef
Dim prm As DAO.Parameter
Dim wApp As Object
Dim wDoc As Object
Dim wActiveDoc As Word.Document
Set dbs = CurrentDb
Set qdf = dbs.QueryDefs(strQuery)
For Each prm In qdf.Parameters
prm = Eval(prm.Name)
Next prm
Set rst = qdf.OpenRecordset
' exit function if recordset is empty
If rst.EOF Then
MsgBox "No data to merge.", vbInformation, "Mail Merge"
GoTo Exit_Here
End If
Set wApp = GetWordApp()
' close datasource document if open in Word
For Each wDoc In wApp.Documents
If wDoc.Path & "\" & wDoc.Name = strDataDoc Then
wDoc.Close wdDoNotSaveChanges
End If
Next wDoc
' delete current Word data file.
' ignore error if file doesn't exist
On Error Resume Next
Kill strDataDoc
On Error GoTo 0
' create new Word data file
ExportToText strQuery, strDataDoc, ",", True
'open word merge document
Set wDoc = wApp.Documents.Open(strMergeFile)
' execute merge
With wDoc.MailMerge
.OpenDataSource strDataDoc
.SuppressBlankLines = blnSuppressBlankLines
.Destination = wdSendToNewDocument
.Execute
End With
Set wActiveDoc = wApp.ActiveDocument
' show document in maximized window
ShowWord wApp, wDoc, wActiveDoc
Exit_Here:
Set rst = Nothing
Set dbs = Nothing
End Function