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

后端 未结 2 1747
傲寒
傲寒 2021-02-13 14:23

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 pas

2条回答
  •  野性不改
    2021-02-13 15:17

    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

提交回复
热议问题