在第十三楼的例子中,由于WORD中的书签的定义与引用消耗大量WORD内存,导致代码运行速度相当慢。为了进一步优化,先是想到了数组,但在WORD中使用数组后存在一个MATCH的问题,则需要调用EXCEL,还得使用两处错误陷阱,测试了一下,不理想,就否定了。然后,就有了以下的代码,与网友们分享之: '* +++++++++++++++++++++++++++++
'* Created By 守柔(ShouRou)@ExcelHome 2005-1-26 5:38:36
'仅测试于System: Windows NT Word: 10.0 Language: 2052
'^The Code CopyIn [ThisDocument-ThisDocument]^'
'* ----------------------------- Sub WordsCountTwo()
Dim i As Range, aVar As Variable, aString As String, MyString As String
'友情提示
MsgBox "受文档字数和可用内存以及WORD自身限制,您的操作可能会需要一段时间," & vbCrLf & _
"也许会出现可用内存不足的情况,您可能需要重启WORD以便接着下一次的工作!", vbOKOnly + vbExclamation, "Warnning"
For Each i In Me.Words '词中循环
If i.Characters.Count > 1 Then '按照中文习惯为二个以上为词组
'判断是否为中文字符
If Asc(i.Characters(1)) < -2050 And Asc(i.Characters(1)) > -20319 Then
If MyString = "" Then GoTo GN '循环初始阶段跳至GX行标签
If InStr(MyString, i.Text & ",") = 0 Then
GN: aString = i.Text & "," '加入","分隔符以便精确定位
MyString = MyString & aString
Else
On Error Resume Next '忽略错误
Me.Variables.Add Name:=i.Text '添加文档变量
If Err.Number <> 0 Then '设置错误陷阱
Err.Clear '清除错误
'将次数累加写入
Me.Variables(i.Text).Value = Me.Variables(i.Text).Value + 1
Else
'首次写入文档变量时,其初始值为2
Me.Variables(i.Text).Value = 2
End If
End If
End If
End If
Next
aString = "": MyString = "" '重新初始化变量
Application.ScreenUpdating = False '关闭屏幕更新
With Selection
.EndKey unit:=wdStory '移到文档末尾
'作一个区分标记
.InsertAfter vbCrLf & "------------------------------------词数频次统计列表------------------------------------" & vbCrLf
.EndKey unit:=wdStory '移到文档末尾
For Each aVar In Me.Variables '在文档变量中循环
'插入文档中
aString = """" & aVar.Name & """出现频次:" & vbTab & aVar.Value & vbCrLf
MyString = MyString & aString '文本累加写入内存变量中,以加速运行
Next
.InsertAfter MyString
'根据出现频次排序
.Sort FieldNumber:="域 1", SortFieldType:= _
wdSortFieldNumeric, SortOrder:=wdSortOrderDescending
End With
VarClear '清空文档变量
Me.UndoClear '清空撤消
Application.ScreenUpdating = True '恢复屏幕更新
End Sub
'----------------------
Sub VarClear()
Dim V As Variable
For Each V In Me.Variables
V.Delete '删除文档变量
Next
End Sub
'---------------------- 实测运行速度较之十三楼的至少快一倍,且无需反复清空撤消,代码更简洁明了。 |