VBA For循环不退出

如果某些条件不符合,我正在循环查看表的行并删除行。 出于某种原因,我的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 

总是从底部开始,在删除行时向顶部工作。 如果从底部到顶部工作失败,则会导致行被跳过,因为在删除行之后行的位置被重置。

切勿在For … Next声明中重置您的计数器。 改变r把事情搞砸了。 更改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 

通常情况下,最好从下往上看最后一个填充的细胞,

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

 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 

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

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

 For r = fromExp to toExp SomeCode() End For 

performance相同

  Dim f = fromExp Dim t = toExp r = f While (r < t) SomeCode() r = r + 1 End While 

在你的例子中,代码变成了toExp

 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 

循环variables不变,所以它永远循环。

最佳实践: 不要在For循环中更改循环variables。