我要过滤日期列基础 1年 2.月
“年”和“月”是动态字段,我将其值保存为 年-年 月-月
宏是否可以使用这些条件进行简单过滤而无需插入其他列?
Sub testcode()
Range("a1:a200").Select
yr = 2019
mnth = Feb
ActiveSheet.Range("$A$1:$A$3200").AutoFilter Field:=1, Criteria1:=yr
End Sub
答案 0 :(得分:0)
使用Criteria1和Criteria2设置日期范围。
dim dt as long
dt = datevalue("1 " & mnth & ", " & yr)
with activesheet
with .range(.cells(1, "A"), .cells(.rows.count, "A").end(xlup))
.autofilter field:=1, criteria1:=">="&dt, operator:=xland, _
criteria2:="<" & dateserial(year(dt), month(dt)+1, 1)
end with
end with
答案 1 :(得分:0)
如果记录日期值自动过滤器的设置,则会得到:
Sub DateFiter_Recorded()
'
' DateFiter_Recorded Macro
'
Columns("C:C").ColumnWidth = 16.29
ActiveSheet.Range("A1:A3200").AutoFilter Field:=1, Operator:= _
xlFilterValues, criteria2:=Array(1, "2/4/2019")
ActiveWindow.SmallScroll Down:=153
Range("C194").Select
End Sub
基于此,很容易编写代码并测试用于设置过滤器的例程:
Option Explicit
Sub SetDateValueRange()
ActiveWorkbook.Names.Add Name:="DateValRange", RefersTo:="=Sheet1!A1:A3200"
End Sub
Sub DateFiter_JAN_2019()
ActiveSheet.Range("DateValRange").AutoFilter Field:=1, Operator:= _
xlFilterValues, criteria2:=Array(1, "1/31/2019")
End Sub
Sub DateFiter_FEB_2019()
Dim criteria2value
criteria2value = Array(1, "2/15/2019")
ActiveSheet.Range("DateValRange").AutoFilter Field:=1, Operator:= _
xlFilterValues, criteria2:=criteria2value
End Sub
Sub DateFiter_AUG_2019()
Dim criteria2value
criteria2value = Array(1, "8/1/2018")
ActiveSheet.Range("DateValRange").AutoFilter Field:=1, Operator:= _
xlFilterValues, criteria2:=criteria2value
End Sub