我想在整个文档的每个段落中搜索特定的字符串,并删除不包含该字符串的段落。
我尝试了这个宏代码:
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
虽然它有字符串,但它会删除段落。
答案 0 :(得分:1)
简化代码。使代码工作的更改是将If语句与InStr()函数分开。首先在单独的行中执行检查,然后测试结果。
<强>试验:强>
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:强>
答案 1 :(得分:0)
非常感谢您使用这段代码。只需要用True替换False参数。否则,它只保留包含字符串“删除我”的段落,它意图使其蒸发。
见下文:
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 = True Then
para.Range.Delete
End If
Next
End Sub