【问题标题】:Checking if a date falls in a given interval not working检查日期是否在给定的时间间隔内不起作用
【发布时间】: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-DD according 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...

标签: excel date vba


【解决方案1】:

问题似乎在于If dataDate &gt;= FilterStart And dataDate &lt;= FilterEnd 直接比较日期时间数据类型,使用比较运算符可能会返回意外结果。我建议使用 VBA 的 DateDiff 函数 (reference)。在this线程中遇到了类似的问题,使用DateDiff函数成功解决。

【讨论】:

    猜你喜欢
    • 2018-07-26
    • 1970-01-01
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-12-25
    • 1970-01-01
    • 2021-08-20
    相关资源
    最近更新 更多