简体   繁体   中英

VBA Trying to loop through a column and delete the entire row if they contain a value

I'm not very good at loops.

I'm trying to use VBA to loop through a column to look for any value, and then delete the entire row if it doesn't find anything (It's essentially a way of deleting rows of data that I've marked (or unmarked in this case)).

I've tried various things. My most recent attempt is below but its just deleting every row regardless of whether that cell has a value or not. Any suggestions?

Dim i as Long
For i = 1 To 50
If Cells(i, 1).Value = "" Then
    Selection.EntireRow.Delete
Else
    i = i + 1
End If
Next i
End Sub

There are several issues here:

  1. When deleting rows in a loop work backwards, if going forward your row number changes as you delete.

  2. There is no need to increment variable "i" next i already does this

  3. Use the Worksheet object to delete the row rather than Selection

I would rewrite like this:

Sub delete()

Dim i As Long
For i = 50 To 1 Step -1
    If Cells(i, 1).Value = "" Then
        Worksheets("Sheet1").Rows(i).EntireRow.delete
    End If
Next i

End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM