Home » excel » excel – How does a variable refer to the same variable in vba?

excel – How does a variable refer to the same variable in vba?

Posted by: admin May 14, 2020 Leave a comment

Questions:

total beginner here. I have a hard time understanding the following code, or any code that operates the same variable.

For example:

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?

How to&Answers:

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.

So:

Iteration 1: i enters the loop as 1, is incremented to 2, then again to 3 by the Next i

Iteration 2: i enters the loop as 3, is incremented to 4, then again to 5 by the Next i

5 is outside of 1-3, so i ends up as 5

Answer:

Saying 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 Next i

I hope this helps you understand it and sorry that my answer is a bit untidy, I’m answering from my mobile.

Answer:

Here’s your For loop re-written using a While loop:

i = 1
While i >= 1 And i <= 3
    i = i + 1
    i = i + 1
End While

Note that Next i is directly translated as i = i + 1 – so now for each iteration of the loop you are effectively performing i = i + 2.

Since i is 1 at the start it matches the loop condition so we add 2 to i. It still matches the loop condition so we execute the loop again adding another 2.

This means that i is 1 + 2 + 2 or 5.