2

In column D, I am trying to delete every row that has a value in it. If the cell is blank, it is not deleted

The For loop only looks at D2 and deletes the entire row because it has a value in it. The loop then stops, and does not continue. The NumRows value is 9324 because there are that many rows in column A.

I'm stuck and cannot figure out how to get the loop to continue. Thanks!

Dim VarDeleteLoop as long
Dim NumRows As Long


NumRows = Worksheets("Sheet").Cells(Application.Rows.Count, "A").End(xlUp).Row


For VarDeleteLoop = 2 To NumRows

        Cells(VarDeleteLoop, 4).Select

        If Cells(VarDeleteLoop, 4).Value = "" Then
                Cells(VarDeleteLoop, 4).Select
        Else
                Cells(VarDeleteLoop, 4).Select
                Selection.EntireRow.Delete
        End If

Next VarDeleteLoop
2
  • When the loop stops, do you get an error message? If so, what is it? Also, you should change Application.Rows.Count to Worksheets("Sheet").Rows.Count Commented May 31, 2018 at 21:33
  • I actually don't get any error. It just deletes the rows and ends. Commented May 31, 2018 at 21:40

2 Answers 2

4

When removing things, it is often a better idea to do it backwards. That way you don't need to keep track of the number of the next line, if the previous one was deleted.

Do your for loop like this instead:

For VarDeleteLoop = NumRows To 2 Step -1
Sign up to request clarification or add additional context in comments.

1 Comment

That worked! I'm new to VBA, only just started working in it about 2 weeks ago, so still have a lot of learning to do. Thanks for your help!
1

.AutoFilter can quickly isolate non-blank cells and identify them for deletion.

With Worksheets("sheet").Columns("D").Cells
    If .Parent.AutoFilterMode Then .Parent.AutoFilterMode = False
    .AutoFilter field:=1, Criteria1:="<>"
    With .Resize(.Rows.Count - 1, .Columns.Count).Offset(1, 0)
        If CBool(Application.Subtotal(103, .Cells)) Then
            .SpecialCells(xlCellTypeVisible).EntireRow.Delete
        End If
    End With
    .Parent.AutoFilterMode = False
End With

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.