Why is simple loop macro stopping

nicolewh

Well-known Member
Joined
Aug 7, 2009
Messages
554
I have a macro that stops when it encounters the first cell which meets the condition of the if then statement. Why?

Code:
Sub Macro1()
Dim Rng As Range
Dim MyRow As Range
Set Rng = Range("Table1[[column1]]")
For Each MyRow In Rng
    Ctw = UBound(Split(MyRow.Value, " ")) + 1
           If Ctw < 3 Then   
                   MyRow.EntireRow.Delete         
           End If
    Next MyRow
End Sub
Thanks!

Nicole
 

Some videos you may like

Excel Facts

What do {} around a formula in the formula bar mean?
{Formula} means the formula was entered using Ctrl+Shift+Enter signifying an old-style array formula.

mikerickson

MrExcel MVP
Joined
Jan 15, 2007
Messages
23,768
I'm not sure that it would stop at the first cell that it finds, but I am sure that it will not work properly.

As you loop through Rng, you are going from top to bottom. When you delete a row, you are moving the un-examined cells below and the next loop skips the row that moved into the vacated space.

To see what I mean, run this code
Code:
Dim aCell as Range
For each aCell in Range("A1:A10")
    MsgBox aCell.Address
    aCell.EntireRow.Delete
Next aCell
you will see only 5 message boxes. And there will be cells that are not deleted.


The fix is to work from bottom to top.
Code:
Sub Macro1()
    Dim Rng As Range
    Dim MyRow As Range
    Dim i As Long

    Set Rng = Range("Table1[[column1]]")

    For I = Rng.Rows.Count To 1 Step-1 
        Set myRow = Rng.Cells(i, 1)
        Ctw = UBound(Split(MyRow.Value, " ")) + 1
        If Ctw < 3 Then   
            MyRow.EntireRow.Delete         
        End If
    Next MyRow
End Sub
 

Subscribe on YouTube

Watch MrExcel Video

Forum statistics

Threads
1,106,052
Messages
5,509,046
Members
408,701
Latest member
daz457

This Week's Hot Topics

  • Turn fraction around
    Hello I need to turn a fraction around, for example I have 1/3 but I need to present as 3/1
  • TIme Clock record reformatting to ???
    Hello All, I'd like some help formatting this (Tbl-A)(Loaded via Power Query) [ATTACH type="full" width="511px" alt="PQdata.png"]22252[/ATTACH]...
  • TextBox Match
    hi, I am having a few issues with my code below, what I need it to do is when they enter a value in textbox8 (QTY) either 1,2 or 3 the 3 textboxes...
  • Using Large function based on Multiple Criteria
    Hello, I can't seem to get a Large formula to work based on two criteria's. I can easily get a oldest value based one value, but I'm struggling...
  • Can you check my code please
    Hi, Im going round in circles with a Compil Error End With Without With Here is the code [CODE=rich] Private Sub...
  • Combining 2 pivot tables into 1 chart
    Hello everyone, My question sounds simple but I do not know the answer. I have 2 pivot tables and 2 charts that go with this. However I want to...
Top