Delete and insert rows with VBA

Remove cancelled orders, get rid of blank rows, add a gap before each department for printing: deleting and inserting rows is part of every clean-up macro. There is one trap nearly everyone falls into once. Here you see it, and the simple way around it.

In short: in a loop, always delete rows from the bottom up: For i = lastRow To 2 Step -1 with If … Then Rows(i).Delete inside. Going forwards skips rows, and no error tells you so.

What you need to know: For Next with Step, finding the last row and If Then Else.

Try it right now

The order list has lines with a quantity of 0, two of them right below each other. Delete them with a backward loop. Check tests with a longer list where three zeros follow one another.

Task The order list contains lines with a quantity of 0. The macro DeleteZeroRows should delete every row that has 0 in column C. Loop backwards from the last row up to row 2.

ABCD
1Item no.ItemQty
24711Lever arch file12
34712Copy paper0
44713Ballpoint pen0
54714Sticky notes30
64715Hole punch2
74716Stapler0
84717Highlighter25

Why backwards?

Excel closes the gap immediately: delete row 3, and row 4 moves into row 3, row 5 into row 4 and so on. A loop counting forwards knows nothing about that. Here is what this macro does with a list that has a cancelled order in row 3 and another in row 4:

For i = 2 To lastRow
    If Cells(i, 3).Value = "cancelled" Then
        Rows(i).Delete
    End If
Next i
iRow i holdsWhat happens
25101, shippednothing
35102, cancelledrow 3 is deleted, 5103 moves up into row 3
45104, opennothing. Order 5103 (cancelled) was never checked

After the run, 5103 is still on the list, and there is no error. That is what makes the bug dangerous: on lists without two matches in a row, you never notice it.

Going backwards, rows only ever move up from below i, and the loop has already dealt with those. The next check is row i - 1, which has not moved. That is why Step -1 is the standard when deleting.

For i = lastRow To 2 Step -1
    If Cells(i, 3).Value = "cancelled" Then
        Rows(i).Delete
    End If
Next i

Find the bug

This is the forward loop from above. Run it, look at which order is left over, and fix it.

Task Find the bug: the macro should delete every order with the status "cancelled". It runs without any error, but afterwards one cancelled order is still in the list. Run it, look at the result and fix it.

ABCD
1OrderCustomerStatus
25101Carter Bakeryshipped
35102Peters Motorscancelled
45103Green Dentalcancelled
55104Harris & Sonsopen
65105Lakeside Hotelshipped
75106Miller Printcancelled

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

Commands for deleting and inserting

CommandEffect
Rows(i).DeleteDeletes the whole row i; everything below moves up.
Cells(i, 3).EntireRow.DeleteThe same, starting from a cell. Handy when you already have a cell to work with.
Rows("5:7").DeleteDeletes rows 5 to 7 in one go.
Rows(i).InsertInserts an empty row above row i; row i and everything below moves down.
Cells(i, 1).EntireRow.InsertThe same, starting from a cell.
Range("C3").DeleteDeletes just that cell; the cells below it in that column move up. The rest of the row stays.

Inserting rows

The same rule applies when inserting, just the other way round: a new row pushes everything below it down. Going forwards, the loop then lands on the row it has just moved. Going backwards, it does not. A typical case is a blank row before each new group in a sorted list:

Task The list is sorted by department. For printing, each new department should start after an empty row. The macro InsertBlankRows inserts a whole row wherever the department in column A differs from the row above. No blank row goes above the first department (row 2).

ABCD
1DepartmentNameHours
2PurchasingEmma Clarke38
3PurchasingRavi Patel40
4WarehouseJake Turner35
5WarehouseOlivia Brown40
6WarehouseLiam Walsh20
7SalesMia Johnson39

This exercise is part of Premium.

Premium unlocks every exercise in every lesson, unlimited practice with fresh tasks and the final test with certificate.

See Premium Already Premium? Log in

The first exercise in this lesson is free.

The loop stops at 3, not 2. Each pass compares row i with row i - 1, and row 2 would be compared with the header.

In real Excel

On the sheet, Ctrl+- deletes a selected row; the macro does the same with Rows(i).Delete. Deleting by macro cannot be undone, so test on a copy first. On long lists every delete costs time, because Excel redraws the screen. How to switch that off is covered in With and ScreenUpdating.

If you are unsure what a loop does, step through it line by line with F8 and watch i in the Locals window. More on that in Debugging.

Common mistakes

Counting forwards

The macro runs, but a match directly below another match stays put. In the find-the-bug exercise, Check points out that A3 contains 5103 instead of 5104. The fix: For i = lastRow To 2 Step -1.

Deleting only the cell

Cells(i, 3).Delete does not delete the row, only that one cell. The quantities below slide up and end up next to the wrong items. For the whole row use Rows(i).Delete or Cells(i, 3).EntireRow.Delete.

Empty cells count as 0

To VBA, an empty cell equals 0 and equals "". So If Cells(i, 3).Value = 0 also deletes rows where the quantity is simply missing. If that should not happen, check that the cell is not empty as well: If Cells(i, 3).Value = 0 And Cells(i, 3).Value <> "" Then.

Inserting forwards

If the loop runs forwards while inserting, after the first new row it compares the blank row with the next department, inserts again, and so on until the loop ends. Instead of one blank row you get several in a row, and Check reports an empty cell where a department name belongs.

FAQ

Can I do it without a backward loop?

Yes, with Do While: after a delete, i stays where it is, because the next row is already at position i. Only when nothing was deleted do you add 1 to i. That is longer and easier to get wrong; the backward loop is the usual way.

Do I need to find lastRow again after deleting?

Not for the loop itself, which starts at the bottom and works its way up. If you need the new length of the list after the loop, for a total below it for example, find it again.

How do I delete duplicate rows?

Sort, then delete backwards every row that matches the row above, or in Excel use RemoveDuplicates directly. Both are in the next lesson, Sort and remove duplicates.

Can I insert several rows at once?

Yes: Rows("5:7").Insert inserts three empty rows above row 5. With variables: Rows(i & ":" & i + 2).Insert.

Learn this next: sort and remove duplicates

With Range.Sort you order a list by one or more columns, in one line of code instead of clicks in the menu.

Learn sorting

Write to us

Choose language

Select your preferred language