Excel vba for循环中循环变量循环变量

时间:2017-07-11 13:11:48

标签: excel vba excel-vba

假设我有类似于此的For循环:

Sub forLoop()
Dim firstRow As Integer
Dim lastRow As Integer
Dim aRow As Integer
firstRow=5
lastRow=200
For aRow = firstRow to lastRow
   If (something) Then  //lets say it happened when aRow = 18
       aRow=aRow+1  //=> aRow=19 
       ...
   End If
Next aRow  //which one ? will next aRow be 19 or 20?

我在循环中增加一个aRow变量。它会导致变量增加两倍吗?

3 个答案:

答案 0 :(得分:2)

如果您要调试代码,您可以自己查看该值。下面的代码结果为

Sub Demo()
    Dim firstRow As Integer
    Dim lastRow As Integer
    Dim aRow As Integer
    firstRow = 5
    lastRow = 200
    For aRow = firstRow To lastRow
        If aRow = 7 Then
            aRow = aRow + 1
        End If
        Debug.Print aRow
    Next aRow
End Sub

输出为

enter image description here

此处,aRow = aRow + 1aRow的值增加1,然后在循环中反映出来。

答案 1 :(得分:1)

是的,确实如此。

运行这个简单的脚本:

Sub forLoop()
Dim i As Long
For i = 1 To 100
    If i Mod 5 = 0 Then
        i = i + 1
    End If

Debug.Print i
Next i
End Sub

正如您在输出中看到的那样,当i为5时,它被强制为6,然后下一个循环为7。

Smalltalk

答案 2 :(得分:1)

你会得到一次性的冲击:

Sub forLoop()
    Dim firstRow As Integer
    Dim lastRow As Integer
    Dim aRow As Integer
    Dim i As Long

    firstRow = 5
    lastRow = 200
    i = 1

    For aRow = firstRow To lastRow
       If (aRow = 18) Then
           aRow = aRow + 1
       End If
       Cells(i, "A") = aRow
       i = i + 1
    Next aRow
End Sub

enter image description here

相关问题