我正在尝试删除最近两天(今天和昨天)中所有包含日期的行。
H列是日期列。
以下是相关代码:
Dim lstRow As Long, Idx As Long
lstRow = Range("H" & Cells.Rows.Count).End(xlUp).row
For Idx = lstRow To 2 Step -1 ' change 1 to the first row with dates
If Cells(Idx, "H") > Application.WorksheetFunction.WorkDay(Date, -1) Then
Cells(Idx, "H").EntireRow.Delete
End If
Next
它没有任何作用。整个日期范围(过去5天)仍包含在数据中。
如果我将>反转为<,则仅保留新日期,这正是我要删除的日期。
答案 0 :(得分:0)
已针对日期样本(从01/07/2018到10/07/2018 [Today])运行了此代码,此代码删除了显示当天日期的行。如果您还想删除前一个工作日,则需要将“ -1”更改为“ -2”,如下所示:
Dim lstRow As Long, Idx As Long
lstRow = Range("H" & Cells.Rows.Count).End(xlUp).row
For Idx = lstRow To 2 Step -1 ' change 1 to the first row with dates
If Cells(Idx, "H") > Application.WorksheetFunction.WorkDay(Date, -2) Then
Cells(Idx, "H").EntireRow.Delete
End If
Next
此外,您没有声明它,但是当您使用“ Application.WorksheetFunction.WorkDay”时,它还将删除该窗口中非工作日的任何日期(因此在我的示例数据中,第7和第8个也被删除,但第一个未被删除。
答案 1 :(得分:0)
记录下来,这是吉普(Jeeped)提出的并且非常有效的解决方案:
Dim lstRow As Long, Idx As Long, wd1 As Long
lstRow = Range("H" & Cells.Rows.Count).End(xlUp).row
wd1 = Application.WorksheetFunction.WorkDay(Date, -1)
For Idx = lstRow To 2 Step -1 ' change 1 to the first row with dates
If Cells(Idx, "H") >= wd1 Then
Cells(Idx, "H").EntireRow.Delete
End If
Next