Tuesday, December 24, 2024

VBA Word - Delete lines which contain specific text

The following VBA code deletes all lines from Word document which contain "Copy code" text. It also deletes the line before the text. Effectively, it deletes 2 lines in each iteration:

Sub DeleteLineBeforeAndContainingCopyCode()
    Dim doc As Document
    Dim currentPosition As Long
    Dim findRange As Range
    Dim deleteRange As Range

    ' Set the document
    Set doc = ActiveDocument

    ' Start from the bottom of the document
    currentPosition = doc.Content.End

    ' Loop until the top of the document
    Do While currentPosition > 0
        ' Set a range starting from the current position
        Set findRange = doc.Range(Start:=0, End:=currentPosition)

        ' Find the "Copy code" text
        With findRange.Find
            .Text = "Copy code"
            .Forward = False ' Search upwards
            .Wrap = wdFindStop
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
        End With

        If findRange.Find.Execute Then
            ' Create a range to delete the current and previous lines
            Set deleteRange = doc.Range(Start:=findRange.Paragraphs(1).Range.Start, _
                                        End:=findRange.Paragraphs(1).Range.End)

            ' Include the line above if it exists
            If findRange.Start > doc.Range.Start Then
                deleteRange.Start = deleteRange.Start - 1
                deleteRange.Start = deleteRange.Paragraphs(1).Range.Start
            End If

            ' Delete the range
            deleteRange.Delete

            ' Update the current position
            currentPosition = findRange.Start
        Else
            ' Exit the loop if "Copy code" is not found
            Exit Do
        End If
    Loop
    MsgBox "Done"
End Sub

No comments:

Post a Comment

Hot Topics