Jan 31 2024 02:30 AM
I wonder if any VBA experts can help. I found online the following macro to remove square brackets.
Sub RemoveSquareBrackets()
Dim oRng As Range
Set oRng = ActiveDocument.Range
With oRng.Find
.ClearFormatting
.Text = "\[*\]"
.MatchWildcards = True
While .Execute
With oRng
.Select
Select Case MsgBox("Do you want to remove brackets?", vbQuestion + vbYesNoCancel, "???")
Case Is = vbYes
.Characters.First.Delete
.Characters.Last.Delete
.Collapse wdCollapseEnd
Case Is = vbNo
.Collapse wdCollapseEnd
Case Else
Exit Sub
End Select
End With
Wend
End With
lbl_Exit:
Exit Sub
End Sub
I want a simpler macro that simply removes the first brackets to the left and right of the cursor (i.e. just one pair of brackets) and does not cycle through the document. If there are no brackets or only a single bracket then a pop up to give a warning.
Many thanks in advance.
Feb 01 2024 12:57 AM
@inarbeth Use
Dim oRng As Range
Set oRng = Selection.Range
With oRng
.Start = ActiveDocument.Range.Start
.Start = .Start + InStrRev(.Text, "(") - 1
.End = ActiveDocument.Range.End
.End = .Start + InStr(.Text, ")")
.Characters(1).Delete
.Characters(.Characters.Count).Delete
.Select
End With
Feb 01 2024 02:04 AM - edited Feb 01 2024 02:06 AM
@Doug_Robbins_Word_MVP Many thanks, Doug. It works very well with one issue. If there are no brackets left, it removes the first two characters in the document. Sorry for my ignorance but how do I insert a condition to Exit Sub if no bracket is found?
Feb 01 2024 02:18 AM
@inarbeth Use
Dim oRng As Range
Set oRng = Selection.Range
With oRng
.Start = ActiveDocument.Range.Start
.Start = .Start + InStrRev(.Text, "(") - 1
.Characters(1).Delete
.End = ActiveDocument.Range.End
If InStr(.Text, ")") <> 0 Then
.End = .Start + InStr(.Text, ")")
.Characters(.Characters.Count).Delete
End If
End With
Feb 02 2024 09:11 AM
Feb 02 2024 06:13 PM
@inarbeth Use a similar test
Dim oRng As Range
Set oRng = Selection.Range
With oRng
.Start = ActiveDocument.Range.Start
If InStr(.Text, "(") <> 0 Then
.Start = .Start + InStrRev(.Text, "(") - 1
.Characters(1).Delete
End If
.End = ActiveDocument.Range.End
If InStr(.Text, ")") <> 0 Then
.End = .Start + InStr(.Text, ")")
.Characters(.Characters.Count).Delete
End If
End With