Home » excel » excel – Date / Time Comparison in VBA

excel – Date / Time Comparison in VBA

Posted by: admin May 14, 2020 Leave a comment

Questions:

Goal: The excel sheet contains a list of activities. The goal is to compare the Date/Time of two activities. I need to identify if there is any overlap between the two. Column B contains the start date and time of each activity and column C contains the end date and time of each activity.

ActivityOneStartTime = Range("B41").Value

ActivityOneEndTime = Range("C41").Value

ActivityTwoStartTime = Range("B32").Value

ActivityTwoEndTime = Range("C32").Value


If ActivityOneStartTime >= ActivityTwoStartTime Then

    If ActivityOneStartTime < ActivityTwoEndTime Then

        booScheduleConflict = True

    End If

End If

If ActivityOneEndTime <= ActivityTwoEndTime Then

    If ActivityOneEndTime > ActivityTwoStartTime Then

        booScheduleConflict = True

    End If

End If

The above, of course, doesn’t work. So, after trying a few other unsuccessful approaches, I’ve started going through the paces of setting up Case statments comparing first years, then months, then days, then hours, then minutes, but I’m sure there is an easier way.

Thank you in advance for any assistance with this challenge.

How to&Answers:

Like this:

ActivityOneStartTime = Range("B41").Value
ActivityOneEndTime = Range("C41").Value
ActivityTwoStartTime = Range("B32").Value
ActivityTwoEndTime = Range("C32").Value

If ActivityOneStartTime < ActivityTwoEndTime Then
    If ActivityOneEndTime > ActivityTwoStartTime Then

        booScheduleConflict = True

    End If    
End If

Answer:

I think your issue is determining the logic to test for overlap.

Try this

booScheduleConflict = Not(ActivityOneEndTime <= ActivityTwoStartTime or _
                          ActivityOneStartTime >=  ActivityTwoEndTime)

Answer:

It can be done by using TimeValue Property. Here is the example:

Dim date1 As Date
Dim date2 As Date
Dim date3 As Date

date1 = TimeValue(Range("A1").Text)
date2 = TimeValue(Range("B1").Text)
date3 = TimeValue(Range("C1").Text)

If date3 >= date1 And date3 <= date2 Then
     'Yes!
Else
     'No!
End If