For...Next

RTHoward

New Member
Joined
Oct 14, 2002
Messages
5
I have the following table:

a b c d
-------
1|- - x -
2|- - - -
3|- - x -
4|- - - -

I want to write VBA that will delete those rows where the value in column c = "x". I need to write it so that the code will work on any table (using CurrentRegion or UsedRange).

I tried the following, but it didn't work properly; it skipped row 3.

Sub Delete_X()
Dim tbl As Object
Dim rw As Object
Dim DateRet

Worksheets("Sheet1").Range("a1").Activate
Set tbl = ActiveCell.CurrentRegion

For Each rw In tbl.Rows
DateRet = rw.Cells(1, 3).Value
If DateRet = "x" Then rw.Delete
Next

End Sub


Any help would be greatly appreciated.
 

Excel Facts

Excel Wisdom
Using a mouse in Excel is the work equivalent of wearing a lanyard when you first get to college
this problem somehow wasn't as simple as it first looked. I originally thought the problem was with the currentregion not doing what you wanted, but when I tried using a for each c in selection type loop, it skipped any lines immediately following another x.

the following isn't elegant but should work.

Sub del_x()

Dim LastCell As Range
Dim A As Integer
Dim noX As Integer

noX = 0

Cells.Find(What:="*", After:=Range("A1"), SearchDirection:=xlPrevious).Select

Set LastCell = ActiveCell

For A = 1 To LastCell.Row

If Cells(A - noX, 3).Value = "x" Then
Cells(A - noX, 3).EntireRow.Delete
noX = noX + 1
End If

Next

End Sub
 
Upvote 0
Instead of using regions and tables, have you considered the find command with column c? everytime you find an 'x' in column c, delete that row. Or if not column c, then some range of c like c1:c150 etc, etc.

something like:

set search = worksheets("sheet1").range("c:c").find ("x", lookin:=xlvalues)

if not search is nothing then
'your delete code here

etc, etc

end if
 
Upvote 0

Forum statistics

Threads
1,214,646
Messages
6,120,716
Members
448,985
Latest member
chocbudda

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
Back
Top