Word VBA:遍历字符的速度非常慢

Jus*_* L. 2 vba ms-word

我有一个宏,可以将数字前面的单引号更改为撇号(或关闭单大引号)。通常,当您在Word中键入“the '80s”之类的内容时,“8”前面的撇号朝向错误。下面的宏可以工作,但是速度非常慢(比如每页 10 秒)。在常规语言(甚至解释型语言)中,这将是一个快速的过程。您知道为什么在 Word 2007 上使用 VBA 需要这么长时间吗?或者,如果有人拥有一些查找+替换技能,无需迭代即可完成此操作,请告诉我。

Sub FixNumericalReverseQuotes()
    Dim char As Range
    Debug.Print "starting " + CStr(Now)
    With Selection
        total = .Characters.Count
        ' Will be looking ahead one character, so we need at least 2 in the selection
        If total < 2 Then
            Return
        End If
        For x = 1 To total - 1
            a_code = Asc(.Characters(x))
            b_code = Asc(.Characters(x + 1))

            ' We want to convert a single quote in front of a number to an apostrophe
            ' Trying to use all numerical comparisons to speed this up
            If (a_code = 145 Or a_code = 39) And b_code >= 48 And b_code <= 57 Then
                .Characters(x) = Chr(146)
            End If 
        Next x
    End With
    Debug.Print "ending " + CStr(Now)
End Sub
Run Code Online (Sandbox Code Playgroud)

ium*_*umo 5

除了两个指定的(Why...? 和 How to do without...?)之外,还有一个隐含的问题 \xe2\x80\x93 如何通过 Word 对象集合进行正确的迭代。\n答案是 \xe2\x80\x93 到使用obj .Next 属性而不是通过索引访问。\n也就是说,而不是:

\n\n
For i = 1 to ActiveDocument.Characters.Count\n    'Do something with ActiveDocument.Characters(i), e.g.:\n    Debug.Pring ActiveDocument.Characters(i).Text\nNext\n
Run Code Online (Sandbox Code Playgroud)\n\n

应该使用:

\n\n
Dim ch as Range: Set ch = ActiveDocument.Characters(1)\nDo\n    'Do something with ch, e.g.:\n    Debug.Print ch.Text\n    Set ch = ch.Next 'Note iterating\nLoop Until ch is Nothing\n
Run Code Online (Sandbox Code Playgroud)\n\n

时间:00:03:30 vs. 00:00:06,超过 3 分钟 vs. 6 秒。

\n\n

在谷歌上找到的,链接丢失了,抱歉。经个人探索证实。

\n