VBA Positive For cycle, negative step

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

Revenues 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 a step outside the loop result in 1?

Why does VBA go beyond Test1 but stop taking a step when it leaves because of bonuses for Test2?

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

For a = 1 To 2 Step 1 leads to 3, but For a = 1 To 2 Step -1 leads to 1.

+5
source share
1 answer

In Test1 (i.e., For a = 1 To 3 Step 1 ), after the third time through the loop, a increases by 4. Since this is more than 3, it stops and displays 4.

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

In For a = 1 To 1 Step 1 , a set to 1, which is not more than 1, so the cycle continues, and then a increases by 2. When 2 is greater than 1, it stops and displays 2.

In For a = 1 To 1 Step -1 , a set to 1, which is not less than 1, so the loop continues, and then a decreases to 0. Since the value 0 is less than 1, it stops and displays 0.

In For a = 1 To 2 Step 1 , a set to 1, which is not more than 2, so the cycle continues, and then a increases by 2, and then a increases by 3. Since 3 is greater than 1, it stops and displays 3.

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


The actual process in these cycles:

  • Initialize the loop counter to the "start value"

  • Complete the following steps:

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

    • Executing statements in a loop

    • Add a "step" to the loop counter

All of this is documented on the MSDN re "For ... Next Statement" page.

+6
source

Source: https://habr.com/ru/post/1274141/


All Articles