对于Next Loop Freezing

时间:2017-10-04 18:26:24

标签: excel vba excel-vba

我有以下代码来搜索日期列表并删除与两年前的日期相关联的所有行。当我跑步时,excel冻结。我是VBA的新手,并且认为我可能对使用这个特定的循环有一个概念上的误解:

Sub DeletePriorDates()
'Delete any dates before two years past
    Dim twoyrpast As Date
    Dim c As Range
    Dim DataRange As Range
    Set DataRange = Sheet6.Range("A:A")
    twoyrpast = DateAdd("yyyy", -2, Sheet1.[B].Value)

    For Each c In DataRange
        If c < twoyrpast Then c.EntireRow.Delete
    Next

End Sub

当我停止运行宏时,调试器会突出显示“下一步”。我尝试过Next的不同迭代,在线代码看起来几乎完全相同。我找不到我做错了什么。

1 个答案:

答案 0 :(得分:5)

继上面我的评论之后,给它一个去吧

Public Sub DeletePriorDates()
'Delete any dates before two years past
    Dim twoyrpast As Date
    Dim i As Long

    With Sheet6
        twoyrpast = DateAdd("yyyy", -2, Sheet1.[B].Value)

        For i = .Cells(.Rows.Count, "A").End(xlUp).Row To 1 Step -1
            If .Cells(i, 1) < twoyrpast Then .Rows(i).EntireRow.Delete
        Next i
    End With
End Sub