In Word, find function is used to find a specified word or sentence from document with lots of contents quickly. In this post, I want to introduce a method about how to find text and highlight it with color by using C#/VB.NET.
Actually, find function is often used by us. We often find many labels at the end of the document to explain some words. If we want to know where the words are, we can use find function to get it. Also, we can use find function to get key words or notes and set colors or special effect to tell readers what they may need to pay attention.
In my example, I prepare a document and I will find word “Breathless” from it and add background color to highlight all “Breathless”.
*The .NET Word component, Spire.Doc is used for realizing this function.
Detailed Step Shown as Following:
- Load the document which I want to find specified word.
- Find word. Declare a TextSelection array which saves word I will find and assign value as document.FindAllString method. I need to send three parameters to this method, word I want to find, bool value for case sensitive, bool value for whole word applied.
- Highlight word. Because there are several same words in a document, I use foreach sentence to highlight all words with specified color in TextSelection array.
- Save and launch file.
static void Main(string args)
Document document = new Document();
document.LoadFromFile(@”D:\work\My Documents\Shayne Breathless.docx”, FileFormat.Docx);
TextSelection textSelections = document.FindAllString(“Breathless”, true, true);
foreach(TextSelection selection in textSelections)
selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.Cyan;
//Save and Launch
Friend Class Find
Shared Sub Main(ByVal args() As String)
Dim document As New Document()
document.LoadFromFile(“D:\work\My Documents\Shayne Breathless.docx”, FileFormat.Docx)
Dim textSelections() As TextSelection = document.FindAllString(“Breathless”, True, True)
For Each selection As TextSelection In textSelections
selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.Cyan
‘Save and Launch
Result Shown as Following: