loop count

  • Thread starter Thread starter Roger
  • Start date Start date
R

Roger

Why does this return 4 after the loop and three at the end of the loop(as
expected)

For i = 1 To 3
debug.print i
Next
debug.print i'should be 3?
 
Roger,

The way For loops work is that the control variable, i in this
case, is incremented at the Next statement and then tested at the
For statement. After the third iteration of the loop, i is
incremented to 4, compared to the upper limit of the For
statement (3, in this case), and then execution transfers to the
instruction following the Next statement.

The variable is correctly 4 after the loop ends.


--
Cordially,
Chip Pearson
Microsoft MVP - Excel
Pearson Software Consulting, LLC
www.cpearson.com
 
Roger,

The loop counter will always be beyond the loop bounds upon exit, unless the
loop is terminated within the loop due to some other condition.

i is incremented in every iteration of the loop, and checked at the start to
see if it is within bounds. So, it increments 3 times, which gets i to 4,
which is greater than its max value of 3, so it exits.

--

HTH

Bob Phillips
... looking out across Poole Harbour to the Purbecks
(remove nothere from the email address if mailing direct)
 
Back
Top