0

I am using following VBA to delete all the rows that does not have * in Column T. It works but it only deletes 1 row at a time. I have to run the vba 25 times in order to delete 25 rows that does not have * in the column T. Do you see anything wrong with the code?

Sub DeleteCells()

    'Loop through cells A1:A10 and delete cells that contain an "x."
    For Each c In Range("t1:t35")
        If c <> "*" Then c.EntireRow.Delete
    Next

End Sub
3

1 Answer 1

4

To delete rows you should work from the bottom up rather than the top down:

Sub DeleteCells()
Dim i As Long

For i = 35 To 1 Step -1
    If Range("T" & i).Value <> "*" Then Range("T" & i).EntireRow.delete
Next i

End Sub

A more efficient way would be to use the autofilter and avoid looping all together. Something like:

Sub DeleteCellsFilter()
    Sheet1.Range("$T$1:$T$35").AutoFilter Field:=1, Criteria1:="<>*"
    Sheet1.UsedRange.Offset(1, 0).SpecialCells(xlCellTypeVisible).EntireRow.delete
    Sheet1.UsedRange.AutoFilter
End Sub

This makes a couple assumptions that you should correct:

1) We're interacting w/ Sheet1 2) Your range is static (rows 1 to 35).

You should adjust these assumptions as appropriate.

Sign up to request clarification or add additional context in comments.

3 Comments

Works. Except I changed Range("T" & i).Value <> "*"
@torres great Glad it worked out for you. Feel free to try the Filter method, as it's a lot more efficient. Either way, if you think it's a good solid answer, please mark it as "accepted". Good luck with the rest of your project!
+ 1 For Auto Filter :)

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.