none
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
    
        Loop
    
      End With
    
    End Sub


    Monday, March 20, 2017 5:36 PM

Answers

All replies

  • Try to use http://converter.telerik.com/ or http://codeconverter.sharpdevelop.net/SnippetConverter.aspx:

    void TestFind() 
    {
            Word.Range myRange myRange = ActiveDocument.Content;
            Word.Find find = myRange.Find;
            while (find.Execute()) 
            {            
                Debug.Print(myRange.Text);
                //    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           
                document.LoadFromFile(@"E:\Work\Documents\WordDocuments\References.docx");
    
                //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