Click here to Skip to main content
15,881,709 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I need a MS Word Macro that would search for a specific substring in every paragraph throughout the document and delete paragraphs that don't contain that string.

I tried this macro code:

VB
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


But it deletes all the paragraph though it has that subtring. I don't have any clue where is the wrong in the code.
Posted

1 solution

Steps to do:

  1. Loop through the collection of paragraphs
  2. Check if paragraph contains searched string

    1. if contains, skip to next paragraph
    2. if not, delete



Sample code:
VB
Option Explicit

Sub SearchAndDestroy()
Dim p As Paragraph
Dim searchedText As String

On Error GoTo Err_SearchAndDestroy

searchedText = "Delete me"
For Each p In ThisDocument.Paragraphs
    If InStr(1, p.Range.Text, searchedText, vbBinaryCompare) > 0 Then GoTo SkipNext
    p.Range.Delete Unit:=wdParagraph, Count:=1
SkipNext:
Next

Exit_SearchAndDestroy:
    Exit Sub

Err_SearchAndDestroy:
    MsgBox Err.Description, vbExclamation, Err.Number
    Resume Exit_SearchAndDestroy
End Sub
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900