Word VBA宏仅在调试模式下工作

时间:2016-04-28 15:39:19

标签: vba debugging replace ms-word

我的宏应该执行以下操作:

  1. 查找双空格的实例。
  2. 用单个空格替换双空格的实例。
  3. 再次浏览文档以查看是否有更多的双倍空格并替换它们(如果有)。例如,如果某个地方最初有4个空格,那么仍然会有双重空格,因此,用单个空格替换剩余的双空格。
  4. 重复上一步,直到没有更多的双倍空格。
  5. 问题是宏在调试模式下完美运行,但如果正常运行则只运行一次。我究竟做错了什么?请注意,我的代码可能不是最紧凑的,但这不是重点;我真正想知道的是为什么代码只能在调试模式下运行而不是在正常运行模式下,以及如何解决这个问题。

    Sub Test_for_doubles()
    '
    ' Test_for_doubles Macro
    '
    Dim blnFoundDoubles As Boolean
    blnFoundDoubles = True
    Do While blnFoundDoubles = True
        Selection.HomeKey Unit:=wdStory 'Go to the beginning of the document.
        blnFoundDoubles = False 'Don't go through this loop again unless we find a double this time through
        With Selection.Find
            .Text = "  "
            .Replacement.Text = " "
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
            If .Found = True Then
                blnFoundDoubles = True
            End If
        End With
    Selection.Find.Execute Replace:=wdReplaceAll
    Loop
    End Sub
    

1 个答案:

答案 0 :(得分:0)

我总是发现测试Found属性有点昙花一现:有时候它有效,有时候不行。我更喜欢声明一个布尔变量并将其分配给Find.Execute,因为如果查找成功,该方法返回True,否则返回False。

您展示的代码还有另一个问题:它在执行Find之前测试Found。尝试将代码更改为更像这样的代码:

Dim blnFoundDoubles As Boolean
Dim bFound as Boolean
blnFoundDoubles = True
bFound = False
Do While blnFoundDoubles = True
    Selection.HomeKey Unit:=wdStory 'Go to the beginning of the document.
    blnFoundDoubles = False 'Don't go through this loop again unless we find a double this time through
    With Selection.Find
        .Text = "  "
        .Replacement.Text = " "
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        bFound = .Execute(Replace:=wdReplaceAll)
        If bFound Then
            blnFoundDoubles = True
        End If
        'OR
        'blnFoundDoubles = bFound
    End With
Loop