Excel vba循环内循环更改循环variables

比方说,我有一个类似于这样的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? 

我在循环中增加一个aRowvariables。 这会导致variables增加两倍吗?

如果你将debugging你的代码,你可以看到自己的价值。 下面的代码导致

 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 

输出为

在这里输入图像说明

这里, aRow = aRow + 1aRow的值递增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 

正如你可以看到的输出,当我是5它被迫6,然后下一个循环是7。

在这里输入图像说明

你会得到一个一次性的碰撞:

 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 

在这里输入图像说明