0

How can I get the count of occurrences of a particular word in a Word document using Microsoft.Office.Interop.Word?

For example, in my Word document I have two ##<Test Sub Clause1>## tags in different places. I need a total count of its occurrence in a particular document. In my example, it will be 2.

Is there is any predefined function that exists in Microsoft.Office.Interop.Word to get this count? Or what is the easiest way to accomplish this?

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
Nithin Paul
  • 2,169
  • 3
  • 33
  • 55

2 Answers2

5

Here's something you can try, modified from a code snippet I found at dotnetperls.

using System;
using Microsoft.Office.Interop.Word;

class Program
{
    static void Main()
    {
        var wordToFind = "some_word_to_find";
        var wordCounter = 0;

        // Open a doc file.
        var application = new Application();
        var document = application.Documents.Open("C:\\word.doc");

        // Loop through all words in the document.
        for (var i = 1; i <= document.Words.Count; i++)
            if (document.Words[i].Text.TrimEnd() == wordToFind)
                wordCounter++;

        Console.WriteLine("Matches Found: {0}", wordCounter);

        // Close word.
        application.Quit();
    }
}

There's also some documentation on MSDN you might want to check out.

Grant Winney
  • 65,241
  • 13
  • 115
  • 165
1

If you want to count the occurrence of word ##< Test Sub Clause1>##. Then you should try this...

//AddLibrary
using Word = Microsoft.Office.Interop.Word;

And try this Code.

object oMissing = System.Type.Missing;
object outputFile = "C:\\WordCountTest.doc";
Word.Application wordApp = new Word.Application();
Microsoft.Office.Interop.Word.Document doc = wordApp.Documents.Open(ref outputFile, ref oMissing,
             ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
             ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing,
             ref oMissing, ref oMissing, ref oMissing, ref oMissing);
        doc.Activate();
int wordCount = 0;
for (int k = 1; k <= doc.Words.Count; k++)
{
     if (doc.Words[k].Text.TrimEnd() == "Test" && doc.Words[k + 1].Text.TrimEnd() == "Sub" && doc.Words[k + 2].Text.TrimEnd() == "Clause1")
         wordCount++;
}