在Word VBA中从空格中删除下标/上标

时间:2018-09-05 04:11:58

标签: ms-word word-vba

我的目标是从空格中删除下标或上标格式。

当我运行以下代码时,只有顶层函数起作用,而底层函数却无能为力。如果我切换功能的位置,仍然只有顶部功能起作用。功能几乎相同,我不知道从哪里开始修复。请有人能指出正确的方向吗?

Dim oRng As Word.Range
Set oRng = ActiveDocument.Range

'For subscripted spaces

Selection.HomeKey unit:=wdStory
With oRng.Find
 .ClearFormatting
 .Replacement.ClearFormatting
.Forward = True
.Text = "[A-z0-9] "
.Replacement.Text = ""
.MatchWholeWord = False
    While .Execute
        If oRng.Characters(2).Font.Subscript = True Then
        oRng.Characters(2).Font.Subscript = False
        End If
    oRng.Collapse direction:=wdCollapseEnd
    Wend
End With

'For superscripted spaces

 Selection.HomeKey unit:=wdStory
With oRng.Find
 .ClearFormatting
 .Replacement.ClearFormatting
.Forward = True
.Text = "[A-z0-9] "
.Replacement.Text = ""
.MatchWholeWord = False
    While .Execute
        If oRng.Characters(2).Font.Superscript = True Then
        oRng.Characters(2).Font.Superscript = False
        End If
    oRng.Collapse direction:=wdCollapseEnd
    Wend
End With

1 个答案:

答案 0 :(得分:0)

问题在于,当您完成对第一个序列的处理时,Rng定义的范围已折叠到最后一个Found实例。无论如何,您不需要循环。试试:

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