【发布时间】:2018-03-14 12:51:50
【问题描述】:
我想检查给定的日期是否在给定的时间间隔内,格式为 mm/dd/yyyy hh:mm:ss。间隔由开始日期定义,格式相同,持续时间为十进制(因此半小时为 0.5 小时),如下例所示
Sub filter_Click()
Application.ScreenUpdating = False
Dim LastDataRow, LastDataCol, LastFilterRow, LastFilterCol, FilterStart, FilterDuration,
_FilterEnd As Long
' get boundaries
With Sheets("data")
LastDataRow = .Cells(.Rows.Count, "A").End(xlUp).Row
LastDataCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
With Sheets("filter")
LastFilterRow = .Cells(.Rows.Count, "A").End(xlUp).Row
LastFilterCol = .Cells(1, .Columns.Count).End(xlToLeft).Column
End With
'filter the data
lineFilter = 2
For rowFilter = 2 To LastFilterRow
FilterStart = Sheets("filter").Cells(lineFilter, 5).Value
FilterDuration = Sheets("filter").Cells(lineFilter, 6).Value
FilterEnd = FilterStart + FilterDuration / 24
For colData = 1 To LastDataCol
rowdestination = 2
colDestination = colData
If colData Mod 2 <> 0 Then
For rowData = 2 To LastDataRow
dataDate = Sheets("data").Cells(rowData, colData)
If dataDate >= FilterStart And dataDate <= FilterEnd Then
Sheets("data").Cells(rowData, colData).Copy
Sheets("filtered data").Cells(rowdestination, colDestination).PasteSpecial
Sheets("data").Cells(rowData, colData + 1).Copy
Sheets("filtered data").Cells(rowdestination, colDestination + 1).PasteSpecial
rowdestination = rowdestination + 1
End If
Next rowData
End If
Next colData
Next rowFilter
Sheets("data").Range("A1:ZZ1").Copy
Sheets("filtered data").Range("A1:ZZ1").PasteSpecial
Application.ScreenUpdating = True
End Sub
现在我希望 C12 中的日期在 E3 和 F3 中定义的时间间隔内,但宏不会复制它们。
事实并非如此。
【问题讨论】:
-
dataDate 似乎没有被 Dim'd (也是 colData)所以你可能有类型转换问题。您应该将日期转换为 CDate 类型以进行比较。如果您将“选项显式”添加到代码顶部,您将能够找到未标注的变量
-
@Tragamor,在这种情况下我不应该得到错误吗?因为我什么都没有。
-
我建议使用 DateDiff 检查日期之间的差异并以此为基础。请看这个帖子:stackoverflow.com/questions/48811340/…
-
为了显示日期,我建议始终使用format
YYYY-MM-DDaccording to ISO 8601,这是唯一一种只有一种解释的格式。这也使得在 VBA 中将字符串解析为日期变得更加容易。 -
如果您无法更改日期格式,类似于@Pᴇʜ 的建议,我建议拆分数据进行比较,例如 left(cell,2)=month(rng) & right(left(cell,10),4)=year(rng),进行精确比较,不依赖于列出的日期格式。您可以在逻辑 if 语句中执行此检查,例如,如果 year_cell = year_rng AND (month_cell = month_rng OR day_cell = day_rng) then...