在Word VBA中浏览段落

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

我有一个 VBA 函数,我想删除用户引入的第一个数字不同的每个段落。此外,它还会删除该段落编号。

示例:

第 1 段:“03 text1”

第2段:“12个文本2”

第3段:“22 text3”

如果用户引入数字1,则文档必须只保留以下段落:“2 text2”

问题是,一旦我删除了段落的第一个数字,for函数就会认为修改后的段落是一个新段落!所以目前在最后一个示例中所有内容都被删除了。

这是我的函数的代码:

`
暗淡作为段落 将第一个字符调暗为字符串

' Run through every paragraph of the document
For Each par In doc.Paragraphs

    'define first character of the paragraph
    firstCharacter = Left(Trim(par.Range.Text), 1)
    
    'check if the first character is numeric
    If IsNumeric(firstCharacter) Then
    
        'if the number is the same, just remove the number, if not, remove the whole paragraph
        If firstCharacter = aux Then
            par.Range.Text = Trim(Mid(par.Range.Text, 2))
        Else
            par.Range.Delete
        End If
    End If
Next par`

输入示例:

第 1 段:“03 text1”

第2段:“12个文本2”

第3段:“22 text3”

用户介绍1

输出:

“2 文本2”

excel vba ms-word macros ms-office
1个回答
0
投票

这就是 Word 在处理元素时如何处理从集合中删除元素的情况。

一种解决方法,用于收集所有相关段落并最后将其放回文档中。

Sub mi()
Dim par As Paragraph, firstCharacter As String
Set doc = ActiveDocument
' Run through every paragraph of the document
aux = 1
For Each par In doc.Paragraphs

    'define first character of the paragraph
    firstCharacter = Left(Trim(par.Range.Text), 1)
    
    'check if the first character is numeric
    If IsNumeric(firstCharacter) Then
    
        'if the number is the same, just remove the number, if not, remove the whole paragraph
        If firstCharacter = aux Then
            buffer = buffer & Trim(Mid(par.Range.Text, 2))
        Else
            par.Range.Delete
        End If
    Else
        buffer = buffer & par.Range.Text    
    End If
Next par
doc.Range.Delete   ' this is needed because the last paragraph would be kept if corresponds to the test.
doc.Range.InsertAfter buffer
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.