VBA For循环未退出

时间:2015-10-27 12:47:10

标签: excel vba excel-vba

如果不满足某些条件,我会遍历表的行并删除行。出于某种原因,即使完成,我的for循环也永远不会退出。我做错了什么?

lastr = Range("a2").End(xlDown).Row
For r = 2 To lastr
    If Cells(r, 1).Value <> "SHORT POSITIONS" And Cells(r, 7).Value = 0 And Cells(r, 10).Value <> "Yes" Then
        Rows(r).Delete
        r = r - 1
        lastr = lastr - 1
    End If
Next r

3 个答案:

答案 0 :(得分:3)

始终从底部开始,在删除行时朝顶部工作。无法从底部到顶部工作将导致跳过行,因为行删除后行的位置会重置。

永远不要在For ... Next Statement中重置您的计数器。改变r可以解决问题。更改lastr无效。当您进入循环时,它仍然会转到原始值lastr

lastr = Range("a" & ROWS.COUNT).End(xlUP).Row
For r = lastr To 2 STEP -1   '<~~ VERY IMPORTANT
    If Cells(r, 1).Value <> "SHORT POSITIONS" And Cells(r, 7).Value = 0 And Cells(r, 10).Value <> "Yes" Then
        Rows(r).Delete
    End If
Next r

通常,最好从下往上查找最后一个填充的单元格,

答案 1 :(得分:0)

如果你想循环并删除它最好先标记行并立即删除它们或使用数组。

lastr = Range("a2").End(xlDown).Row
dim DR() as long
dim c as long
For r = 2 To lastr
    If Cells(r, 1).Value <> "SHORT POSITIONS" And Cells(r, 7).Value = 0 And Cells(r, 10).Value <> "Yes" Then
        c = c +1
        redim preserve DR(c)
        dr(c-1) = R
    End If
Next r
'delete the rows one by one, or you could build a string and delete once.
For r = 0 to UBound(DR)
    Rows(dr(i).delete ' or entirerow delete 
next i

答案 2 :(得分:0)

你从循环变量中减去1,所以它永远循环。

在Visual Basic for循环中,“from”和“to”在开头计算一次(它们是固定的),但循环变量每次都增加。所以

For r = fromExp to toExp
  SomeCode()
End For

的行为与

相同
    Dim f = fromExp
    Dim t = toExp

    r = f

    While (r < t)
       SomeCode()
       r = r + 1
    End While

在您的示例中,代码更改为Exp

For r = fromExp to toExp
   toExp = toExp + 1
   r = r - 1
EndFor

不会影响循环

    Dim f = fromExp
    Dim t = toExp

    r = f

    While (r < t)
       toExp = toExp + 1   // does not affect the loop
       r = r - 1
       r = r + 1           // r is unchanged
    End While

循环变量没有变化,所以它永远循环。

最佳做法:不要更改For循环中的循环变量。

相关问题