65.9K
CodeProject is changing. Read more.
Home

Search and highlight text in MS Word through C#

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.78/5 (8 votes)

Jul 3, 2011

CPOL
viewsIcon

37515

Code to search and highlight text in MS Word.

You can use the following code to open a Word document and highlight the searched for text(s):

private void btnFind_Click(object sender, EventArgs e)
{
    object fileName = "xxxxx"; //The filepath goes here
    string textToFind = "xxxxx"; //The text to find goes here
    Word.Application word = new Word.Application();
    Word.Document doc = new Word.Document();
    object missing = System.Type.Missing;
    try
    {
        doc = word.Documents.Open(ref fileName, ref missing, ref missing, 
        ref missing, ref missing, ref missing, ref missing, ref missing, 
        ref missing, ref missing, ref missing, ref missing, ref missing, 
        ref missing, ref missing, ref missing);
        doc.Activate();
        foreach (Word.Range docRange in doc.Words)
        {
            if(docRange.Text.Trim().Equals(textToFind,
               StringComparison.CurrentCultureIgnoreCase))
            {
                docRange.HighlightColorIndex = 
                  Microsoft.Office.Interop.Word.WdColorIndex.wdDarkYellow;
                docRange.Font.ColorIndex = 
                  Microsoft.Office.Interop.Word.WdColorIndex.wdWhite;
            }
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show("Error : " + ex.Message);
    }
}

You have to add a reference to Microsoft.Office.Interop.Word using the following statement:

using Word = Microsoft.Office.Interop.Word;