vbams-word

Set style of multiple words based on first character


I have a series of quotes stored in single column table rows in Word 365 (Version 2403, Build 16.0).

I need to adjust the formatting of the quote attribution.

The format of each quote/row is:

This is a quote.
- Attribution Name
This is a quote.
- Attribution 
This is a quote.
- Attribution123

The Attribution may be 1 or 2 words of alphanumeric characters.

I need to format all characters after the "- ". Currently, my attempts format up until the space after the first word. It works on single name attributions.

My current code:

Sub DashFormat()
'
' DashFormat Macro
'
'
    
    With ActiveDocument.Range.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Forward = True
        .Format = True
        .Wrap = wdFindContinue
        .MatchWildcards = True
        .MatchWholeWord = False
        .Text = "- [A-z0-9]@>"
        .Replacement.Style = "Subtle Emphasis"
        .Execute Replace:=wdReplaceAll
    End With
End Sub

The above applies the style to everything after the - except " Name".

I understand all of this except the function of @> at the end of the .Text string. I know that it doesn't work without the addition of some character specification in brackets before it.

I tried adding a space in the brackets.
I tried indicating space Chr codes.
I played with wildcards and escape characters.

Can anyone help design the query or explain the function of @>?


Solution

  • Find and Replace using wildcards

    @ is used to find re-occurrences of the previous character (if any)

    > is used to mark the end of a word

    Sub DashFormat()
        With ActiveDocument.Range.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Forward = True
            .Format = True
            .Wrap = wdFindContinue
            .MatchWildcards = True
            .MatchWholeWord = False
            .Text = "- [A-z0-9]@>"
            .Replacement.ClearFormatting
            .Replacement.Style = "Subtle Emphasis"
            .Execute Replace:=wdReplaceAll
            .Text = "- [A-z0-9]@> [A-z0-9]@>"
            .Execute Replace:=wdReplaceAll
        End With
    End Sub
    

    Update:

    Sub DashFormat()
        Dim docRng As Range
        Set docRng = ActiveDocument.Content
        With docRng.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .Forward = True
            .Format = False
            .Wrap = wdFindStop
            .MatchWildcards = True
            .MatchWholeWord = False
            .Text = "- [A-z0-9]@>"
            .Replacement.ClearFormatting
            Do While .Execute
                docRng.Expand Unit:=wdSentence
                If UBound(Split(docRng.Text)) < 3 Then
                    docRng.Style = "Subtle Emphasis"
                    docRng.Collapse Word.wdCollapseEnd
                End If
            Loop
        End With
    End Sub