Mail Merge from a Form

TourOperator

Registered User.
Local time
Today, 00:46
Joined
Sep 11, 2014
Messages
14
I have been trying to create VBA code to mail merge to a Word document from a Form. There are plenty of examples out there but nothing that I can make work. My closest attempt is the following code, but I get “Run time error ‘424’ – Object required” at the ‘MailMerge.OpenDataSource’ line. Does anyone have VBA that achieves this?

Code:
 Private Sub TestButton_Click()

Dim pathMergeTemplate As String
Dim sql As String
Dim sqlWhere As String
Dim sqlOrderBy As String

' create folder path

    pathMergeTemplate = "F:\Destinations\Merge Documents\"

'Base query

    sql = "SELECT [Lead Name] FROM [Green Book]"
    
    With Forms("Red-Book")

'Filter and order records using the current form

    sqlWhere = "WHERE (([Green Book].[Reference Number]) =" & Me![Reference Number] & ")"
    sqlOrderBy = ""

    End With

' Build the sql string

    sql = sql & sqlWhere & sqlOrderBy & ";"

‘ Show me the sql string in Debug window

    Debug.Print sql

'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

'Maybe supposed to be new code block

‘Open Word

    Dim appWord As Object
    Dim docWord As Object

    Set appWord = CreateObject("Word.Application")

        appWord.Application.Visible = True

'Open the Word document

        Set docWord = appWord.Documents.Add(Template:=pathMergeTemplate & "Test.docx")

'Mail Merge

            docWord.MailMerge.OpenDataSource Name:=pathMergeTemplate & "qryMailMerge.txt"

        Set docWord = Nothing

    Set appWord = Nothing

End Sub

I have opened a similar thread, but I feel that I am now moving into a different area. I thank Gina Whipp for advising me on the best way to approach this.
 

Users who are viewing this thread

Back
Top Bottom