Friday, November 21, 2008

Determine If The Current Time Falls Within a Range

This code is useful if you need to determine if the current time falls between two other times, and then execute some code or processes based on the results. This implements a user-defined function named InRange().

Declarations:
'(None)
Code:
Public Function InRange(startTime As Date, endTime As Date) As Boolean

    Dim dtNow As Date

    dtNow = Now

    Select Case TimeValue(dtNow)
        Case Is > TimeValue(startTime)
            If TimeValue(endTime) > TimeValue(dtNow) Then
                InRange = True
            End If
        Case Is > TimeValue(startTime)
            If TimeValue(endTime) > TimeValue(dtNow) Then
                InRange = True
            Else
                InRange = False
            End If
        Case Is < TimeValue(startTime) And (TimeValue(endTime) > TimeValue(dtNow))
                InRange = True
        Case Else
            InRange = False
    End Select

End Function

Private Sub Form_Load()
     Debug.Print InRange(CDate("03:00:00"), CDate("18:00:00"))
End Sub

No comments:

Post a Comment