Our forums are currently in maintenance mode and the ability to post is disabled. We will be back up and running as soon as possible. Thanks for your patience!



Word 2003 mailmerge VBA automation

By techrepublic ·
I have a web-based application that needs to generate a mailmerge in Word on the client machine. This is working fine for letters.

However we would also like to generate the mailmerge as emails; but although the merge works, Word pops up an error message "Word cannot merge documents that can be distributed by mail or fax without a valid mail address". Word is open at that point, and if I open the Mailmerge wizard, I find the email Subject line, and the field to use for the email address, is NOT populated although I have set these in code.

How this works:
1. My webpage opens a .hta document in a new window
2. The hta document has a script that runs that creates an instance of Word and automates it, setting the mailmerge datasource AND the email subject and address field, then executes the merge.

As above, this works fine for letters. What's very odd is that if I take the VBA code out of the .hta document, and make it into a .VBS script, or paste it into an app such as Excel's VBA editor, it works perfectly and the emails get sent. Only when running as an HTA does the script fail to set the email address field. Full script follows:

{script language="vbscript"}
dim wd
dim doc
dim fname
fname="[path and filename of merge document]"
on error resume next
set wd=CreateObject("Word.Application")
if err.number then
msgbox err.Description,,"Couldn't open Word"
Set doc = wd.Documents.Open(fname)
If Err.Number Then
MsgBox Err.Description, , "Couldn't open Document"
doc.MailMerge.OpenDataSource "[datasourcename].odc", , , , , , , , , , , , , , , 0
If Err.Number Then
MsgBox Err.Description, , "Couldn't open merge data"
doc.MailMerge.MailSubject="This is a test subject"
doc.MailMerge.MailFormat = 1 'HTML
doc.Mailmerge.MailAddressFieldName = "Contact_Work_Email"
doc.MailMerge.MainDocumentType = 4 '' wdEmail
doc.MailMerge.Destination = 2 'wdSendToEmail
doc.MailMerge.Execute true
If Err.Number Then
MsgBox Err.Description, , "Couldn't execute merge"
doc.Close False
End If
End If
End If
End if

This conversation is currently closed to new comments.

Thread display: Collapse - | Expand +

All Answers

Collapse -

[Problem solved - doh!]

by techrepublic In reply to Word 2003 mailmerge VBA a ...

OK, fixed it myself. Because I was taking the document filename as a parameter to the .hta URL, I was using the same URL over and over during testing, and IE was cacheing it and using an old version (that wasn't setting the MailAddressFieldName.

Changing the URL to ensure a fresh copy was downloaded from the server fixed my problem! :-)

Collapse -

That is nice to know.. :)

Please post back if you have any more problems or questions.

Related Discussions

Related Forums