Exiting a Loop Early After a Condition Is

There are times where you don't need to execute the whole loop. Perhaps you simply need to read through the dataset until you find one record that meets a certain criteria. In this case, you would want to find the first record and then stop the loop. There is a statement called Exit For that does this.

The following sample macro looks for a row in the dataset where service revenue in Column F is positive and product revenue in Column E is 0. If such a row is found, you might indicate a message that the file needs manual processing today and move the cell pointer to that row:

' Are there any special processing situations in the data? FinalRow = Cells(65536, 1).end(xlup).row ProblemFound = False For I = 2 to FinalRow

If cells(I, 5).value = 0 then Cells(I, 6).Select ProblemFound = True Exit For End if End if Next I

If ProblemFound then

MsgBox "There is a problem at row " & I Exit Sub End if

0 0

Post a comment