Click here to Skip to main content
12,823,312 members (46,581 online)
Click here to Skip to main content
Add your own
alternative version


9 bookmarked
Posted 3 Jul 2011

Search and highlight text in MS Word through C#

, 4 Jul 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
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;
        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);
        foreach (Word.Range docRange in doc.Words)
                docRange.HighlightColorIndex = 
                docRange.Font.ColorIndex = 
    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;


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


About the Author

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,

You may also be interested in...

Comments and Discussions

PraiseNice article Pin
er.vks18-Oct-16 22:11
memberer.vks18-Oct-16 22:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170308.1 | Last Updated 4 Jul 2011
Article Copyright 2011 by DARSHAN MODANI
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid