2017-10-04 81 views
0

我有以下代碼來搜索日期列表並刪除任何與兩年前的日期相關的行。當我跑步時,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的不同迭代,並且在線代碼看起來幾乎完全相同。我找不到我做錯了什麼。

+6

當刪除行建議向後運行循環即'對於i = 100:1個的步驟-1'您的問題作爲你造成的通過將DataRange設置爲整個列將其置於無限循環中 – Tom

+0

好的,這很好理解。我不熟悉,但現在我會查找它。感謝您的答覆! @湯姆 – Kim

回答

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