How To Delete Rows In Excel Vba

To delete rows in Excel VBA, you can use the “Delete” method of the “Range” object. Here is an example of how it can be done:

Sub DeleteRows()
    Dim ws As Worksheet
    Set ws = ThisWorkbook.Worksheets("Sheet1") ' Change "Sheet1" to the name of your worksheet
    
    Dim lastRow As Long
    lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row ' Get the last row number in column A
    
    Dim i As Long
    For i = lastRow To 1 Step -1 ' Loop through each row from bottom to top
        If ws.Cells(i, 1).Value = "Delete" Then ' Change "Delete" to the criteria for deleting rows
            ws.Rows(i).Delete ' Delete the row
        End If
    Next i
End Sub

Let’s go through the code:
– First, we define a variable `ws` to represent the worksheet that contains the data. Make sure to change the worksheet name to match yours.
– Next, we find the last row with data in column A using the `End` and `xlUp` properties.
– We set up a loop to iterate through each row from the last row to the first row in the worksheet.
– Inside the loop, we check if the value in column A of the current row matches the criteria for deleting rows. You can modify this condition as needed.
– If the condition is met, we use the `Delete` method to delete the entire row.
– Finally, we move to the next row in the loop and repeat the process.

Note that when deleting rows in a loop, it’s important to start from the last row and move upwards. Otherwise, deleting rows from the top down can cause the row numbers to shift and result in skipped rows.

Hope this explanation helps! Let me know if you have any further questions.

Same cateogry post

Leave a comment