Excel: Use VBA to delete rows within a specified date range

时间:2015-07-31 20:11:56

标签: excel vba excel-vba

I have a workbook with ~20 sheets. In each sheet Column A has dates and Column B has data points. Column A is not the same in every sheet! I want to cut out data I don't need based on date ranges. I've tried this, and it runs for quite a long time, but does nothing.

Sub DeleteRowBasedOnDateRange()

Dim RowToTest As Long
Dim ws As Worksheet

For Each ws In ThisWorkbook.Sheets

For RowToTest = ws.Cells(Rows.Count, 1).End(xlUp).Row To 2 Step -1

With ws.Cells(RowToTest, 1)
    If .Value > #6/16/2015# _
    And .Value < #6/22/2015# _
    Then _
    ws.Rows(RowToTest).EntireRow.Delete
End With

Next RowToTest

Next

End Sub

Suggestions?

2 个答案:

答案 0 :(得分:1)

    Sub DeleteRowBasedOnDateRange()

Dim RowToTest As Long
Dim ws As Worksheet

For Each ws In ThisWorkbook.Sheets

For RowToTest = ws.Cells(Rows.Count, 1).End(xlUp).Row To 1 Step -1

With ws.Cells(RowToTest, 1)
    If .Value < #6/16/2015# _
    Or .Value > #6/22/2015# _
    Then _
    ws.Rows(RowToTest).EntireRow.Delete
End With

Next RowToTest

Next

End Sub
  

这段代码对我来说很好。您说每张纸的日期格式不同。也许您需要在运行宏之前尝试修复格式,因为它可能不会被视为日期。 - bbishopca

bbshopca你是对的!它确实有效。事实证明我的逻辑都倒退了。我想删除2015-06-16到2015-06-22范围之外的日期,而不是在内。由于我有这么多行的数据,我会看到2015-06-16之前的日期没有删除,并认为我的代码不起作用。感谢所有输入。

答案 1 :(得分:0)

To speed it up, rather than delete one row at a time, you could sort the column by date, then find the rows within that range by using cells.find. Save those rows, then delete the range of rows at once. By doing it this way it's less brute force and it only requires finding 2 cells, and deleting rows once.