Excel vba用于在循环内更改循环变量
假设我有一个类似如下的For循环:Excel vba用于在循环内更改循环变量,vba,excel,Vba,Excel,假设我有一个类似如下的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
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变量。这会导致该变量增加两倍吗?如果您要调试代码,您可以自己查看该值。下面的代码导致
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+1
将aRow
的值增加1
,并随后反映在循环中 如果要调试代码,您可以自己查看值。下面的代码导致
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+1
将aRow
的值增加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
是的,是的
运行以下简单脚本:
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
您将获得一次性通气:
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
您将获得一次性通气:
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