Changing a Word Mail Merge Field in C#

The mail merge fields in Microsoft Word are actually just a specific type of the more general Fields. Fields can be used to make fill-in forms, autogenerated text, dates, etc… They typically are displayed surrounded by funny looking square brackets, like <<first_name>>.

Inside the Word Xml, the Field and the display value are stored separately – the field looks like “ MERGEFIELD User_Title “, then in a separate range, the display of “«User_Title»” is stored.

Using the Word Object Model, Document.MailMerge.Fields contains MailMergeField objects for each instance of a merge field. The .Code member contains the range object, of which the .Text member will contain the field code (aka “ MERGEFIELD User_Title “). If you do a replace on this text field, it will update the merge field, but the display will remain the same.

You next have to call Document.Fields.Update() to get the display matching.

Here is some code:

        private void RenameMergeField(Word.Document doc, string oldName, string newName)
        {
            foreach (Word.MailMergeField field in doc.MailMerge.Fields)
            {
                if (field.Code.Text.Contains(oldName))
                {
                    field.Code.Text = field.Code.Text.Replace(oldName, newName);
                }
            }
            doc.Fields.Update();
        }

Leave a Reply

Your email address will not be published. Required fields are marked *