MS Word VBA,全部替换,死循环

MS Word VBA, replace all, infinite loop

我有一个看似简单的 VBA 问题,我一直在努力解决自己的问题。我的目标是开发一个宏来突出显示从一个左括号到下一个左括号的文本(如果它们之间没有右括号)。该宏在大多数情况下运行良好,但在我将在下面描述的其他情况下会产生无限循环。这是宏:

Sub HighlightNestedParentheses()
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    Selection.Find.Replacement.Highlight = True
    Options.DefaultHighlightColorIndex = wdGray50
    With Selection.Find
        .Text = "\([!\)]@\("
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchAllWordForms = False
        .MatchSoundsLike = False
        .MatchWildcards = True
    End With
    Selection.Find.Execute Replace:=wdReplaceAll
End Sub

当 Word 文件包含以下文本时,宏可以正常工作:

text (text (text

但是,当文档仅包含一个左括号时,宏会创建一个无限循环,如下所示:

text (text

在第二种情况下,我更希望宏不突出显示任何文本,并且一直在努力弄清楚为什么宏会进入无限循环或如何解决此问题。

非常感谢您的意见!

尝试:

Sub Demo()
Application.ScreenUpdating = False
Dim Rng As Range
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "\(*\)"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindStop
    .Format = False
    .MatchWildcards = True
  End With
  Do While .Find.Execute
    With .Duplicate
      Set Rng = .Characters.Last
      Do While InStr(2, .Text, "(", vbTextCompare) > 0
        .MoveEndUntil ")", wdForward
        .End = .End + 1
        .Start = .Start + 1
        .MoveStartUntil "(", wdForward
        Set Rng = .Characters.Last
      Loop
    End With
    .End = Rng.End
    .HighlightColorIndex = wdGray50
    .Collapse wdCollapseEnd
  Loop
End With
Application.ScreenUpdating = True
End Sub

修改后的描述:

Sub Demo()
Application.ScreenUpdating = False
Dim Rng As Range
With ActiveDocument.Range
  Set Rng = .Duplicate
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Text = "("
    .Replacement.Text = ""
    .Forward = False
    .Wrap = wdFindStop
    .Format = False
    .MatchWildcards = False
  End With
  Do While .Find.Execute
    Rng.Start = .Start + 1
    With Rng
      If InStr(.Text, ")") = 0 Then
        .HighlightColorIndex = wdBrightGreen
      Else
        .MoveEndUntil ")", wdBackward
        If InStr(.Text, "(") = 0 Then
          .MoveEndUntil "(", wdBackward
          .HighlightColorIndex = wdBrightGreen
        End If
      End If
    End With
    .Collapse wdCollapseStart
  Loop
End With
Application.ScreenUpdating = True
End Sub