从某个单元格中删除Excel VBA中的整行

时间:2013-06-17 11:32:15

标签: excel vba

如果日期比今天晚一周以上,我试图删除整行数据,但我不想删除标题。今天的日期是A2中出现的变量。

编辑:A栏的日期格式为dd / mm / yyyy。

此代码是我目前所拥有的,但它不起作用并删除标题:

Sub deletedates()

Dim firstDate As Date, secondDate As Date
Dim i As Range

firstDate = DateValue(Range("A2"))
secondDate = DateAdd("d", 6, firstDate)

MsgBox secondDate

For Each i In Range("A:A")
If i.Value > secondDate Then
i.Select
ActiveCell.EntireRow.Delete

End If
Next i


End Sub 

1 个答案:

答案 0 :(得分:1)

我添加了一些有助于解决两个问题的内容:

1)lngCounter = Cells.Find(“*”,[A1] ,,, xlByRows,xlPrevious).row找到最后一行数据,因为原始代码将查看A列中的每个单元格,如果您使用较新版本的Excel,则超过一百万。

2)我已经开始在A列的第2行搜索数据,以避免删除标题行。

希望这有帮助!

Sub deletedates()

Dim firstDate As Date, secondDate As Date
Dim i As range
Dim lngCounter As Long
Dim strRange As String

lngCounter = Cells.Find("*", [A1], , , xlByRows, xlPrevious).row 'Find last row of data

strRange = "a2:a" & lngCounter 'Start at Row 2, Column A, finish at last row of Column A

firstDate = DateValue(range("A2"))
secondDate = DateAdd("d", 6, firstDate)

'MsgBox secondDate

    For Each i In range(strRange) 'Starts at second row of data.

        If i.Value > secondDate Then
        i.Select
        ActiveCell.EntireRow.Delete

        End If

    Next i

End Sub