VBA Positive For loop, negative step

时间:2017-12-18 07:04:33

标签: excel vba excel-vba

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.

1 个答案:

答案 0 :(得分:7)

In <script> $(document).ready(function () { var typingTimer; //timer identifier var doneTypingInterval = 100; //time in ms (5 seconds) $("#myInput").on('keyup', function () { clearTimeout(typingTimer); if ($('#myInput').val()) { typingTimer = setTimeout(doneTyping, doneTypingInterval); } }); }); //user is "finished typing," do something function doneTyping() { var key = $('#myInput').val(); if (key.length >= 1) { $.ajax({ url: '/admin/search/?myInput='+key, type: 'GET', beforeSend: function () { $("#table").slideUp('fast'); }, success: function (data) { console.log(data); $("#table").append(data); $("#table").slideDown('fast'); } }); } } </script> (i.e. Test1), after the 3rd time through the loop, For a = 1 To 3 Step 1 is incremented to 4. As that is greater than 3, it stops and displays 4.

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

In a, For a = 1 To 1 Step 1 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 a, For a = 1 To 1 Step -1 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 a, For a = 1 To 2 Step 1 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 a, For a = 1 To 2 Step -1 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".