VBA For 循环不退出

问题描述 投票:0回答:4

我正在循环遍历表的行并在不满足某些条件时删除行。由于某种原因,我的 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
vba excel
4个回答
3
投票

删除行时始终从底部开始并向顶部努力。无法从下到上工作将导致跳过行,因为行删除后行的位置会重置。

切勿在“对于...下一个声明”中重置计数器。改变 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

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


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



0
投票

在 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 循环中的循环变量。


0
投票

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

	
© www.soinside.com 2019 - 2024. All rights reserved.