检查日期是否在给定的时间间隔内不起作用

时间:2018-03-14 12:51:51

标签: excel excel-vba date vba

我想检查一个给定的日期,格式为mm / dd / yyyy hh:mm:ss是否在给定的时间间隔内。间隔由开始日期定义,格式相同,持续时间以十进制表示(半小时为0.5小时),如下例所示

称为过滤器的工作表中的间隔示例 enter image description here

名为data的工作表中的数据示例 enter image description here 我写了以下代码:

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中定义的区间内,但宏不会复制它们。

事实并非如此。

1 个答案:

答案 0 :(得分:1)

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