I am using windows 10 OS excel 13 so in the below code 1
should return 1/1/1900
right ? below it doesn't why.
On this question OP passed 2016
and got the same result I got so if there is some error why do I got the same result as OP when I passed 2016
?
Sub ndat()
Dim dt As Date
dt = 2016
Debug.Print "dt is " & dt
End Sub
Integers and dates map differently in VBA than in the worksheet. For example:
Sub marine()
Dim i As Integer, d As Date
Dim mgs As String
msg = ""
For i = -10 To 10
d = CDate(i)
msg = msg & i & vbTab & Format(d, "mm/dd/yyyy") & vbCrLf
Next i
MsgBox msg
End Sub
Produces:
Note you can get dates prior to 1/1/1900
EDIT#1:
This may help to understand the difference. I put some integers in column A.
In B1, I put =A1
and copy down. I format column B to display in date format.
I use this UDF():
Public Function VBA_Date(i As Long) As String
VBA_Date = Format(CDate(i), "mm/dd/yyyy")
End Function
To fill column C:
Note the transition between rows #19 and #20
It is just the worksheet itself. Or to be correct: The worksheet-functionality!
Quick test:
?cdate(1)
1899-12-31
?format(1,"YYYY-MM-DD")
1899-12-31
?worksheetfunction.Text(1,"YYYY-MM-DD")
1900-01-01
But going for todays date does not show this gap:
?clng(now)
42463
?worksheetfunction.Text(now,"0")
42463
That shows that somewhere between 1 and 42463 is a gap (the quick lotus check shows it:
?cdate(60) & " --- " & cdate(61)
1900-02-28 --- 1900-03-01
?format(60,"YYYY-MM-DD") & " --- " & format(61,"YYYY-MM-DD")
1900-02-28 --- 1900-03-01
?worksheetfunction.Text(60,"YYYY-MM-DD") & " --- " & worksheetfunction.Text(61,"YYYY-MM-DD")
1900-02-29 --- 1900-03-01
Just one last test to show it again:
?format("1900-02-28","0") & " --- " & format("1900-03-01","0")
60 --- 61
?worksheetfunction.Text("1900-02-28","0") & " --- " & worksheetfunction.Text("1900-03-01","0")
59 --- 61
starting with 61, there is simply now difference in numbers. But the Lotus-Bug adds the 1900-02-29 for "compatibility".
Also: that is a "feature" for excel and has nothing to do with basic, vbscript, vba.......... All other programs work in the correct way and it would get lots of trouble if VBA would not. So for "compatibility" the VBA in excel just does it in the correct way ;)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With