I'm trying to use VB to automate MS Mail Merge to create purchase orders. I'm using a Word template (.dot) for the form and a comma delimited file for the datasource. The code below works fine if there is only one record in the file + the header record (defining the fields). If there is more than 1 data record, I get the the following error: 'Run-time error "5535"; Word could not finish merging these documents or inserting this database'. The error is on the execute command. If I perform the merge through Word, it works fine with multiple data records - allowing me to page through the resulting purchase orders. Any thoughts?
Code follows:
CODE
Option Explicit
Dim WithEvents oApp As Word.Application
Private Sub Form_Load()
'Start Word.
Set oApp = CreateObject("Word.Application")
End Sub
Private Sub cmdConnAny_Click()
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim wrdMerge As Word.MailMerge
On Error GoTo errorhandler
' create an instance of microsoft word.
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = False
' now create a new document based on the template
Set wrdDoc = wrdApp.Documents.Add("C:\MMS\PURCHASE ORDER TEST.dot")
With wrdDoc.MailMerge
.MainDocumentType = wdFormLetters
.OpenDataSource _
Name:="C:\temp\B9724.txt"
End With
' now get the mailmerge object
Set wrdMerge = wrdDoc.MailMerge
' do the mailmerge
With wrdMerge
.Destination = wdSendToNewDocument
.Execute False
End With
' close the orginal file
wrdDoc.Close wdDoNotSaveChanges
' save the newly created file
wrdApp.ActiveDocument.SaveAs "C:\MMS\PURCHASE ORDERS VBMERGE.doc"
wrdApp.Quit False
Set wrdApp = Nothing
Set wrdMerge = Nothing
Set wrdDoc = Nothing
Set oApp = Nothing
Unload Me
errorhandler:
MsgBox "Problem occurred with MailMerge. Program ending."
Set oApp = Nothing
Set wrdMerge = Nothing
Set wrdDoc = Nothing
Set wrdApp = Nothing
Unload Me
End Sub