Sunil:
The following function is one used to do this in an application I developed
a few years ago. It works with an unbound form in which the date, hours and
minutes are entered into separate controls and the actual date/time values
are then computed. The function takes the true date/time values as its
arguments, however, so the logic behind it would be equally applicable to a
bound form with controls bound to true date/time fields, calling the function
in the form's BeforeUpdate event procedure:
Private Function ValidateTimes(dtmStartTime As Date, dtmEndTime As Date) As
Boolean
Dim strMessage As String, strCriteria As String
Dim varTimes As Variant
ValidateTimes = False
varTimes = Me!cboStartHour + Me!cboStartMinutes + _
Me!cboEndHour + Me!cboEndMinutes
' execute only if all time controls have values
If Not IsNull(varTimes) Then
' validate that start/end times are compatible
If dtmStartTime >= dtmEndTime Then
strMessage = "Finishing time must be later than start time."
MsgBox strMessage, vbExclamation, "Invalid operation"
Exit Function
ElseIf Me!cboEndHour = "24" And Me!cboEndMinutes > "0" Then
strMessage = "Finishing time cannot be after 24:00 hours"
MsgBox strMessage, vbExclamation, "Invalid operation"
Exit Function
End If
' ensure time range does not overlap with another record for current
employee
strCriteria = "((" & USDateTime(dtmStartTime) & " >= StartTime " & _
"And " & USDateTime(dtmStartTime) & " < EndTime) " & _
"Or (" & USDateTime(dtmEndTime) & " <= EndTime " & _
"And " & USDateTime(dtmEndTime) & " > StartTime) " & _
"Or (" & USDateTime(dtmStartTime) & " <= StartTime " & _
"And " & USDateTime(dtmEndTime) & " >= EndTime)) " & _
" And EmployeeID =" & Me!cboEmployee
Debug.Print strCriteria
If Not IsNull(DLookup("TimeRecordID", "Times", strCriteria)) Then
strMessage = "Times conflict with times previously entered for "
& _
"this employee on " & Format(dtmStartTime, "dddd dd mmmm
yyyy")
MsgBox strMessage, vbExclamation, "Invalid operation"
Exit Function
End If
End If
ValidateTimes = True
End Function
The function calls the following USDateTime function to format the date/time
values as date/time literals in US format. In Access date/time literals must
be in this or an otherwise internationally unambiguous format:
Public Function USDateTime(dtmDateTime As Date) As String
' returns date/time as string in US date format
On Error GoTo Err_Handler
USDateTime = "#" & Format(dtmDateTime, "mm/dd/yyyy hh:nn:ss") & "#"
Exit_Here:
Exit Function
Err_Handler:
MsgBox Err.Description & " (" & Err.Number & ")", vbExclamation, "Error"
Resume Exit_Here
End Function
Ken Sheridan
Stafford, England