我通过为每周处理的报告编写宏来教自己VBA。在本报告中,我需要按日期过滤大量数据(~4000行)。我的目标是摆脱任何开始日期不在上周的行。我编写了以下函数来仅显示我想要保留的数据,但是当我意识到我想要删除所有未显示的数据时,它就卡住了。
Sub LimitDates()
'Define date variables
Dim today As Date
Dim strDate As Date
Dim endDate As Date
Dim dateArray(6) As Date
today = Date
strDate = DateAdd("d", -7, today)
endDate = DateAdd("d", -1, today)
dateArray(0) = strDate
dateArray(1) = strDate + 1
dateArray(2) = strDate + 2
dateArray(3) = strDate + 3
dateArray(4) = strDate + 4
dateArray(5) = strDate + 5
dateArray(6) = strDate + 6
'Define Row Count
originalRowCount = Cells(Rows.Count, 1).Row
'Filters to only relevent dates
Range("A1:I1").Select
Selection.AutoFilter
ActiveSheet.Range("A1").Resize(RowSize:=originalRowCount, _
ColumnSize:=9).AutoFilter Field:=5, Operator:= xlFilterValues, _
Criteria2:=Array(2, dateArray(0), 2, dateArray(1), 2, dateArray(2), _
2, dateArray(3), 2, dateArray(4), 2, dateArray(5), 2, dateArray(6))
End Sub
我确信有很多方法可以使上述代码更好,但我的问题是:如何过滤“糟糕”日期,而不是过滤“糟糕”日期(我日期范围之前和之后的所有内容) )?*
答案 0 :(得分:1)
Dim today As Date
Dim strDate As Date
Dim endDate As Date
today = Date
strDate = DateAdd("d", -7, today)
endDate = DateAdd("d", -1, today)
'Define Row Count
originalRowCount = Cells(Rows.Count, 1).Row
'Filters to only relevent dates
Range("A1:I1").Select
Selection.AutoFilter
ActiveSheet.Range("A1").Resize(RowSize:=originalRowCount, _
ColumnSize:=9).AutoFilter Field:=5, _
Criteria1:="<" & strDate, Operator:=xlOr, Criteria2:=">" & endDate
使用小于或大于您想要的日期作为标准。