Home » excel » vba – Inconsistent behaviour of CDate()

vba – Inconsistent behaviour of CDate()

Posted by: admin April 23, 2020 Leave a comment

Questions:

Regional settings in Windows are MM/DD/YYYY

Now look at these two lines, and the change in the MONTH:

Sub DateBug()
    Debug.Print Format(CDate("11/4/1999"), "MMMM D, YYYY")
    Debug.Print Format(CDate("30/4/1999"), "MMMM D, YYYY")
End Sub

OUTPUT:

November 4, 1999
April 30, 1999

Great, huh? What is going on?

In the 2nd line, I want an error, not “guessing”.

Is this a bug? Any idea how this can be circumvented ?

Same in Excel 2007, 2010, 2013

How to&Answers:

This is not a bug, its a “feature”

enter image description here

CDate() will interpret the string according to fixed rules. If the date is valid as m/d/y, that will be returned. If the date is not valid as m/d/y, but is valid as d/m/y, then that will be returned. If the date is not valid as either m/d/y or d/m/y, then an error will be returned.

Sub dural()
    Dim st As String
    st = CStr(CDate("12/4/2012")) & vbCrLf & CStr(CDate("13/4/2012"))
    MsgBox st
End Sub

Answer:

Not a bug. VB will convert strings to date literals using the default regional settings, if it can. Which it did in the first date. But on the second date, that would have given an invalid date, so it tried DD/MM/YYYY and that worked. Solution, put use date literals instead of strings. Put # signs around both date literals (ex: ‘#4/30/1999#’) to ignore regional setting and force use of the MM/DD/YYYY format. ‘#30/4/1999#’ would have given you the error you want. This will make your code independent of the regional setting of the computer – ie, it will work regardless. Or else use DateTime(1999, 4, 30, 0, 0, 0). Look here… Date Data Type (Visual Basic)

In Excel, you would use the literal without the single quotes:

Sub Macro1()
Range("D2").Select
ActiveCell.FormulaR1C1 = CDate(#4/30/1999#)
End Sub