Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Delete rows based on a condition
#1
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.
Also follow me on Youtube for videos about video games:
https://www.youtube.com/channel/UCxfkGVU...2mQ/videos
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Sum values based on criteria Qomplainerz 0 235 07-27-2023, 11:20 AM
Last Post: Qomplainerz
  Create a pivot table based on data in a worksheet with VBA Qomplainerz 0 261 07-27-2023, 09:48 AM
Last Post: Qomplainerz
  Change cell colors based on values with VBA Qomplainerz 0 206 07-27-2023, 08:19 AM
Last Post: Qomplainerz
  Count the number of rows in a worksheet with VBA Qomplainerz 0 225 07-27-2023, 07:50 AM
Last Post: Qomplainerz

Forum Jump:


Users browsing this thread: 2 Guest(s)