VBA循环和删除问题

时间:2017-08-09 08:26:38

标签: excel-vba loops vba excel

我创建了一些编码,用于循环数据集并根据所需条件删除行。我需要帮助,因为它删除了第一个找到的匹配条件,但没有遍历其余的数据。我错过了什么?非常感谢

Sub RemoveFivePoundException()

Dim I As Integer
Dim LR As Long

Application.ScreenUpdating = False


Sheets("Claims").Select
LR = Cells(Rows.Count, "A").End(xlUp).row
Range("a1").Select

 For I = 3 To LR
    If Cells(I, 6).Value > 5# And Cells(I, 7) = "Under £5 write off" Then
       Cells(I, 1).EntireRow.Delete
    End If

  Next I

 Application.ScreenUpdating = True

 End Sub

1 个答案:

答案 0 :(得分:0)

删除行时,应该反转循环。删除每一行后,下一行的索引都已更改。

将你的循环改为:

For I = LR To 3 step -1 'Invert loop!
    If Cells(I, 6).Value > 5# And Cells(I, 7) = "Under £5 write off" Then
       Cells(I, 1).EntireRow.Delete
    End If
Next I

或者,您可以这样做:

For I = 3 To LR
    If Cells(I, 6).Value > 5# And Cells(I, 7) = "Under £5 write off" Then
        Cells(I, 1).EntireRow.Delete
        I = I - 1 'To avoid skipping rows.
    End If
Next I

根据下面的评论,这第二个选项有效,但这是不好的做法。