0

I'm trying and trying and i just can't afford last thing to end my application.

I have some phrases stored as strings, for example "Something is just". And at now my program will highlight all "Something is just", but also all "Something", all "is" and all "just" in the Word .docx text.

I don't know how make it possible, because now I'm using my document divided by words. I don't know if I should use other foreach type or maybe there is just a method of Range that could help me solve this problem.

Here is my code:

for (int i = 0; i < keyList.Count; i++)
{
    foreach (Range range in doc.Words)
    {
        if (keyList[i].Contains(range.Text.Trim()))
        {
            range.HighlightColorIndex = Microsoft.Office.Interop.Word.WdColorIndex.wdDarkYellow;
        }       
    }
}

A keyList has three-word string. Thanks for any help!

Starynowy
  • 3
  • 2
  • http://stackoverflow.com/a/41364583/3060520 – huse.ckr Apr 17 '17 at 11:36
  • Possible duplicate of [How do I write bold text to a Word document programmatically without bolding the entire document?](http://stackoverflow.com/questions/11564073/how-do-i-write-bold-text-to-a-word-document-programmatically-without-bolding-the) – krillgar Apr 17 '17 at 11:39
  • That doesn't solve my problem :( – Starynowy Apr 17 '17 at 12:55

1 Answers1

0

This solution is based on using Word's Range.Find object to find the position of the phrase in the document text and setting the HighlightColorIndex property of the any found items.

public static void WordHighliter(Word.Document doc, IEnumerable<string> phrases, Word.WdColorIndex color)
            {
            Word.Range rng = doc.Content;
            foreach (string phrase in phrases)
                {
                rng = doc.Content;
                Word.Find find = rng.Find;

                find.ClearFormatting();
                find.Text = phrase;
                find.Forward = true;
                find.Wrap = Word.WdFindWrap.wdFindStop;
                find.Format = false;
                find.MatchCase = false;
                find.MatchWholeWord = true;
                find.MatchWildcards = false;
                find.MatchSoundsLike = false;
                find.MatchAllWordForms = false;
                find.MatchByte = true;

                while (find.Execute())
                    {
                    Int32 start = rng.Start;
                    // ensure that phrase does not start within another word
                    if (rng.Start == rng.Words[1].Start)
                        {
                        rng.HighlightColorIndex = Word.WdColorIndex.wdYellow;
                        }
                    }
                }

            }
TnTinMn
  • 11,522
  • 3
  • 18
  • 39