首页 > 解决方案 > 删除最后几个工作日

问题描述

我正在尝试删除所有包含过去两天(今天和昨天)日期的行。

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 天)仍包含在数据中。

如果我将 > 反转为 <,则只保留新日期,这正是我想要摆脱的。

标签: excelvba

解决方案


针对日期样本(从 01/07/2018 到 10/07/2018 [今天])运行此代码后,此代码删除了显示今天日期的行。如果您还想删除前一个工作日,则需要将“-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 也被删除但第一个不是)。


推荐阅读