The VBA CDate function converts an expression into a Date (or Date/Time) data type.
The syntax of the function is:
Where the Expression argument is the expression that that you want to convert to a Date.
The VBA Date data type holds both date and time information. Therefore the Expression that is supplied to the CDate function must be able to be interpreted as a valid VBA date or time.
The CDate function can interpret text representations of dates and times that are in a recognised Excel format. However, the function is unable to interpret dates that include the text description of the weekday (Sunday, Monday, etc).
In the following VBA code, the CDate function is used to convert various text strings and numeric values into VBA dates and times.
' Convert strings and numeric values into dates and/or times
Dim dt1 As Date
Dim dt2 As Date
Dim dt3 As Date
Dim dt4 As Date
Dim dt5 As Date
dt1 = CDate( "12/31/2015" )
' dt1 is now equal to the date 12/31/2015
dt2 = CDate( "Jan 1 2016 3:00 AM" )
' dt2 is now equal to the date/time 1/1/2016 3:00:00 AM
dt3 = CDate( "12:00:00" )
' dt3 is now equal to the time 12:00:00 PM
dt4 = CDate( 42369 )dt5 = CDate( 0.5 )
' dt4 is now equal to the date 12/31/2015
' dt5 is now equal to the time 12:00:00 PM
Note that, in the above VBA code:
If the Expression that is supplied to the CDate function cannot be converted to a date or time, you will get the error: