嘿伙计我知道如何在列中过滤时间,但如果日期也在同一列中,它是如何完成的?我尝试在12:00:00 AM - 3:00:00 PM之间过滤数字过滤器,但它根本没有过滤。数据的格式与第一张图片类似,但我将其更改为仅显示时间而不是日期。
[lastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
ActiveSheet.Range("A4", "A" & lastRow).NumberFormat = "hh:mm:ss AM/PM"
ActiveSheet.Range("$A$4:$C$18").AutoFilter Field:=1, Criteria1:="<=m/d/yyyy 12:00:00 AM", Operator:=xlAnd, Criteria2:=">= m/d/yyyy 3:00:00 PM"
ActiveSheet.Range("$A$4:$C$18").AutoFilter Field:=1, Criteria1:="<=12:00:00 AM", Operator:=xlAnd, Criteria2:=">=3:00:00 PM"]
答案 0 :(得分:1)
假设数据有一个固定的日期(在你的例子中我猜是6/1/2017
)你可以使用下面的方法从第一个数据点获取日期,然后从日期的总和建立标准部分加上您想要传递给时间部分的任何输入。
该行:
dtCriteria1 = CDate(CLng(dtConstant)) + TimeValue("00:03:00")
仅通过保留表示日期的数字的整数部分将第一个数据点转换为日期,然后添加小时,分钟和秒部分的时间值。
所以,从这开始:
运行此代码:
Option Explicit
Sub FilterTimeWithADate()
Dim ws As Worksheet
Dim rng As Range
Dim dtConstant As Date
Dim dtCriteria1 As Date
Dim dtCriteria2 As Date
' get references to sheet and range
Set ws = ThisWorkbook.Worksheets("Sheet1") '<-- set to your worksheet
Set rng = ws.Range("A1:A24") '<-- set to your range
' reset filter
ws.AutoFilterMode = False
' reset range numberformat
rng.Offset(1, 0).Resize(rng.Rows.Count - 1, 1).NumberFormat = "dd/mm/yy h:mm:ss"
' get date from first data point
dtConstant = CDate(rng.Cells(2, 1).Value)
' set filter dates
dtCriteria1 = CDate(CLng(dtConstant)) + TimeValue("00:03:00")
dtCriteria2 = CDate(CLng(dtConstant)) + TimeValue("00:08:30")
' set range format
rng.Offset(1, 0).Resize(rng.Rows.Count - 1, 1).NumberFormat = "hh:mm:ss AM/PM"
' set filter
rng.AutoFilter Field:=1, _
Criteria1:=">=" & dtCriteria1, _
Operator:=xlAnd, _
Criteria2:="<=" & dtCriteria2
End Sub
最终得到这个:
您可能希望在调试模式中单步执行代码以查看每个点的行为。
答案 1 :(得分:1)
Sub Original_01()
Dim Criteria1 As Variant
Dim Criteria2 As Variant
ActiveSheet.AutoFilterMode = False
lastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
Set r = ActiveSheet.Range("A1" & ":C" & lastRow)
dtConstant = DateValue(CDate(r.Cells(2, 1).Value))
Criteria1 = CDbl(dtConstant + TimeValue(CDate("04:00:00 AM")))
Criteria2 = CDbl(dtConstant + TimeValue(CDate("08:30:00 AM")))
Criteria1 = ">=" & Replace(Criteria1, ",", ".")
Criteria2 = "<=" & Replace(Criteria2, ",", ".")
r.AutoFilter Field:=1, Criteria1:=Criteria1, Criteria2:=Criteria2
End Sub