Question

I have a List of Merge Field names passed into my application, along with a Word Document. The Merge Fields include periods and underscores, in the form "Here.Is.An.Example.Merge_Field". These separators are required - the characters may be able to be changed, but they cannot be removed altogether.

Several of these Merge Fields are contained within a datasource that is created for the document. The datasource has no data save for the merge field names - the merge itself takes place elsewhere in the process.

I attach the document to the datasource as below:

WordApplication.MailMerge.OpenDataSource(DataFilePath);

This loads the Merge Fields into the menu as desired, but all the periods have gone. I now have "HereIsAnExampleMerge_Field", which causes issues at other points in my application.

How can I prevent Word from removing these characters?

Was it helpful?

Solution

I don't think you can, because AFAIK the merge field names are modified to be valid bookmark names, which have certain restrictions

(See, e.g. What are the limitations for bookmark names in Microsoft Word? for a discussion, except in this case I think Word will insert an "M" before an initial "_". Plus, names over 40 characters long are mangled to produce unique names.)

So what to do really depends on what issues you are facing.

You can retrieve the fieldnames that Word actually uses (i.e. its mangled names) from either ActiveDocument.MailMerge.DataSource.DataFields or .FieldNames. AFAIK these are in the same sequence as the fields in the data source, even though Word sometimes rearranges fields for display in the Edit Recipients dialog (e.g., it sorts field names that it considers to be address field names in a certain sequence). So that should allow you to match its field names with the originals.

Alternatively, if your code needs to insert { MERGEFIELD } fields in a Mail Merge Main Document and knows the sequence of the fields in the data source, you can use field numbers (1 for the first field retrieved by Word etc.), e.g. { MERGEFIELD 1 }. But beware, as I have never seen that facility documented anywhere by Microsoft.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top