Detecting Wrong MergeFields while automating MailMerge

C

Christof Nordiek

Hi all,

another question over MailMerge automation:
Does someone know how programmatically detect, if there are MaiMerge-Fields
in a Maindocument wich don't appear in the DataSource?
When i start the MailMerge, and there are such fields in the document a
dialog is opened (but it's not visible, it's only reachable by Alt-Tab-Key)
where the user has to exchange the name of the field.
if then the user presses Cancel the MailMerge goes on anyway, and ugly
errorMessages appear in the merged document, (very bad, if you are printing
direct to the printer).

What i want, is a way to detect the errors in my app and react on it by
myself. At least the user should be able to stop the merging

Any ideas?

Thanks
 
P

Peter Jamieson

The following code will detect /most/ of the mergefields in a document - it
may not see some of the fields in the graphics layer.

Sub IterateMergeFields()
Dim r As Range
Dim f As Field
Dim s As Shape
For Each r In ActiveDocument.StoryRanges
If r.StoryType <> wdTextFrameStory Then
For Each f In r.Fields
If f.Type = wdFieldMergeField Then
' do whatever you need
End If
Next
End If
Next
For Each s In ActiveDocument.Shapes
If s.Type = msoTextBox Then
For Each f In s.TextFrame.TextRange.Fields
If f.Type = wdFieldMergeField Then
' do whatever you need
End If
Next
End If
Next
End Sub

If you take the name of the merge field and use it as the index to the

ActiveDocument.MailMerge.DataSource.DataFields()

collection, an error should be raised if the field is not in the collection
(I haven't checked to ensure it is trappale - if not, you would have to
iterate through the collction and try to match each fieldname in the data
source).

However, as a further complication, Word may alter the data source field
names when it inserts them as MERGEFIELD fields, if
a. they contain certain characters
b. they are over a certain length (over around 31 characters I think)

I don't have a list of the relevant rules or code that deals with them. I
suspect merge documents where renaming occurs are relatively rare.

Peter Jamieson
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top