简体   繁体   中英

VBA Positive For loop, negative step

Sub Test1()
    Dim a As Integer
    For a = 1 To 3 Step 1 'STEP POSITIVE ONE
    Next
    Debug.Print a
End Sub

Yields 4, as expected.

Sub Test2()
    Dim a As Integer
    For a = 1 To 3 Step -1 'STEP NEGATIVE ONE
    Next
    Debug.Print a
End Sub

Why does stepping "outside" the loop result in 1?

Why does VBA step out-of-bounds for Test1, but stop stepping when it goes out-of-bonuds for Test2?

EDIT: In addition to the above, running For a = 1 To 1 Step 1 results in 2, and For a = 1 To 1 Step -1 results in 0.

For a = 1 To 2 Step 1 results in 3, but For a = 1 To 2 Step -1 results in 1.

In Test1 (ie For a = 1 To 3 Step 1 ), after the 3rd time through the loop, a is incremented to 4. As that is greater than 3, it stops and displays 4.

In Test2 (ie For a = 1 To 3 Step -1 ), a is initially set to 1. As that is already less than 3, it immediately stops and displays 1.

In For a = 1 To 1 Step 1 , a is set to 1, which is not greater than 1, so the loop proceeds and then a is incremented to 2. As 2 is greater than 1, it stops and displays 2.

In For a = 1 To 1 Step -1 , a is set to 1, which is not less than 1, so the loop proceeds and then a is decremented to 0. As 0 is less than 1, it stops and displays 0.

In For a = 1 To 2 Step 1 , a is set to 1, which is not greater than 2, so the loop proceeds and then a is incremented to 2, and then a is incremented to 3. As 3 is greater than 1, it stops and displays 3.

In For a = 1 To 2 Step -1 , a is set to 1, which is less than 2, so the loop stops and displays 1.


The actual process in these loops is:

  • Initialise the loop counter to the "start value"

  • Loop over the following steps:

    • Determine whether the loop counter is greater than the "end value" (if "step" is positive or zero) or less than the "end value" (if "step" is negative) and, if so, exit the loop

    • Perform statements within the loop

    • Add "step" to the loop counter

This is all documented on the MSDN page re the "For...Next Statement" .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM