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
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))
DateSerial(2018, 12, 7) > DateSerial(2016, 12, 31) to make it independend from the operating system localization. DateValue needs the operating system date format to be dd-mm-yyyy to work with these string dates. If you use your code and the operating system is set to yyyy-mm-dd for example it will fail.DateSerial is that you can't use a complete date string, it will have to be broken up.07-12-2018 is dd-mm-yyyy or mm-dd-yyyy? Computers cannot know it so that's the task of the programmer. You will always need to split the string into day, month, and year and use DateSerial if you not want Excel to start guessing.
"07-12-2018"and"31-12-2016"into variables of type Date and compare that.