anandhu
anandhu

Reputation: 760

Issue while comparing dates in VBA?

I am trying to compare two dates using the below code:

MsgBox (Format("07-12-2018", "dd-MMM-yyyy") > Format("31-12-2016", "dd-MMM-yyyy"))

Though the first date is greater than the second, the Message box displays False

Upvotes: 2

Views: 528

Answers (1)

Tim Stack
Tim Stack

Reputation: 3248

Instead of comparing strings, use the DateValue or DateSerial function.

DateValue

MsgBox (DateValue("07-12-2018") > DateValue("31-12-2016")) 

This will correctly display True

Note:

DateValue recognizes the order for month, day, and year according to the Short Date format that you specified for your system

DateSerial

Is independent of the local system's Short Date format, since it uses separate arguments for the year, month, and date:

MsgBox (DateSerial(2018,12,7) > DateSerial(2016,12,31))

Upvotes: 2

Related Questions