即使满足边界,VBA For循环也会继续运行

时间:2016-05-13 22:32:10

标签: excel vba excel-vba for-loop

所以我有一个像这样运行的代码:

maxRow = 5

For numRow=1 to maxRow

    If Range("A" & numRow).Value = 0 Then

        Rows(numRow).Select

        Selection.Delete Shift:=xlUp

        numRow = numRow - 1 

        maxRow = maxRow - 1 

    End If

Next numRow

我有

  

A1至A5 = 4 0 3 1 9(分别)

由于某种原因,循环仍在继续

任何人都请帮助我,所以我最终得到A1 = 4,A2 = 3,A3 = 1和A4 = 9没有连续循环。

2 个答案:

答案 0 :(得分:1)

有时候走向后

会更好

在:

enter image description here

代码:

Sub ytrewq()
maxRow = 5

For numRow = maxRow To 1 Step -1
    If Range("A" & numRow).Value = 0 Then
        Rows(numRow).Select
        Selection.Delete Shift:=xlUp
    End If
Next numRow
End Sub

之后:

enter image description here

<强> 注:

什么都没有减少 Select不是必需的:

Sub ytrewq()
maxRow = 5

For numRow = maxRow To 1 Step -1
    If Range("A" & numRow).Value = 0 Then
        Rows(numRow).Delete Shift:=xlUp
    End If
Next numRow
End Sub

也会起作用。

答案 1 :(得分:1)

原因是因为在For - Next循环中,您确定了第一次进入循环时的迭代次数,无论是否在循环期间,您都要更新其结束条件中涉及的变量。 / p>

如果你事先不知道在循环中运行语句的次数,就像在你的情况下一样,那么使用Do While - Loop循环:

Option Explicit

Sub main()
Dim maxRow As Long, numRow As Long

maxRow = 5
numRow = 1
Do While numRow <= maxRow

    If Range("A" & numRow).Value = 0 Then
        Rows(numRow).Delete Shift:=xlUp
        maxRow = maxRow - 1
    Else
        numRow = numRow + 1
    End If

Loop

End Sub