WORD VBA计数单词出现次数 [英] WORD VBA Count Word Occurrences

查看:540
本文介绍了WORD VBA计数单词出现次数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我下面的代码已经在工作.但是我需要进一步简化代码.我下面的代码对文档中出现的单词进行计数.代码如下:

i have a code below that is already working. However i need to simplify the code even further. The code i have below counts the word occurrences in a document. The code is as follows:

Option Base 1

Sub arrangepara()
Dim r As Range

Set r = activedocument.Range
If (r.Characters.Last.text = vbCr) Then r.End = r.End - 1
sortpara r
End Sub

Function sortpara(r As Range)
Dim sWrd As String
Dim Found As Boolean
Dim N As Integer, i As Integer, j As Integer, k As Integer, WordNum As Integer
N = r.Words.count
ReDim Freq(N) As Integer
ReDim Words(N) As String
Dim temp As String

i = 1
WordNum = 0
Do While r.Find.Execute(findtext:="<*>", MatchWildcards:=True, Wrap:=wdFindStop) = True
   If i = N Then Exit Do
        Found = False
        For j = 1 To WordNum
               If Words(j) = r.text Then
                   Freq(j) = Freq(j) + 1
                   Found = True
                   Exit For
               End If
        Next j
        If Not Found Then
            WordNum = WordNum + 1
            Words(WordNum) = r.text
            Freq(WordNum) = 1
        End If
   i = i + 1
Loop

Set r = activedocument.Range
r.Collapse wdCollapseEnd
r.InsertParagraphBefore
r.Collapse wdCollapseEnd

r.InsertAfter "Occurrence List:"
r.Collapse wdCollapseEnd
r.InsertParagraphBefore
r.Collapse wdCollapseEnd


For j = 1 To WordNum
    r.InsertAfter Words(j) & " (" & Freq(j) & ")" & vbCr
Next j

r.Select
Selection.sort SortFieldType:=wdSortFieldAlphanumeric, SortOrder:=wdSortOrderAscending
r.Font.Color = wdColorAqua

End Function

我只需要简单地讲这部分,我不知道怎么做.有没有好的撒玛利亚人可以简化我的代码?非常感谢!以下是我需要简化的内容:

I need to simply this part and i dont know how. Are there any good samaritans out there that can simplify the codes for me? Thanks much! Below is what i need to simplify:

Do While r.Find.Execute(findtext:="<*>", MatchWildcards:=True, Wrap:=wdFindStop) = True
   If i = N Then Exit Do
        Found = False
        For j = 1 To WordNum
               If Words(j) = r.text Then
                   Freq(j) = Freq(j) + 1
                   Found = True
                   Exit For
               End If
        Next j
        If Not Found Then
            WordNum = WordNum + 1
            Words(WordNum) = r.text
            Freq(WordNum) = 1
        End If
   i = i + 1
Loop

推荐答案

我将假设简化"表示提高性能",因为我怀疑这会太慢.

I'm going to assume that by "simplify" you mean "improve performance", as I suspect this is going to be horrendously slow.

我会避免使用查找"来获得所有单词.代替:

I would avoid getting all the words by using Find. Instead of:

Do While r.Find.Execute(findtext:="<*>", MatchWildcards:=True, Wrap:=wdFindStop) = True
   ...
Loop

我认为您应该使用:

Dim w as Word
For each w In ActiveDocument.Words
   ...
Next

这篇关于WORD VBA计数单词出现次数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆