Excel VBA:删除旧记录

时间:2016-12-07 23:07:30

标签: excel vba excel-vba

我正在尝试删除任何180天或更早的记录。日期在F列。当我运行时,没有任何反应。我认为它与Date()函数有关。

Sub ClearOldData()
Application.ScreenUpdating = False
Sheets("Data").Select
Dim LastRow As Long
With ActiveSheet
    LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With
For i = 2 To LastRow
    Dim recdate As Date
    recdate = Cells(i, "F").Value 
    If DateDiff(d, Date, recdate) > 179 Then
        ws.Rows(i).Delete
    End If
Next i
Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:3)

在VBA中日期/时间是从1开始的数值,相当于#1/1/1900#。

日期/时间值

  • 1天= 1
  • 1小时= 1/24
  • 1分钟= 1/24/60
  • 1秒= 1/24/60/60

始终从最后一行/项目删除到第一行/项目。我对Compare cells to delete rows, value is true but not deleting rows的回答说明了原因。

DateDiff("d", Date, recdate) > 179Int(Date - recdate) > 179是等效的。

Sub ClearOldData()
    Application.ScreenUpdating = False
    Dimi As Long

    With Sheets("Data")

        For i = 2 To LastRow Step -1
            If Int(Date - Cells(i, "F").Value) > 179 Then
                .Rows(i).Delete
            End If
        Next i

    End With
    Application.ScreenUpdating = True
End Sub
相关问题