[英]Word VBA Macro to comment out nested parenthesis
我有一個宏如下:
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
但是,如果我有嵌套括號,這不起作用,例如This is my (nested parenthesis (document ) in full)
它將匹配第一個右括號而不是最外面的括號。 有沒有辦法在匹配的地方編寫正則表達式?
嘗試:
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
作為建議,請嘗試在每個模塊/類/表單的開頭使用 Option Explicit。 這將阻止您使用尚未聲明的變量。
下面的代碼將減少
This is my (nested parenthesis (document ) in full)
至
This is my
和
(nested parenthesis (document ) in full)
添加為評論。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.