WORD VBA算词Word出现

时间:2011-04-13 07:21:54

标签: vba ms-word word-vba

我有一个已经正常工作的代码。但是我需要进一步简化代码。我在下面的代码计算文档中出现的单词。代码如下:

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

我只需要这部分,我不知道如何。有没有好的撒玛利亚人可以为我简化代码?非常感谢!以下是我需要简化的内容:

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

1 个答案:

答案 0 :(得分:0)

我将假设“简化”意味着“提高性能”,因为我怀疑这会非常缓慢。

我会避免使用Find获取所有单词。而不是:

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

我认为你应该使用:

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