Word VBA将文档中特定字符设置为上标或下标

Option Explicit

Sub SetSuperscriptAndSubscript(ByVal PrefixChr As String, ByVal SetChr As String, Optional ByVal SuperscriptMode As Boolean = True)
    '程序功能:设置文档中特定字符为上标或下标。

    '参数说明:
    'PrefixChr:必选参数,要设置为上、下标字符之前的字符;
    'SetChr:必选参数,要设置为上、下标的字符;
    'SuperscriptMode:可选参数,设置为 True 表示将 SetChr 设置为上标,设置为 False 表示将 SetChr 设置为下标,默认为 True。

    '举例说明:
    '我们要将文档中所有的“m3/s”中的“3”设置为上标,可通过下面这一行代码调用本程序完成:
    'SetSuperscriptAndSubscript "M","3" '这里设置上标,可省略第三个参数。

    Selection.Start = ActiveDocument.Paragraphs(1).Range.Start '将光标定位至活动文档第一段落段首的位置
    Selection.Collapse wdCollapseStart '折叠至起始位置
    With Selection.Find
        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = PrefixChr & SetChr
        .Replacement.Text = "^&"
        If SuperscriptMode Then .Replacement.Font.Superscript = True Else .Replacement.Font.Subscript = True
        .Execute Replace:=wdReplaceAll

        .ClearFormatting
        .Replacement.ClearFormatting
        .Text = PrefixChr
        If SuperscriptMode Then .Font.Superscript = True Else .Font.Subscript = True
        .Replacement.Text = "^&"
        If SuperscriptMode Then .Replacement.Font.Superscript = False Else .Replacement.Font.Subscript = False
        .Execute Replace:=wdReplaceAll
    End With
End Sub

发表评论

邮箱地址不会被公开。 必填项已用*标注