Format number between markers as subscript

2019-08-31 08:04发布

问题:

I would like to find a number between two hashtags, delete the hashtags and format the number that was between the hashtags as subscript.

Example: The text ##12## should be converted to 12.

Here is my code so far:

Public Sub SubscriptText()
    With Selection.Find
         .ClearFormatting
         .Text = "##"
         .Replacement.ClearFormatting
         .Replacement.Text = "##"
         .Execute Replace:=wdReplaceAll, Forward:=True, Wrap:=wdFindContinue
    End With
End Sub

This removes the ##, but how do I format the number as subscript?

回答1:

I would do this: look for the end of the opening hashtag, and the start of the closing hashtag. Everything between those two positions is presumably a number for which you want to change the font.

end of
opening
hashtag
    ꜜ
 # # 1 2 # # 
        ꜛ
     start of
     closing
     hashtag       

This worked for me:

Dim wd As Document
Dim rOpeningHashtag As Range
Dim rClosingHashtag As Range
Dim rBewteenHashtags As Range
Dim hashtagFound As Boolean

Set wd = ActiveDocument
wd.Range.Select

Do
    'Look for opening hashtag
    hashtagFound = Selection.Find.Execute("##")
    If Not hashtagFound Then Exit Do 'end of document reached
    Set rOpeningHashtag = Selection.Range
    'Look for closing hashtag
    Selection.Find.Execute "##"
    Set rClosingHashtag = Selection.Range

    'Number is in between the two.
    Set rBewteenHashtags = wd.Range(rOpeningHashtag.End, rClosingHashtag.Start)
    rBewteenHashtags.Font.Subscript = True
    'Get rid of the opening and closing hashtags
    rClosingHashtag.Delete
    rOpeningHashtag.Delete
Loop