Search code examples
vbareplacems-wordfindsuperscript

Using VBA in Word to find and format ordinal ranks with superscript


I am working in Microsoft Word and need VBA to find and format specific text as superscript. I am trying to format the following text as superscript, but only if the text immediately follows a number. Here's the four pieces of text I would need to find:

st nd rd th

Here's an example:

Bill was 1st in the race, but was followed closely by the second place finisher, Steve.

After applying the code to this example, the "st" of 1st would be formatted as a superscript, but the "nd" in second would be untouched.

Below is the code I am working with, but I can't seem to get it to work.

Sub ReplaceOrdinals()

ActiveDocument.Range.Select

Dim regExp As Object
Set regExp = CreateObject("vbscript.regexp")

With regExp
    .Pattern = "(?<=[0-9])[dhnrst]{2}"
    .Global = True
    Selection.Font.Superscript = wdToggle
End With

End Sub

Solution

  • Private Function SuperscriptAll(ByVal where As Range, ByVal pattern As String, ByVal wildcards As Boolean)
      Dim true_end As Long
      true_end = where.End
    
      With where.Find
        .ClearFormatting
        .ClearAllFuzzyOptions
    
        Do While .Execute(pattern, MatchWildcards:=wildcards, Forward:=True, Wrap:=wdFindStop)
          With .Parent
            .MoveStart wdCharacter, 1
            .Font.Superscript = True
            .SetRange .End, true_end
          End With
        Loop
      End With
    End Function
    
    Public Sub ReplaceOrdinals()
      SuperscriptAll ActiveDocument.Range, "1st", False
      SuperscriptAll ActiveDocument.Range, "2nd", False
      SuperscriptAll ActiveDocument.Range, "3rd", False
      SuperscriptAll ActiveDocument.Range, "[0-9]th", True
    End Sub