Word VBA:遍历字符非常慢 [英] Word VBA: iterating through characters incredibly slow

查看:34
本文介绍了Word VBA:遍历字符非常慢的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a macro that changes single quotes in front of a number to an apostrophe (or close single curly quote). Typically when you type something like "the '80s" in word, the apostrophe in front of the "8" faces the wrong way. The macro below works, but it is incredibly slow (like 10 seconds per page). In a regular language (even an interpreted one), this would be a fast procedure. Any insights why it takes so long in VBA on Word 2007? Or if someone has some find+replace skills that can do this without iterating, please let me know.

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

推荐答案

除了两个指定的(为什么...?和如何不用...?)还有一个隐含的问题——如何通过 Word 对象集合进行适当迭代.答案是 – 使用 obj.Next 属性而不是通过索引访问.也就是说,而不是:

Beside two specified (Why...? and How to do without...?) there is an implied question – how to do proper iteration through Word object collection. Answer is – to use obj.Next property rather than access by index. That is, instead of:

For i = 1 to ActiveDocument.Characters.Count
    'Do something with ActiveDocument.Characters(i), e.g.:
    Debug.Pring ActiveDocument.Characters(i).Text
Next

应该使用:

Dim ch as Range: Set ch = ActiveDocument.Characters(1)
Do
    'Do something with ch, e.g.:
    Debug.Print ch.Text
    Set ch = ch.Next 'Note iterating
Loop Until ch is Nothing

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

Timing: 00:03:30 vs. 00:00:06, more than 3 minutes vs. 6 seconds.

在 Google 上找到,链接丢失,抱歉.经个人探索确认.

Found on Google, link lost, sorry. Confirmed by personal exploration.

这篇关于Word VBA:遍历字符非常慢的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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