ActiveDocument.Paragraphs.Range 的奇怪行为

问题描述 投票:0回答:1

不是 VBA 专家,但我正在尝试做一些非常简单的事情。我正在尝试删除 Word 文档中每个段落的前导空格。

这是我的VBA代码:

Function RemoveLeadingSpaces()
    Dim apara As Paragraph

    Application.ScreenUpdating = False
    For Each apara In ActiveDocument.Paragraphs

        'apara.Range.Text = Trim(apara.Range.Text)
        Debug.Print apara.Range.Text

    Next apara
    Application.ScreenUpdating = True
End Function

当我取消注释替换文本的行时,我开始出现一些奇怪的行为。循环变得无限,它只一遍又一遍地应用/替换第一个项目/段落。如果我发表评论,那么调试会按应有的方式打印所有段落。

我做错了什么?

vba ms-word
1个回答
0
投票

通过添加两行调试行,您可以观察到第 5 行(覆盖段落分隔符)不仅修改了循环变量,还修改了

Paragraph collection
。在下一次循环迭代中,选择更新的第一段,从而创建无限循环。

Function RemoveLeadingSpaces()
    Dim apara As Paragraph
    For Each apara In ActiveDocument.Paragraphs
        apara.Range.Select ' the 1st paragraph is selected
        apara.Range.Text = Trim(apara.Range.Text)
        apara.Range.Select ' the 2nd paragraph is selected
        Debug.Print apara.Range.Text
    Next apara
End Function

enter image description here


请尝试删除前导空格而不影响段落分隔符。

Sub DemoRemoveLeadingSpaces()
    Dim apara As Paragraph, rngPara As Range
    Application.ScreenUpdating = False
    For Each apara In ActiveDocument.Paragraphs
        Set rngPara = apara.Range.Duplicate
        rngPara.MoveEnd wdCharacter, -1
        rngPara.Text = Trim(rngPara.Text)
        Debug.Print apara.Range.Text
    Next apara
    Application.ScreenUpdating = True
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.