简体   繁体   中英

For Next Loop Freezing

I have the following code to search a list of dates and delete any rows associated with a date prior to two years ago. When I run, excel freezes. I'm new to VBA, and think I'm probably having a conceptual misunderstanding regarding using this particular loop:

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

When I stop running the macro, the debugger highlights the "Next". I've tried different iterations of Next, and code online seems almost identical. I can't find what I'm doing wrong.

Further to my comment above give this a go

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM