How to Create and Insert a MergeField into a Word Document when Developing a AddIn Using VSTO

2.8k Views Asked by At

Now I can insert a text after the current cursor,using

Globals.ThisAddIn.Application.Selection.Range.Text = itm.Value;

I want to replace the text with a MergeField,but I don't know how to create a MergeField object using VSTO and how to insert it into a document.

2

There are 2 best solutions below

0
On

This is how you insert merge field

object objType = Word.WdFieldType.wdFieldMergeField;
object objFieldName = fieldName;
Word.Field field = range.Fields.Add(range, ref objType, ref objFieldName, ref missing);

To replace the text you can either for String.Replace in C# or Find object from Word Object Model.

0
On

You could also just add in after the Word.Field field = ....

field.Result.Text = "Whatever you want";