您的位置:首页 > 编程语言 > VB

VBA获取WORD文档中各英文单词出现的次数,并输出

2019-02-15 23:22 561 查看
Sub 统计各单词出现的次数()
Dim a As String, Dic As Object
Dim myReg As Object, Matches As Object, Match As Object
Dim k, i As Long, j As Long, temp As String, c As String

a = ActiveDocument.Content.Text
Set Dic = CreateObject("Scripting.Dictionary")
Dic.CompareMode = vbTextCompare
Set myReg = CreateObject("VBScript.RegExp")
With myReg
.Pattern = "[A-Za-z]+"  '匹配模式:由纯字母组成的字符串
.Global = True
Set Matches = .Execute(a)
For Each Match In Matches  '统计频次
With Match
If Dic.Exists(.Value) Then Dic(.Value) = Dic(.Value) + 1 Else Dic.Add .Value, 1
End With
Next
k = Dic.Keys  '获取各“单词”
For i = 0 To UBound(k) - 1 '排序
For j = i + 1 To UBound(k)
If k(i) > k(j) Then
temp = k(i)
k(i) = k(j)
k(j) = temp
End If
Next
Next
For i = 0 To UBound(k)  '合并以用于输出
c = c & k(i) & vbTab & Dic(k(i)) & Chr(13)
Next
Documents.Add.Content.Text = "共有如下" & Dic.Count & "个英文单词(含频次):" & Chr(13) & c
End With
End Sub
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐