total beginner here. I have a hard time understanding the following code, or any code that operates the same variable.
Private Sub CommandButton1_Click() Dim i As Long For i = 1 To 3 i = i + 1 Next i MsgBox (i) End Sub
Why does this return 5?
You should note that typically it’s bad practise to alter a
For loop counter inside the loop.
Here’s what’s going on though:
As the loop runs,
Next i adds one to the value of
i (even though you already added one…) – if the value of
i is outside of the
For bounds then the loop terminates.
i enters the loop as 1, is incremented to 2, then again to 3 by the
i enters the loop as 3, is incremented to 4, then again to 5 by the
5 is outside of 1-3, so
i ends up as 5
i = i + 1 has the same effect that
Next i. You basically are adding 1 to i within the
for statement and once again when you increment it.
For i = 1 to 3 'starts with i = 1 i = i + 1 'adds 1 to i, i = 2 in the first loop Next i 'adds 1 to i, i = 3 at the end of the first loop. Thee second loop starts
i starts the secons loop with a value of 3 and you add 1 to it when
i = i + 1 and once again when
I hope this helps you understand it and sorry that my answer is a bit untidy, I’m answering from my mobile.
For loop re-written using a
i = 1 While i >= 1 And i <= 3 i = i + 1 i = i + 1 End While
Next i is directly translated as
i = i + 1 – so now for each iteration of the loop you are effectively performing
i = i + 2.
1 at the start it matches the loop condition so we add
i. It still matches the loop condition so we execute the loop again adding another
This means that
1 + 2 + 2 or