I have a simple loop counter which I expected to msg me 1,2,3...10
. Instead I get 1,3,5,7,9
and I can't figure out where this extra increment is coming from. I'm a bit rusty after layoffs so bear with me if this seems simple.
here is my code:
Dim x As Integer
For x = 1 To 10
MsgBox x
x = x + 1
Next x
It is typical that a for
loop in most programming languages will automatically increment or iterate through something. In most languages, it's also common to provide a way to specify the increment amount. This is the case in VBA—see VBA For...Next documentation . For example:
For i = 1 to 20 Step 2
'do something
next i
Your code is incrementing x
, and For
is also incrementing x
. There are times when you want to increment the counter within the loop if some special condition is met, but not on every loop.
If you want to manually increment, then you should use a while
loop instead.
The Next x
line, when referring to an integer (x) in a For
loop, will increment x by 1
If you would like to increment by more than one, or increment in a negative direction you could use step
at the end of the For
line, which provides direction to the Next
portion. Example:
For x = 10 to 0 step -1
msgbox x
next x
will result in 11 consecutive msgbox's displaying:
10
9
8
7
6
5
4
3
2
1
0
Depending on how you would like to control X you have different options:
Option 1:
Let the for-loop control everything and use "step". In this case x will raise by y at each iteration. And you should not alter x within the loop.
Dim y As Integer
y = 1
For x = 1 To 10 step y
MsgBox x
Next x
Option 2:
If X depends on something happening within the loop and you don't want the for loop to alter x you could set step to 0.
For x = 1 To 10 step 0
MsgBox x
If x Mod 2 = 0 Then
x = x + 3
Else
x = x - 1
End If
Next x
Alternativ option
Having a for loop as in option 2 not altering the x would be bad practice. It is not wrong as the code is working just fine but a while loop would be a better solution.
Dim x As Integer
x = 1
Do While x < 10
MsgBox x
If x Mod 2 = 0 Then
x = x + 3
Else
x = x - 1
End If
Loop
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.