简体   繁体   English

使用单词宏基于子字符串删除特定段落

[英]Delete specific paragraphs based on substring using word macro

I want to search for a specific string in every paragraph throughout the document and delete paragraphs that don't contain that string. 我想在整个文档的每个段落中搜索特定的字符串,然后删除不包含该字符串的段落。

I tried this macro code: 我尝试了以下宏代码:

Sub DeleteParagraphContainingString()

    Dim search As String
    search = "delete me"

    Dim para As Paragraph
    For Each para In ActiveDocument.Paragraphs

        Dim txt As String
        txt = para.Range.Text

        If Not InStr(LCase(txt), search) Then
            para.Range.Delete
        End If

    Next

End Sub

It deletes paragraphs although it has that string. 尽管具有该字符串,但它会删除段落。

Simplify the code. 简化代码。 The change that made the code work was separating the If statement from the InStr() function. 使代码起作用的更改是将If语句与InStr()函数分开。 Performing the check first in a separate line then test the result. 首先在单独的一行中执行检查,然后测试结果。

TESTED: 测试:

Sub DeleteParagraphContainingString()

    Dim check As Boolean
    Dim search As String
    Dim para As Paragraph
    Dim tempStr As String
    Dim txt As String

    search = "delete me"

    For Each para In ActiveDocument.Paragraphs
        txt = para.Range.Text
        tempStr = LCase(txt)
        check = InStr(tempStr, search)

        If check = False Then
            para.Range.Delete
        End If
    Next
End Sub

BEFORE: 之前:

之前

AFTER: 后:

后

Thank you so much for this piece of code. 非常感谢您提供这段代码。 Just had to replace the False parameter with True. 只需将False参数替换为True。 Otherwise, it would keep only the very paragraphs that contain the string "delete me" it was intended to vaporize. 否则,它将仅保留包含打算蒸发的字符串“删除我”的段落。

See below: 见下文:

Sub DeleteParagraphContainingString() 子DeleteParagraphContainingString()

Dim check As Boolean
Dim search As String
Dim para As Paragraph
Dim tempStr As String
Dim txt As String

search = "delete me"

For Each para In ActiveDocument.Paragraphs
    txt = para.Range.Text
    tempStr = LCase(txt)
    check = InStr(tempStr, search)

    If check = True Then
        para.Range.Delete
    End If
Next

End Sub 结束子

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM