Excel VBA删除for循环中的行未命中行
我有一个子程序,删除包含大约1000行的范围内的行。 行在critera上被删除。 下面的代码工作。
但是,当我运行macros时,通常必须运行4次,才能删除包含删除条件的所有行。
我猜这是因为for循环在删除一行时突然消失的时候会错过它的索引。
我的第一个代码看起来像这样。
Set StatusRange = Range("B2", Range("B2").End(xlDown)) For Each StatusCell In StatusRange If StatusCell = "FG" Then StatusCell.EntireRow.Delete ElseIf StatusCell = "QC" Then StatusCell.EntireRow.Delete ElseIf StatusCell = "CS" Then StatusCell.EntireRow.Delete Else End If Next StatusCell
当我尝试更新范围每个循环,它仍然无法正常工作。
Set StatusRange = Range("B2", Range("B2").End(xlDown)) For Each StatusCell In StatusRange If StatusCell = "FG" Then StatusCell.EntireRow.Delete ElseIf StatusCell = "QC" Then StatusCell.EntireRow.Delete ElseIf StatusCell = "CS" Then StatusCell.EntireRow.Delete Else End If Set StatusRange = Range("B2", Range("B2").End(xlDown)) Next StatusCell
有没有人知道这个问题? 谢谢。
从下往上工作。 如果删除一行,则所有内容都将向上移动,并在下一次迭代中跳过该行。
下面是代码的“胆量”从底部开始。
With Worksheets("Sheet1") For rw = .Cells(.Rows.Count, "B").End(xlUp).Row To 2 Step -1 Select Case UCase(.Cells(rw, "B").Value2) Case "FG", "QC", "CS" .Rows(rw).EntireRow.Delete End Select Next rw End With
由于For Each
没有反向循环,所以需要使用稍微不同的方法。
此外,您的代码与多个If
和OR
是“尖叫使用Select Case
。
Dim StatusRange As Range Dim i As Long Set StatusRange = Range("B2", Range("B2").End(xlDown)) ' loop backward when deleting Ranges, Rows, Cells For i = StatusRange.Rows.Count To 1 Step -1 Select Case StatusRange(i, 1).Value Case "FG", "QC", "CS" StatusRange(i, 1).EntireRow.Delete Case Else ' for the future if you need it End Select Next i