Excel VBA:需要删除其中单元格在当前日期的7天内包含日期的行

时间:2017-12-05 16:22:36

标签: excel-vba vba excel

我尝试使用r1c1公式和自动过滤器。我也尝试拼凑我在互联网上找到的代码,但没有任何工作正常。拜托,我非常喜欢寻求帮助的业余爱好者。

我需要代码查看特定列,并删除该列中的单元格在今天的7天内的所有行。所以今天的日期为12/5/2017,我需要删除包含日期11/28到12/5的所有行。

必须始终根据当前日期进行评估。任何帮助都非常感激。感谢

Sub DeleteLastContact()

Dim ws As Worksheet, cel As Range, compRng As Range

Set ws = ThisWorkbook.Worksheets("Data")
Set compRng = ws.UsedRange.Columns("AE")

Dim delRng As Range, tmpVal As Date

For Each cel In compRng.Cells
Debug.Print cel.value
    tmpVal = cel.value
    If tmpVal < Date - 7 Then
        If delRng Is Nothing Then
            Set delRng = cel
        Else
            Set delRng = Union(cel, delRng)
        End If
    End If
Next cel

If Not delRng Is Nothing Then delRng.EntireRow.Delete



End Sub

1 个答案:

答案 0 :(得分:0)

这是未经测试的,如果您有错误,请告诉我。

您可以遍历AE列中的所有单元格,将符合条件的每个单元格添加到特殊范围,最后删除特殊范围内的所有行。

Sub DeleteLastContact()

    Dim ws As Worksheet, cel As Range, compRng As Range
    Set ws = ThisWorkbook.Worksheets("Sheet1")
    Set compRng = ws.UsedRange.Columns("AE")

    Dim delRng As Range, tmpVal As Date

    For Each cel In compRng.Cells
        tmpVal = cel.Value
        If tmpVal < Date - 7 Then
            If delRng Is Nothing Then
                Set delRng = cel
            Else
                Set delRng = Union(cel, delRng)
            End If
        End If
    Next cel

    If Not delRng Is Nothing Then delRng.EntireRow.Delete

End Sub