2016-12-07 50 views
1

我試圖刪除180天或更長時間的任何記錄。日期在F欄。當我運行這個時,沒有任何反應。我在想它與Date()函數有關。Excel VBA:刪除舊記錄

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 
+3

當刪除行,最好從下往上的工作,所以你行的索引不會被幹擾。 '對於我= LastRow到2步-1' –

+0

好點。我已經做了這個改變。雖然沒有解決手頭的問題。 – superblowncolon

+1

Tim有一點,運行你的for循環爲'For i = LastRow to 2 Step -1'從底部開始,而且你正在使用'ws'對象(可能是作爲工作表的參考),但是你從未將它放在任何地方。您還可以將'Debug.Print recdate&「」&Date&「」&DateDiff(「d」,Date,recdate)'添加到循環的開頭,以確切瞭解它正在計算的內容。 – Dave

回答

3

在VBA日期/時間是從1開始的數值,相當於#1/1/1900#。

日期/時間值

  • 1天= 1
  • 1小時= 1/24
  • 1分鐘= 60年1月24日
  • 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