user15355871
user15355871

Reputation:

Counting number of times some words appear in a word document and exporting it to excel

I'm looking to count the number of times a few words have been mentioned in a word document and export it to excel. I have figured out how to export word counts and the file names they correspond to (here is my earlier post), but I'm unsure how to apply that to this ask. Again, any help is greatly appreciated!!

Public Sub CountOccurrences()

Dim iCount As Long
Dim strSearch As String

strSearch = InputBox$("[M] [P]")
iCount = 0

With ActiveDocument.Content.Find
    .Text = strSearch
    .Format = False
    .Wrap = wdFindStop
    Do While .Execute
        iCount = iCount + 1
    Loop
End With

MsgBox Chr$(34) & strSearch & Chr$(34) & " was found " & _
        iCount & " times."

End Sub

Upvotes: 1

Views: 99

Answers (1)

macropod
macropod

Reputation: 13490

For example:

Sub CountOccurrences(wordDoc As Object, r As Long)
Dim c As Long, i As Long
Const Wordlist As String = "Apple,Banana,Cherry"
With wordDoc
  Range("A1").Offset(r, 1).Value = .Name
  For c = 0 To UBound(Split(Wordlist, ","))
    i = 0
    With .Range.Find
      .Text = Split(Wordlist, ",")(c)
      .MatchWholeWord = True
      .Wrap = 0 'wdFindStop
      Do While .Execute
        i = i + 1
      Loop
    End With
    Range("A1").Offset(r, c + 2).Value = i
  Next
End With
End Sub

which you'd call via:

Call CountOccurrences(wordDoc, i)

in your existing code.

Upvotes: 3

Related Questions