Macro to remove brackets

Copper Contributor

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.

6 Replies

@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

@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?

@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
Not quite. If there are no brackets, the macro deletes the first character on the page.

@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
Many thanks Doug.