I'll paste my code below. I have the code saved in a module, and I'm calling the function from a command button on a form.
The error I'm currently getting is a Microsoft Office Word error: "The Microsoft Office Access database engine cannot find the input table or query 'ailmerge_Source_Safeguardin'. Make sure it exists and that its name is spelled correctly."
The query definitely exists, and I know I've spelled it correctly as I copied and pasted the name into the code. Why when it executes is it omitting the first and last characters of the query name?
Any help much appreciated. Thank you.
Expand|Select|Wrap|Line Numbers
- Function MergeIt()
- On Error GoTo ErrHandling
- Dim objDoc As Word.Document
- Dim objWord As Word.Application
- Dim blnCreated As Boolean
- Dim strFilename As String
- Dim strQueryName As String
- Dim strDBpath As String
- strFilename = "C:\Users\Laura\Documents\Safeguarding_Certificate.docx"
- strQueryName = "Mailmerge_Source_Safeguarding"
- strDBpath = "C:\Users\Laura\Documents\Absences.accdb" 'Or probably just CurrentDb.Name
- On Error Resume Next
- Set objWord = GetObject(, "Word.Application")
- If Err Then
- Set objWord = CreateObject("Word.Application")
- blnCreated = True
- End If
- On Error GoTo ErrHandling
- Set objDoc = objWord.Documents.Open(strFilename)
- 'Make Word Visible
- objWord.Visible = True
- 'Execute the MailMerge
- With objDoc.MailMerge
- 'Set Merge Data Source
- objDoc.MailMerge.OpenDataSource Name:=strDBpath, _
- LinktoSource:=True, _
- Connection:="QUERY " & strQueryName, _
- SQLStatement:="SELECT * FROM " & strQueryName
- .Destination = wdSendToNewDocument
- .Execute
- objWord.ActiveDocument.PrintOut False
- objWord.ActiveDocument.Close wdDoNotSaveChanges
- End With
- 'Close The form files and the merged document
- objDoc.Close wdDoNotSaveChanges
- If blnCreated Then
- objWord.Quit
- End If
- Set objDoc = Nothing
- Set objWord = Nothing
- Exit Function
- ErrHandling:
- MsgBox "Whoops" 'Better error handling of course
- End Function