Home » excel » excel – How to compare date variable with a given time?

excel – How to compare date variable with a given time?

Posted by: admin May 14, 2020 Leave a comment

Questions:

I have an array with time values like 2020-02-17 10:00:00 AM.

I’m trying to write an if statement that executes when the time value is between two values.

If starttime(i) >= #10:00:00 AM# Then
    If starttime(i) < #10:30:00 AM# Then

The first value in the array is 2020-02-17 10:00:00 AM and it passes the first line but not the second.

It passes the first line even if I write

If starttime(i) >= #10:10:00 AM# Then

Why might this be?

How to&Answers:

#10:00:00 AM# might look and read like a time literal value, it’s not. VBA does not have any Time data type, this is a Date literal value, with an implicit date portion and a time part that says it’s 10 AM.

Use the TimeValue function to strip the Date part and only work with times.

If starttime(i) >= #10:10:00 AM# Then

That condition is always True, because the implicit Date part of the #10:10:00 AM# date literal is CDate(0), which is always going to be smaller than any other valid date value.

Debug.Print Year(#10:00:00 AM#), Month(#10:00:00 AM#), Day(#10:00:00 AM#)
 1899          12            30 

1899-12-30 is what 0 evaluates to as a date.

If TimeValue(starttime(i)) >= TimeValue(#10:00:00 AM#) Then
    If TimeValue(starttime(i)) < TimeValue(#10:30:00 AM#) Then