我在Microsoft Word中工作,需要VBA才能找到特定文本并将其格式化为上标。我试图将以下文本格式化为上标,但前提是文本紧跟在数字后面。这是我需要找到的四段文字:
ST ND RD 个
以下是一个例子:
比尔在比赛中排名第一,但紧随其后的是第二名,史蒂夫。
将代码应用于此示例后,1st的“st”将被格式化为上标,但第二个中的“nd”将不受影响。
下面是我正在使用的代码,但我似乎无法让它工作。
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
答案 0 :(得分:0)
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