For Loop Gotcha

From a recent email from a collegue. It seems that For loops only evaluate the conditions once, when the loop is entered:

Hi all,

I have just encountered an ‘interesting’ property of for loops.

It appears that they hard-code the number that they loop through until, and there doesn’t seem to be any way to affect this number.

I.e. If you have a rowset and are looping through it via a for loop - &I = 1 to &rowset.activerowcount, and you add a row to the rowset, the for loop will only go through the original number of rows – the added row will not be part of the &rowset.activerowcount of the loop. (If there were originally 10 rows in the rowset, and I add another 5 rows to the rowset as part of the for loop, &I will only ever get to 10 – not 15).


If you wish to loop through a rowset (or any variable number loops) you should use a while or a repeat loop, as the conditions are re-evaluated each time the loop comes to the conditional part (the top of the while statement, and the until of the repeat statement).


Hope that helps people.

0 comments: