Hey there. I'm trying to automate a process to load up a Word template and populate it with data from from my Access 2010 database. The process is iniated by clicking a button on one of my Access forms.
I have managed to get it working using some code I picked up online (see below) but the problem is that it opens 2 instances of Word; one containing the data in the mailmerge fields and another that is just a blank copy of the template.
Basically I want to stop the blank copy opening up.
I'm pretty sure it's the appWord.Application.Visible = True line that is causing the extra copy to open up but if I dont include that line the user never sees the Word instance.
Can anyone help?
I have managed to get it working using some code I picked up online (see below) but the problem is that it opens 2 instances of Word; one containing the data in the mailmerge fields and another that is just a blank copy of the template.
Basically I want to stop the blank copy opening up.
I'm pretty sure it's the appWord.Application.Visible = True line that is causing the extra copy to open up but if I dont include that line the user never sees the Word instance.
Can anyone help?
Code:
Dim pathMergeTemplate As String
Dim sql As String
Dim sqlWhere As String
Dim sqlOrderBy As String
'Get the word template from the Letters folder
pathMergeTemplate = "ApplicationFolderPath\LetterTemplates\"
'This is a sort of "base" query that holds all the mailmerge fields
sql = "SELECT * FROM ltr_BaseSUdata"
'Create a temporary QueryDef to hold the query
Dim qd As DAO.QueryDef
Set qd = New DAO.QueryDef
qd.sql = sql
qd.Name = "mmexport"
CurrentDb.QueryDefs.Append qd
' Export the data using TransferText
DoCmd.TransferText acExportDelim, , "mmexport", pathMergeTemplate & "qryMailMerge.txt", True
' Clear up
CurrentDb.QueryDefs.Delete "mmexport"
qd.Close
Set qd = Nothing
Dim appWord As Object
Dim docWord As Object
Set appWord = CreateObject("Word.Application")
' Open the template in the Resources\Letters folder:
Set docWord = appWord.Documents.Add(Template:=pathMergeTemplate & "FreeText.doc")
'Now I can mail merge without involving currentproject of my Access app
docWord.MailMerge.OpenDataSource Name:=pathMergeTemplate & "qryMailMerge.txt", LinkToSource:=False
docWord.MailMerge.Execute Pause:=False
appWord.Application.Visible = True
Set docWord = Nothing
Set appWord = Nothing