View Single Post
 
Old 07-16-2014, 05:00 AM
BobBridges's Avatar
BobBridges BobBridges is offline Windows 7 64bit Office 2010 32bit
Expert
 
Join Date: May 2013
Location: USA
Posts: 700
BobBridges has a spectacular aura aboutBobBridges has a spectacular aura about
Default

The reason I did the second loop backward is easy to miss at first. Consider what happens if we do the loop the normal way, like this:
Code:
For jr = 1 to 6
  If ows.Cells(jr, 7).Value = "Phase" then ows.Rows(jr).Delete
  Next jr
Let's say that rows 2, 3 and 5 are "Phase" records. So let's trace what the program does:

1) jr is set to 1
2) Checks G1; it's not "Phase", so it skips to the next record
3) jr is now 2
4) Checks G2; it's equal to "Phase", so it deletes row 2.
5) jr is now 3.
6) Checks G3...

But wait! We just deleted row 2; so what was row 3 a moment ago is row 2 now, and row 4 is now row 3, and so on. So when I check row 3 (because jr is now 3), I skipped a row. G3—what was originally G3 but is now G2—has "Phase", but the above logic never looks at it.

There's more than one way to get around that. My way is usually to run the loop backward, like this:
Code:
For jr = 6 to 1 Step -1
  If ows.Cells(jr, 7).Value = "Phase" then ows.Rows(jr).Delete
  Next jr
Another way is to back up jr every time you do a delete:
Code:
For jr = 1 to 6
  If ows.Cells(jr, 7).Value = "Phase" Then
    ows.Rows(jr).Delete
    jr = jr - 1
    End If
  Next jr
That works because the For...Next construction doesn't keep track of what jr was last time; it just adds 1 to jr and then checks, before going into the loop, to be sure it hasn't passed 6.

And the fact that I had to do the loop backward is why I had to have two loops in the first place. Until I noticed the above problem, I had a nice simple bit of logic with one loop, doing everything in one pass. Oh, well.
Reply With Quote