07-27-2023, 09:47 AM
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.
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
https://www.youtube.com/channel/UCxfkGVU...2mQ/videos