【发布时间】:2016-10-28 12:27:23
【问题描述】:
我需要删除给定日期范围之外的所有行。我能够记录一个宏,但这仅适用于给定的数据集,并且随着添加更多数据而无法删除所有适当的行。我未能成功修改在主题中找到的其他宏,这些宏询问完全相同的事情......对不起。
日期交易日期在 C 列中,最早的在单元格 J1 中(通常是一个公式,如果这很重要,但我可以更改它),日期范围的结束在单元格 L1 中。
我尝试使用 Dan Wagner 之前发布的这段代码:
Option Explicit
Sub DeleteDateWithAutoFilter()
Dim MySheet As Worksheet, MyRange As Range
Dim LastRow As Long, LastCol As Long
'turn off alerts
Application.DisplayAlerts = False
'set references up-front
Set MySheet = ThisWorkbook.Worksheets("Sheet1")
'identify the last row in column A and the last col in row 1
'then assign a range to contain the full data "block"
With MySheet
LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
LastCol = .Range("A" & .Columns.Count).End(xlToLeft).Column
Set MyRange = .Range(.Cells(1, 1), .Cells(LastRow, LastCol))
End With
'apply autofilter to the range showing only dates
'older than january 1st, 2013, then deleting
'all the visible rows except the header
With MyRange
.AutoFilter Field:=1, Criteria1:="<1/1/2013"
.SpecialCells(xlCellTypeVisible).Offset(1, 0).Resize(.Rows.Count).Rows.Delete
End With
'turn off autofilter safely
With MySheet
.AutoFilterMode = False
If .FilterMode = True Then
.ShowAllData
End If
End With
'turn alerts back on
Application.DisplayAlerts = True
End Sub``
提前谢谢你!
【问题讨论】:
-
您要删除
column C的任何单元格中日期小于 01/01/2013 的任何行吗?我对你提到J1和L1感到困惑 -
单元格 J1 将具有我想要保留的最早日期,L1 将具有我想要保留的最后日期。这两个单元格仅提供宏需要保留的日期范围。 2013 年 1 月 1 日是我尝试修改数据的宏之一的一部分。我尝试添加图片,但我的积分还不够。