Search code examples
vbams-wordtext-formatting

Format text segments after returns and : in text


We have an array of documents to be formatted for better visibility.

As the output of our speech to text protocols we get a transcript.

The VBA script should format the text bold after every (return), and the text after a (:) not bold until the next return.

Example:
Speaker1 Question1: Answer Answer Answer
Speaker1 Question2: Answer Answer Answer

This is not working as expected already at the first part of the function.

Sub BoldGenerator()

    ' BoldGenerator Macro
    Selection.WholeStory

    'Make each .Method belong to Selection.Find for readability
    With Selection.Find
        'Set search criteria for break font
        .Text = "^l"
        'Find next occurrence
        .Execute
        
        Do While .Found
        Selection.Text = Selection.Font.Bold = True
        .Execute
        Loop
        
    End With
    
    '
    Call BoldGenerator
End Sub

Solution

  • This should bold everything between a (return) (actually it is a new line or a carriage return) and a colon (:)

    It is not an easy VBA. Regular expressions are used which are not native in VBA, so we need to get them from VBScript library. We use regular expressions to find all instances starting after a carriage return and ending with a colon. Regular expressions are not able to change the format (to bold). So we need to use .Find method too. We again find what we previously found, but this time we make it bold.

    You will see the first instance will not become bold, because it does not start after a carriage return.

    Sub BoldGenerator()
    
    Dim RE As Object
    Dim REMatches As Object
    Dim mch As Object
    
    Selection.HomeKey wdStory
    Selection.WholeStory
    
    Set RE = CreateObject("vbscript.regexp")
    With RE
      .Global = True
      .Pattern = "\r(.+?:)"
    End With
    Set REMatches = RE.Execute(Selection.Text)
    
    If REMatches.Count > 0 Then
      Selection.HomeKey wdStory
        With Selection.Find
          .ClearFormatting
          .Forward = True
          .Format = False
          .MatchCase = True
          For Each mch In REMatches
            .Text = mch
            .Execute
            Selection.Font.Bold = True
            Selection.MoveRight wdCharacter
          Next
        End With
      Selection.HomeKey wdStory
    End If
    
    Set RE = Nothing
    Set REMatches = Nothing
    Set mch = Nothing
    
    End Sub