VBA 在 MSWord 的上标和下标前后插入

VBA to insert before and after superscript and subscript in MSWord

我正在尝试创建 VBA 以在上标和下标前后插入。我的代码如下。

Public Sub MySubscriptSuperscript() 
Dim myRange As Word.Range, myChr 
For Each myRange In ActiveDocument.StoryRanges  
Do     
     For Each myChr In myRange.Characters 
     If myChr.Font.Superscript = True Then
        myChr.Font.Superscript = False
        myChr.InsertBefore "<sup>"
        myChr.InsertAfter "</sup>"
    End If  

    If myChr.Font.Subscript = True Then
        myChr.Font.Subscript = False
        myChr.InsertBefore "<sub>"
        myChr.InsertAfter "</sub>"
    End If
Next
Set myRange = myRange.NextStoryRange
Loop Until myRange Is Nothing   
Next 
End Sub

此代码适用于上标和下标的每个字符。

但是,我正在寻找 VBA 在完成之前和之后插入标签 superscript/subscript word/letters。

示例

C12H22O11 和 x23 + y397 + x67

以上 VBA 给出以下输出

C<sub>1</sub><sub>2</sub>H<sub>2</sub><sub>2</sub>O<sub>1</sub><sub>1</sub><sub> </sub><sub> </sub> and x<sup>2</sup><sup>3</sup> + y<sup>3</sup><sup>9</sup><sup>7</sup> + x<sup>6</sup><sup>7</sup>

但我正在寻找这个输出

C<sub>12</sub>H<sub>22</sub>O<sub>11</sub> and x<sup>23</sup> + y<sup>397</sup> + x<sup>67</sup>

请指导,这是如何实现的。

我很想采用最简单的方法来获得最终结果 - 最后,只需将 </sub><sub></sup><sup> 替换为空字符串 ""

不过,我就是这样偷懒的...

编辑 - 只是一个想法: 用替换来完成整个事情会不会更快?您不必检查每个字符。以下是 Word 为替换所做的记录,需要一些润色:

    Selection.Find.Replacement.ClearFormatting
    With Selection.Find.Replacement.Font
        .Superscript = False
        .Subscript = False
    End With
    With Selection.Find
        .Text = "^?"
        .Replacement.Text = "<sup>^&</sup>"
        .Forward = True
        .Wrap = wdFindContinue
        .Format = True
        .MatchCase = False
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
    End With
    Selection.Find.Execute Replace:=wdReplaceAll

因此,最后,您将 运行 搜索并替换 4 次:

  • 替换上标
  • 删除上标的结束标签和开始标签
  • 替换下标
  • 删除下标的结束标签和开始标签

尝试:

Sub Demo()
Application.ScreenUpdating = False
With ActiveDocument.Range
  With .Find
    .ClearFormatting
    .Replacement.ClearFormatting
    .Forward = True
    .Text = ""
    .Wrap = wdFindContinue
    .Font.Subscript = True
    .Replacement.Text = "<sub>^&<\sub>"
    .Execute Replace:=wdReplaceAll
    .Font.Superscript = True
    .Replacement.Text = "<sup>^&<\sup>"
    .Execute Replace:=wdReplaceAll
  End With
End With
Application.ScreenUpdating = True
End Sub

不清楚为什么要遍历所有故事范围,因为此类内容通常只出现在文档正文中。也就是说,修改代码以适用于所有故事范围很容易。