excel中如何从单元格中获取日期

Анд*_*нов 0 excel vba

我在 VBA 中有一个函数可以处理单元格中的日期。但当By ref error我选择细胞时我得到了。可能是什么问题?这是我的代码

Function DifferenceInYears(existdate As Date, estimdate As Date) As Double

    Dim yearDifference As Integer
    Dim monthDifference As Integer
    Dim dayDifference As Integer
    yearDifference = 0
    monthDifference = 0
    dayDifference = 0
    If (estimdate <= existdate) Then
        MsgBox "Input correct range"
        GoTo myerr
    End If
    Dim tempDate As Date
    IsDateLeapDay = False
    Dim existYear As String
    Dim estimYear As String
    existYear = Year(existdate)
    estimYear = Year(estimdate)
    estimMonth = Month(estimdate)
    existMonth = Month(existdate)

    and so on...
Run Code Online (Sandbox Code Playgroud)

Gis*_*ofx 5

这应该可以帮助您开始:

Sub GetDatesAndComputeElapsedYears()

   Dim d1 As String
   Dim d2 As String

   d1 = Range("a2").Value2 'put a date in A2 Formatted as date(cell format)
   d2 = Range("b2").Value2 'put a date in B2 Formaated as date(cell format)

   Dim date1 As Date
   Dim date2 As Date

   date1 = CDate(d1) 'converts serialized date to DATE Object
   date2 = CDate(d2)

   Dim years

   years = DateDiff("yyyy", date1, date2) 'use this for date difference calculations

   MsgBox CStr(years), vbOKOnly, "Years Elapsed"

End Sub
Run Code Online (Sandbox Code Playgroud)