I have a macro as follows:
Sub CommentOutParenthsLocal()
'
' CommentBubble Macro
'
'
Dim myRange As Range
Set myRange = Selection.Range
Set oScope = myRange.Duplicate
searchText = "\(*\)"
With myRange.Find
.MatchWildcards = True
Do While .Execute(findText:=searchText, Forward:=True) = True
If myRange.InRange(oScope) Then
If Len(myRange.Text) > 4 Then
ActiveDocument.Comments.Add myRange, myRange.Text
myRange.Text = ""
End If
Else
Exit Do
End If
Loop
End With
End Sub
However, this doesn't work if I have nested parenthesis for example This is my (nested parenthesis (document ) in full)
It will match to the first right parenthesis not the outermost. Is there a way to write a regular expression where it matches?
Try:
Sub Demo()
Application.ScreenUpdating = False
Dim Rng As Range
With Selection
Set Rng = .Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "\([!\(]@\)"
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
.Execute
End With
Do While .Find.Found
If Not .InRange(Rng) Then Exit Do
If Len(.Text) > 4 Then
.Comments.Add .Range, .Text
.Text = ""
End If
.Collapse wdCollapseEnd
.Find.Execute
Loop
End With
Application.ScreenUpdating = True
End Sub
As advice, please try to use Option Explicit at the start of every Module/Class/Form. This will prevent you from using variables that you haven't declared.
The code below will reduce
This is my (nested parenthesis (document ) in full)
To
This is my
with
(nested parenthesis (document ) in full)
added as a comment.
Option Explicit
Sub CommentOutParenthsLocal()
'
' CommentBubble Macro
'
'
Dim myRange As Range
Set myRange = Selection.Range
Dim oScope As Word.Range
Set oScope = myRange.Duplicate
Dim searchtext As String
searchtext = "\(*\)"
With myRange.Find
.MatchWildcards = True
Do While .Execute(findText:=searchtext, Forward:=True) = True
myRange.Select
If myRange.InRange(oScope) Then
Dim myCount As Long
Dim myText As String
myText = myRange.Text
myCount = Len(myText) - Len(Replace(myText, "(", vbNullString)) - 1
Do Until myCount = 0
myRange.MoveEndUntil cset:=")"
myRange.MoveEnd Count:=1
myCount = myCount - 1
Loop
If Len(myRange.Text) > 4 Then
ActiveDocument.Comments.Add myRange, myRange.Text
myRange.Text = ""
End If
Else
Exit Do
End If
myRange.Start = myRange.End + 1
myRange.End = oScope.End
Loop
End With
End Sub
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.