I've got a spreadsheet that contains a number of dates. These generally appear in either mm/dd/yyyy or mm/dd/yyyy hh:mm.
The problem is that the dates aren't always put in correctly and I want to have checks to make sure they are dates in the code.
My original thought was to use IsDate to check or CDate but this didn't seem to work: it was still returning strings instead of dates.
I've since set up a small experiment which shows that these functions don't work the way I expect them to. Methodology is:
- In a cell A1 I enter the formula
=DATE(2013,10,28) - Cell B1 formula
=A1*1which should equal a number (41575) Run this little script
Sub test() MsgBox ("Start:" & TypeName(ActiveCell.Value) & " " & IsDate(ActiveCell.Value)) ActiveCell.Value = Format(ActiveCell.Value, "mm/dd/yyyy") MsgBox ("After format: " & TypeName(ActiveCell.Value) & " " & IsDate(ActiveCell.Value)) ActiveCell.Value = CDate(ActiveCell.Value) MsgBox ("After Cdate: " & TypeName(ActiveCell.Value) & " " & IsDate(ActiveCell.Value)) End Sub
When the script starts the cell is a of type date and IsDate returns true. After it is run through Format it is of type string but IsDate still returns true. CDate will also convert the cell to a string. Cell B1 will also now return 0 (since its a string*1).
So I guess to summarize the questions:
- Why are
FormatandCDatechanging my cells to strings? - How can I ensure that a cell will return a date value and not just a string that looks like a date?