计算某些单词出现在word文档中的次数并将其导出到excel

问题描述

我想计算word文档中提到几个单词的次数并将其导出到excel。 我已经想出了如何导出字数和它们对应的文件名(here is my earlier post),但我不确定如何将其应用于此问题。 再次,非常感谢任何帮助!

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

解决方法

例如:

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

您会通过以下方式调用:

Call CountOccurrences(wordDoc,i)

在您现有的代码中。