Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does the date returns "31-12-1899" when 1 is passed to it?

Tags:

date

excel

vba

enter image description here

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

enter image description here

like image 870
Stupid_Intern Avatar asked Apr 02 '16 20:04

Stupid_Intern


2 Answers

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:

enter image description here

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:

enter image description here

Note the transition between rows #19 and #20

like image 109
Gary's Student Avatar answered Oct 23 '22 10:10

Gary's Student


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 ;)

like image 41
Dirk Reichel Avatar answered Oct 23 '22 11:10

Dirk Reichel