Alice
Alice

Reputation: 13

'Exit For' is not working

Doing a reverse for loop in Excel VBA, looking for the last populated cell in a certain column. Once found, it should exit the loop, but Exit For is not working, and continues looping all the way back. Any ideas?

    rewind:
'            so we 're still "under", rollback to the right line
            While Not Range("I" & a).Value = getsum
                a = a - 1
                On Error GoTo TryCatch
                If Not Range("E" & a).Value = "" Then
                    Rows(a).Select
                    currfield = Range("E" & a).Value
                    runningstrsum = runningstrsum - currentstrsum 'we're switching streets
'                    and since we just lost currentstrsum, we have to reset it to the last one, yay
                    For c = a - 1 To 2 Step -1
                        If Not Range("E" & c).Value = "" Then 'there it is
                            currentstrsum = Range("E" & c).Value
                            Exit For
                        End If
                    Next c
                End If
            Wend
            If overunder < 0 Then 'go back to overunder<
                GoTo goodjobunder
            ElseIf overunder = 0 Then
                GoTo goodjobeven
            End If

Upvotes: 0

Views: 1231

Answers (1)

SierraOscar
SierraOscar

Reputation: 17647

You're only exiting the inner loop, the code will resume outside of this loop - which is still inside the While loop and therefore re-enter the For loop.

If you want to find the last populated cell in a column just use something like:

Dim lastCell As Excel.Range
Set lastCell = Range("E" & Rows.Count).End(xlUp)

No need to loop.

Might also be a good time to look at Debugging VBA Code

Upvotes: 5

Related Questions