QP School

Full Version: Delete rows based on a condition
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Example:

Sub DeleteRowsBasedOnCondition()
    Dim ws As Worksheet
    Dim lastRow As Long
    Dim i As Long

    'Set the worksheet where the data is located
    Set ws = ThisWorkbook.Sheets("Sheet1")

    'Find the last row with data in column A
    lastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row

    'Loop through the rows in reverse order to avoid skipping rows after deletion
    For i = lastRow To 2 Step -1
        If ws.Cells(i, "A").Value < 10 Then
            ws.Rows(i).Delete
        End If
    Next i
End Sub

Explanation:

The code defines a subroutine named DeleteRowsBasedOnCondition.
It declares variables for the worksheet (ws), the last row with data in column A (lastRow), and a loop counter (i).
Set ws = ThisWorkbook.Sheets("Sheet1") specifies the worksheet ("Sheet1") where the data is located.
The lastRow variable is determined using ws.Cells(ws.Rows.Count, "A").End(xlUp).Row, which finds the last row with data in column A.
The For loop iterates through the rows in reverse order (from the last row to the second row) to avoid skipping rows after deletion.
The If statement checks the value in column A for each row. If the value is less than 10, the entire row is deleted using ws.Rows(i).Delete.