Search code examples
vbams-word

Adding missing brackets for text to speech silence codes in Word VBA


I am current trying to make a macro to find broken silence codes and add that missing bracket. It worked the first time around but it stopped working

Basically this should fix something like:

John [slnc 50]] Doe [[slnc 50]

to

John [[slnc 50]] Doe [[slnc 50]]

The tempArray will have more items in it, both longer and shorter pauses, but i put like three as an example

Dim var As String
Dim tempArray() As Variant
Dim i As Integer

                           ' Example
tempArray = Array("[[slnc 0]]", "[[slnc 25]]", "[[slnc 50]]")

For i = LBound(tempArray) To UBound(tempArray)
    var = tempArray(i)
   
 ' Check if the opening bracket is missing
    If Left(var, 2) <> "[[" Then
        var = "[[" & var
    End If
    
    ' Check if the closing bracket is missing
    If Right(var, 2) <> "]]" Then
        var = var & "]]"
    End If

    Selection.HomeKey Unit:=wdStory
    Selection.Find.ClearFormatting
    Selection.Find.Replacement.ClearFormatting
    
    With Selection.Find
        .Text = var
        .Replacement.Text = ""
        .Forward = True
        .Wrap = wdFindContinue
        .Format = False
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With

    Selection.Find.Execute Replace:=wdReplaceAll
Next

TL;DR: Needed this to add missing brackets, worked once and never again. Wondering what i am missing or what i could add


Solution

    • tempArray will have more items in it, both longer and shorter pause You don't have to keep maintaining the list.

    • Assuming there are no more than two consecutive square brackets (eg. [[[) in the document, otherwise, additional code would be needed to handle it.

    • The code replaces all instances in Word doc.

    • Note: || is used as a temp delimiter char. If you use it in the doc, using other char works well (eg. ##).

    Option Explicit
    Sub ReplaceBracket()
        Dim aTxt, sRepTxt As String, i As Long
        aTxt = Array("\[\[([!\[\]]@)\]\]", "\[([!\[\]]@)\]\]", "\[\[([!\[\]]@)\]", "||([!\[\]]@)||")
        For i = 0 To UBound(aTxt)
            sRepTxt = IIf(i = UBound(aTxt), "[[\1]]", "||\1||")
            With Selection.Find
                .ClearFormatting
                .Replacement.ClearFormatting
                .Forward = True
                .Wrap = wdFindContinue
                .Format = False
                .MatchCase = False
                .MatchWholeWord = False
                .MatchByte = False
                .MatchAllWordForms = False
                .MatchSoundsLike = False
                .MatchWildcards = True
                .Text = aTxt(i)
                .Replacement.Text = sRepTxt
                .Execute Replace:=wdReplaceAll
            End With
        Next
    End Sub
    

    enter image description here