PDA

View Full Version : For Next lop ends on x +1



werafa
08-26-2021, 02:41 AM
Hi,

I've noticed that


Private Sub testloop()
Dim myrow As Long

For myrow = 1 To 10
Next myrow

Debug.Print myrow
End Sub

gives 11 as the output
Can anyone explain definitively why this is so? (I'd like to trust this enough to use it as a success/failure test)

thanks

~~~~

arnelgp
08-26-2021, 04:24 AM
the For..Next is analogous to

Do While myrow <= 10
Loop

it is incrementing loop (incrementint myrow on every Loop).
will only stop until myrow > 10.

werafa
08-26-2021, 04:26 AM
thanks arneglp

so ...
myrow = myrow +1
if myrow < 11 then do the loop again
loop

arnelgp
08-26-2021, 05:37 AM
mrow = 1
do until mrow > 10
mrow = mrow + 1
loop

Paul_Hossler
08-27-2021, 02:45 PM
gives 11 as the output
Can anyone explain definitively why this is so? (I'd like to trust this enough to use it as a success/failure test)


The For / Next loop terminates when i > 10

Since the Next increments the loop variable i, it's last value = 10 + 1 = 11 and it doesn't loop any more

What are you really trying to do that you want to make this a success/failure test?

jolivanes
08-27-2021, 09:45 PM
If you don't trust something or don't know if something is right or not, make a test run.
have an empty Sheet and run the code you're wondering about.



Sub What_Is_The_Outcome_A()
Dim i As Long
For i = 1 To 10
Cells(i, 3).Value = i
Next i
End Sub

Sub What_Is_The_Outcome_B()
Dim i As Long
i = 1
Do While i <= 10
Cells(i, 5).Value = i
i = i + 1
Loop
End Sub
That will give you a visual of the outcome.
Pretty soon it will be second nature.