突出显示从一个左括号到下一个右括号的文本



我的目标是突出显示从一个左括号到下一个右括号的文本,如果它们之间没有右括号的话。

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

但是,当文档包含一个开括号时,会有一个无限循环:

文本(文本

在第二种情况下,我不喜欢突出显示任何文本。

尝试:

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

相关内容

  • 没有找到相关文章

最新更新