dboddington
Instructor
I have written some code to automate a mail merge which merges an query with a Word MM document. But I want to save each of the letters separately with a descriptive file name. This is the code I have written (thanks to a user here for part of it!). The problems I am trying to solve are (1) I always get an error (462) the first time it is run, the second time seems to be OK, (2) I want to close the final instance of Word down - how can I get a pointer to the instance of Word (3) Can I initially check if Word is running before the MM is done so as to prompt the user to close it? (4) If anyone can think of any way the code can be improved - would be much appreciated...
Thanks again!
Code:
Private Sub cmdMerge_Click()
Dim intNumRec As Integer
Dim strName As String
Dim rst As ADODB.Recordset
Dim objWord As Word.Document
'Need a reference to Microsoft Word 9.0 Object Library
Dim strSQL As String
Set rst = New ADODB.Recordset
rst.ActiveConnection = CurrentProject.Connection
rst.CursorType = adOpenStatic
rst.Open "SELECT Client from qryAddressInfo"
intNumRec = rst.RecordCount
On Error GoTo ErrorHandler
For I = 1 To intNumRec
strSQL = "Select * from [qryAddressInfo] _
Where [Client] = '" & rst![Client] & "'"
Set objWord = GetObject _
("C:\MMDoc.doc","Word.Document")
'Make Word visible.
objWord.Application.Visible = True
'Set the mail merge data source
objWord.MailMerge.OpenDataSource _
Name:="C:\My Documents\Merging\MergeDB.mdb", _
LinkToSource:=True, _
Connection:="QUERY qryAddressInfo", _
SQLStatement:=strSQL
'Execute the mail merge.
objWord.MailMerge.Destination = wdSendToNewDocument
objWord.MailMerge.Execute
objWord.Close wdDoNotSaveChanges
ActiveDocument.SaveAs "C:\"& I & rst![Client]
ActiveDocument.Close
rst.MoveNext
Next
Exit Sub
ErrorHandler:
If Err.Number = 462 Then
MsgBox "Error encountered - Try Again"
ActiveDocument.Close
Else
MsgBox "Error" & Err.Number & " " & Err.Description
End If
End Sub
Thanks again!