View Full Version : [SOLVED:] VBA loop formula explanation?
torquil
01-10-2020, 08:36 AM
Hi guys, I am a beginner in VAB and just doing some online training when i come up against this questions:
What value will "x" have when this loop completes:
x=0
a=0
while a<10
x=x+a
a=a+1
wend
The online test gives me the corrected answer of 45......... but i cannot work out why this is correct.
Please explain to this vba kindergarten newbie.
YasserKhalil
01-10-2020, 08:53 AM
Using While a<10 means the loop statements will be executed only if the variable a is less than 10
When the code starts a = 0 so the statements will go on and x=x+a >> x=0+0 >> x=0 ||| a=a+1 >> a=0+1 >> a=1
In the next loop the variable x will be x=x+a >> x=0+1 >> x=1 ||| a=a+1 >> a=1+1 >> a=2
In the next loop the variable x will be x=x+a >> x=1+2 >> x=3 ||| a=a+1 >> a=2+1 >> a=3
In the next loop the variable x will be x=x+a >> x=3+3 >> x=6 ||| a=a+1 >> a=3+1 >> a=4
And so on..
It is easier to use Debug.Print so as to display the result of the variable x in the immediate window (Press Ctrl + G to display this window)
Sub Test()
Dim a As Integer, x As Integer
a = 0
x = 0
While a < 10
x = x + a
Debug.Print a, x
a = a + 1
Wend
End Sub
The immediate window will be like that
25781
Powered by vBulletin® Version 4.2.5 Copyright © 2025 vBulletin Solutions Inc. All rights reserved.