VBA to delete rows when values meet certain criteria?

thommo41

Board Regular
Joined
Nov 10, 2006
Messages
142
Hi,

I have a list of data that contains some rows that I dont want. These rows aren't necessarily in order.
Basically, where the value in column A of that row is LESS THAN 3 characters long, I want to delete the row.
I have done the following routine that does this, but as it deletes a row, it doesn't check the immediate row below, as the loop doesn't take into account the deleted row (does that make sense?)

Code:
Sub delrow()
alan = Sheets("Sheet1").UsedRange.Rows.Count
For Row = 2 To alan
    If Len(Range("A" & Row).Value) < 3 Then
    Rows(Row).Delete Shift:=xlUp
    End If
Next
End Sub

I either need a simple fix to make this simple loop take into account when it deletes a row, the next row is infact the one it is looped on, or I need a better way of deleting all rows in a range where the Cell range("A" & row#) is less than 3 characters.

A solution for the loop taking into account the deleted row(s) would be nice anyway, and if some better code is mentioned also, that would be a bonus :wink:

Thanks in advance
Alan
 

Excel Facts

Return population for a City
If you have a list of cities in A2:A100, use Data, Geography. Then =A2.Population and copy down.

Domski

Well-known Member
Joined
Jan 18, 2005
Messages
7,292
Hi,

You should run the delete code from the bottom up like this:

Code:
Sub delrow() 
alan = Sheets("Sheet1").UsedRange.Rows.Count 
For Row = alan To 2 Step -1
    If Len(Range("A" & Row).Value) < 3 Then 
    Rows(Row).Delete Shift:=xlUp 
    End If 
Next 
End Sub

Hope it helps.

Dom
 
Upvote 0

Forum statistics

Threads
1,191,703
Messages
5,988,179
Members
440,136
Latest member
dandanfielding

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Top