0
votes

I use following function to find and replace text:

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, "A", "B");

private void FindAndReplace(Microsoft.Office.Interop.Word.Application doc, object findText, object replaceWithText)
    {
        try
        {
            //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);
        }
        catch (Exception e)
        {
            throw e;
        }
    }

It works fine, but I wonder if there is any way to replace text "A" with "B" formated in other style? I mean ex: replace "A" FontColor="Black" with "B" FontColor="Red".
In other words I wonder if it is possible to change the color of the text "A" or replace it with "B" colored with another color.

1

1 Answers

0
votes

Yes, you can use Word's Find/Replace to change formatting, as well as text. The best way to get exactly the syntax you need is to record the actions in a Word macro then take the properties you need into your C# code.

Ctrl+H will bring up the Find/Replace dialog box. Click the "More" button to expose the advanced options. With the cursor in the "Replace" box, click the Format button to access formatting commands, the font color will be in the "Font" entry (dialog box).

When you look at the recorded VBA code look for the Find.Replacement section where the properties for "replace" will be listed.

In your C# code, declare an object for Find and instantiate it. For example: Word.Find wdFind = Selection.Find;

Use this with the properties: wdFind.Replacement.Font.Color

And execute the find on the object: wdFind.Execute(....