我的宏应该执行以下操作:
问题是宏在调试模式下完美运行,但如果正常运行则只运行一次。我究竟做错了什么?请注意,我的代码可能不是最紧凑的,但这不是重点;我真正想知道的是为什么代码只能在调试模式下运行而不是在正常运行模式下,以及如何解决这个问题。
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 :(得分: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