How to find highlighted text from Word file in C# ? RRS feed

  • Question

  • I found example in VBA but I need to convert into C#so any help ?

    Sub TestFind()
      Dim myRange As Range
      Set myRange = ActiveDocument.Content    '    search entire document
      With myRange.Find
        .Highlight = True
        Do While .Execute = True     '   loop while highlighted text is found
          Debug.Print myRange.Text   '   myRange is changed to contain the found text
      End With
    End Sub

    Monday, March 20, 2017 5:36 PM


All replies

  • Try to use or

    void TestFind() 
            Word.Range myRange myRange = ActiveDocument.Content;
            Word.Find find = myRange.Find;
            while (find.Execute()) 
                //    myRange is changed to contain the found text

    profile for Eugene Astafiev at Stack Overflow, Q&A for professional and enthusiast programmers

    • Marked as answer by wel123 Monday, March 20, 2017 9:54 PM
    Monday, March 20, 2017 8:05 PM
  • Much appreciated Eugene
    Monday, March 20, 2017 9:54 PM
  • Just an alternative solution to find and highlight text in Word file using C#.

    using System.Drawing;
    using Spire.Doc;
    using Spire.Doc.Documents;
    namespace FindAndHighlight
        class Program
            static void Main(string[] args)
                //create a document object
                Document document = new Document();
                //load an existing file           
                //find text
                TextSelection[] text = document.FindAllString("forming", false, true);
                foreach (TextSelection seletion in text)
                    //hightlight text with preferable color          
                    seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
                //save to file
                document.SaveToFile("FindHighlight.docx", FileFormat.Docx);

    Tuesday, June 27, 2017 6:39 AM