简体   繁体   English

VBA正面For循环,负面步骤

[英]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. 收益率为4,如预期。

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? 为什么踩到“外部”循环会导致1?

Why does VBA step out-of-bounds for Test1, but stop stepping when it goes out-of-bonuds for Test2? 为什么VBA步入Test1的界限,但是当它对于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 1 Step 1得到2,而For a = 1 To 1 Step -1得到0。

For a = 1 To 2 Step 1 results in 3, but For a = 1 To 2 Step -1 results in 1. For a = 1 To 2 Step 1得到3,但For a = 1 To 2 Step -1得到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. Test1 (即For a = 1 To 3 Step 1 ),在第3次循环之后, a增加到4.当它大于3时,它停止并显示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. Test2 (即For a = 1 To 3 Step -1 ), a初始设置为1.因为它已经小于3,所以它立即停止并显示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. For a = 1 To 1 Step 1a设置为1,其不大于1,因此循环继续,然后a递增到2.当2大于1时,它停止并显示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. For a = 1 To 1 Step -1a设置为1,不小于1,因此循环继续,然后a递减到0.当0小于1时,它停止并显示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. For a = 1 To 2 Step 1a设置为1,不大于2,因此循环继续,然后a递增到2,然后a递增到3.当3大于1时,它停止并显示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. For a = 1 To 2 Step -1a设置为1,小于2,因此循环停止并显示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 将“step”添加到循环计数器

This is all documented on the MSDN page re the "For...Next Statement" . 这些都记录在MSDN页面上的“For ... Next Statement”中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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