c# word interop find and replace everything

Tom van den Berk picture Tom van den Berk · Oct 8, 2013 · Viewed 42.1k times · Source

I have some code to replace text inside a word 2010 docx.

        object fileName = Path.Combine(System.Windows.Forms.Application.StartupPath, "document.docx");

        Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application { Visible = true };

        Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(ref fileName, ReadOnly: false, Visible: true);

        aDoc.Activate();

        Microsoft.Office.Interop.Word.Find fnd = wordApp.ActiveWindow.Selection.Find;

        fnd.ClearFormatting();
        fnd.Replacement.ClearFormatting();
        fnd.Forward = true;

        fnd.Wrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue;

        fnd.Text = "{id}";
        fnd.Replacement.Text = "123456";
        fnd.Execute(Replace: WdReplace.wdReplaceAll);

This works without formatting. But when {id} is formatted it does not replace the text.

How can I make this code ignore formatting?

Answer

joecop picture joecop · Oct 10, 2013

I use this function to find and replace. you can specify any of the options.

private void FindAndReplace(Microsoft.Office.Interop.Word.Application doc, object findText, object replaceWithText)
{
    //options
    object matchCase = false;
    object matchWholeWord = true;
    object matchWildCards = false;
    object matchSoundsLike = false;
    object matchAllWordForms = false;
    object forward = true;
    object format = false;
    object matchKashida = false;
    object matchDiacritics = false;
    object matchAlefHamza = false;
    object matchControl = false;
    object read_only = false;
    object visible = true;
    object replace = 2;
    object wrap = 1;
    //execute find and replace
    doc.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord,
        ref matchWildCards, ref matchSoundsLike, ref matchAllWordForms, ref forward, ref wrap, ref format, ref replaceWithText, ref replace,
        ref matchKashida ,ref matchDiacritics, ref matchAlefHamza, ref matchControl);                
}

And usage would be :

object fileName = Path.Combine(System.Windows.Forms.Application.StartupPath, "document.docx");
Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application { Visible = true };
Microsoft.Office.Interop.Word.Document aDoc = wordApp.Documents.Open(fileName, ReadOnly: false, Visible: true);
aDoc.Activate();
FindAndReplace(wordApp, "{id}", "12345");

And you can use the FindAndReplace function over and over....
Hope this helps.