Click here to Skip to main content
Click here to Skip to main content

Search and highlight text in MS Word through C#

By , 4 Jul 2011
Rate this:
Please Sign up or sign in to vote.

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;

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

DARSHAN MODANI
Software Developer Texas Learning and Computation Center
United States United States
Darshan is an enthusiastic and passionate Software Developer. He has achieved a Master's Degree in Computer Science from University of Houston, TX. He currently works as a Research Assistant at Texas Learning and Computation Center. He owns this blog and loves sharing interesting thoughts about programming.
 
Visit my personal Blog, www.darshansblog.com

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web03 | 2.8.140415.2 | Last Updated 4 Jul 2011
Article Copyright 2011 by DARSHAN MODANI
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid