We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

MergeField with Words


I have several hundreds of word documents in which I have to replace some words by the corresponding mergefield.
Doing it by hand will take me too much time as you guess.

Is there a way to replace a word with a mergefield ?


Hi<?xml:namespace prefix = o ns = "urn:schemas-microsoft-com:office:office" />

Thank you for your interest in Aspose.Words. Yes of course you can replace text with mergefield using Aspose.Words. I think you should use ReplaceEvaluator to achieve this. Please see the following link for more information.


Also see the following code example:

public void Test003()


//Open document

Document doc = new Document(@"Test003\in.doc");

//Replace word with mergefield using ReplaceEvaluator

Regex regex = new Regex("word");

doc.Range.Replace(regex, new ReplaceEvaluator(ReplaceInsertMergeField), false);

//Save output document



private ReplaceAction ReplaceInsertMergeField(object sender, ReplaceEvaluatorArgs e)


//Get MatchNode

Run run1 = (Run)e.MatchNode;

//Create Run

Run run2 = (Run)run1.Clone(true);

//Get index of match value

int index = run1.Text.IndexOf(e.Match.Value);

//split run that contains matched text

run2.Text = run1.Text.Substring(index + e.Match.Value.Length);

run1.Text = run1.Text.Substring(0, index);

run1.ParentParagraph.InsertAfter(run2, run1);

//Create document builder

DocumentBuilder builder = new DocumentBuilder(e.MatchNode.Document);

//Move to run2


//Insert mergefield

builder.InsertField(@"MERGEFIELD myField \* MERGEFORMAT", "«myField»");

return ReplaceAction.Skip;


Hope this helps.

Best regards.

Many many thanks, you save my life :-)