2016-04-28 50 views
0

我的宏应该做到以下几点:字VBA宏只能在调试模式

  1. 查找双重空间的情境。
  2. 用单个空格替换双空格的实例。
  3. 再次浏览文档以查看是否还有更多的双空格并替换它们,如果有的话。例如,如果某个地方最初有4个空格,则仍然有双空格,因此,用剩余空格替换剩余的双空格。
  4. 重复上一步直到没有更多的双空格。

问题是,宏在调试模式下完美工作,但只运行正常运行一次。我究竟做错了什么?请注意,我的代码可能不是最紧凑的,但这不重要;我真正想知道的是为什么代码只能在调试模式下工作,而不是在正常运行模式下工作,以及如何解决这个问题。

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 
+0

@CindyMeister:您的建议工作。谢谢! – user6267463

回答

0

我总是发现,测试Found属性是有点打了小姐:有时它的工作原理,有时没有。我更喜欢声明一个布尔变量并将其分配给Find.Execute,因为如果查找成功,则该方法返回True,否则返回False。

您显示的代码有另一个问题:在执行查找之前它正在测试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 
+0

我用你的代码和我的原始代码做了一些额外的测试,我确定直接测试.Found方法不是问题。相反,正如你稍后所说的,问题在于我测试了。在执行.Execute之前发现。只是想你可能想知道。再次感谢您的帮助。 – user6267463

+0

感谢您的反馈:-)是的,直接使用'.Found'可以工作,但我遇到过很多情况下,它不是我只是玩它安全,并建议相同... –