Home » excel » excel – VBA deleting rows based on cell vale

excel – VBA deleting rows based on cell vale

Posted by: admin May 14, 2020 Leave a comment

Questions:

enter image description hereI’ve written the following code where i want to find the value “BEST Cards Raised:” in column B and where ever this value is delete this and all subsequent rows with data in column B.

I thought what i’ve written would work but its currently deleting all rows and I cant figure it out 🙁

Dim lastRow As Long, found As Range
With ActiveSheet

    Set found = .Range("B1:B" & .Cells(.Rows.Count, "B").End(xlUp).Row).Find("BEST Cards Raised:")
    If Not found Is Nothing Then
        lastRow = .Cells.Find(What:="*", _
                              After:=.Cells(1, 1), _
                              Lookat:=xlPart, _
                              LookIn:=xlFormulas, _
                              SearchOrder:=xlByRows, _
                              SearchDirection:=xlPrevious, _
                              MatchCase:=False).Row
        If lastRow >= found.Row Then
            Debug.Print .Rows(found.Row & ":" & lastRow).EntireRow.Delete
        End If
    End If
End With
How to&Answers:

If also deleting the row where found then perhaps try the following:

Option Explicit
Public Sub DeleteRows()
    Dim lastRow As Long, found As Range
    With ThisWorkbook.Worksheets("Sheet1") '<your sheet

        Set found = .Range("B1:B" & .Cells(.Rows.Count, "B").End(xlUp).Row).Find("BEST Cards Raised:")
        If Not found Is Nothing Then
            lastRow = .Cells.Find(What:="*", _
                                  After:=.Cells(1, 1), _
                                  Lookat:=xlPart, _
                                  LookIn:=xlFormulas, _
                                  SearchOrder:=xlByRows, _
                                  SearchDirection:=xlPrevious, _
                                  MatchCase:=False).Row
            If lastRow >= found.Row Then
                .Rows(found.Row & ":" & lastRow).EntireRow.Delete
            End If
        End If
    End With
End Sub

Post debugging

Dim lastRow As Long, foundRow As Variant
With ThisWorkbook.Worksheets("Sheet8")
    lastRow = .Cells(.Rows.Count, "B").End(xlUp).Row
    foundRow = Application.Match("BEST Cards Raised:", .Range("B1:B" & lastRow), 0)
    If IsError(foundRow) Then Exit Sub
    If lastRow >= foundRow Then .Rows(foundRow & ":" & lastRow).EntireRow.Delete
End With

Answer:

Try this (comments in code):

Sub DeleteRows()
    Dim ws As Worksheet, lastRow As Long, i As Long, j As Long
    Set ws = ThisWorkbook.Worksheets("Sheet1")

    lastRow = ws.Cells(ws.Rows.Count, 2).End(xlUp).Row
    'determine where to start deleting rows
    For i = 1 To lastRow
        If Trim(ws.Cells(i, 2).Value) = "BEST Cards Raised:" Then Exit For
    Next
    'delete all rows from last to found row, looping backwards
    For j = lastRow To i Step -1
        ws.Rows(j).Delete
    Next
End Sub