我在使用MS Excel上的VBA过滤日期和时间值时遇到问题。当我只需要过滤日期时,我发现使用下面的代码没有问题:
myRange.AutoFilter Field:=3, Criteria1:= _
">=" & CDbl(CDate((Date - 2))), Operator:=xlAnd, Criteria2:="<=" & CDbl(CDate((Date)))
问题是:如何指定过滤时间?示例:我想从昨天19:00到今天8:00过滤结果。
答案 0 :(得分:0)
考虑:
Sub DateTimeMaker()
Dim d1 As Date, d2 As Date, MyRange As Range
Dim crt1 As Double, crt2 As Double
d1 = DateValue("6/24/2014") + TimeValue("19:00")
d2 = DateValue("6/25/2014") + TimeValue("8:00")
crt1 = CDbl(d1)
crt2 = CDbl(d2)
Set MyRange = Range("A1:C10")
MyRange.AutoFilter Field:=3, Criteria1:=">=" & crt1, Operator:=xlAnd, Criteria2:="<=" & crt2
End Sub
修改#1:强>
让日期&#34;浮动&#34;使用方法:
Sub DateTimeMaker()
Dim d1 As Date, d2 As Date, MyRange As Range
Dim crt1 As Double, crt2 As Double
d1 = Date - 1 + TimeValue("19:00")
d2 = Date + TimeValue("8:00")
crt1 = CDbl(d1)
crt2 = CDbl(d2)
Set MyRange = Range("A1:C10")
MyRange.AutoFilter Field:=3, Criteria1:=">=" & crt1, Operator:=xlAnd, Criteria2:="<=" & crt2
End Sub
答案 1 :(得分:0)
我找到了一条路:
Sub DateTimeFilter()
Dim d1, d2, m1, m2, y1, y2 As Integer
Dim dt1, dt2 As String
d1 = Day(Date - 1)
d2 = Day(Date)
m1 = Month(Date - 1)
m2 = Month(Date)
y1 = Year(Date - 1)
y2 = Year(Date)
dt1 = m1 & "/" & d1 & "/" & y1
dt2 = m2 & "/" & d2 & "/" & y2
ActiveSheet.Range("$A$3:$L$2012").AutoFilter Field:=3, Criteria1:= _
">=" & dt1 & " 19:00", Operator:=xlAnd, Criteria2:="<=" & dt2 & " 08:00"
End Sub