none
Delete specific paragraphs based on substring using word macro RRS feed

  • Question

  • 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:

        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. 
    Wednesday, December 17, 2014 7:18 AM

Answers

  • As a minimum, you need another parameter in the Instr. You can then probably get away with this:

    If Instr(1,LCase(txt), search) Then

    [Personally I would probably accept that Instr returns a number and spell it out

    If Instr(1,LCase(txt), search) > 0 Then


    Peter Jamieson

    • Marked as answer by VidhyaRaju Wednesday, December 17, 2014 10:33 AM
    Wednesday, December 17, 2014 9:59 AM

All replies

  • As a minimum, you need another parameter in the Instr. You can then probably get away with this:

    If Instr(1,LCase(txt), search) Then

    [Personally I would probably accept that Instr returns a number and spell it out

    If Instr(1,LCase(txt), search) > 0 Then


    Peter Jamieson

    • Marked as answer by VidhyaRaju Wednesday, December 17, 2014 10:33 AM
    Wednesday, December 17, 2014 9:59 AM
  • Thank you so much it works fine.
    Wednesday, December 17, 2014 10:34 AM
  • You might find the following code more efficient:

    Sub Demo()
    Application.ScreenUpdating = False
    With ActiveDocument.Range
      .Font.Hidden = True
      With .Find
        .ClearFormatting
        .Text = InputBox("What is the Text to Find")
        With .Replacement
          .ClearFormatting
          .Text = ""
          .Font.Hidden = False
        End With
        .Forward = True
        .Wrap = wdFindStop
        .Format = True
        .MatchCase = True
        .MatchWholeWord = False
        .MatchWildcards = False
        .MatchSoundsLike = False
        .MatchAllWordForms = False
        .Execute
      End With
      Do While .Find.Found
        .Paragraphs.First.Range.Font.Hidden = False
        .Collapse wdCollapseEnd
        .Find.Execute
      Loop
      With .Find
        .Replacement.ClearFormatting
        .Wrap = wdFindContinue
        .Font.Hidden = True
        .Text = ""
        .Execute Replace:=wdReplaceAll
      End With
    End With
    Application.ScreenUpdating = True
    End Sub


    Cheers
    Paul Edstein
    [MS MVP - Word]

    Thursday, December 18, 2014 3:46 AM