我在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...
答案 0 :(得分:3)
这应该让你开始:
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
答案 1 :(得分:0)
只是在这里猜测,但无论函数调用此代码,都不会传入实际的VB Date
,并且由于您没有使用ByVal
限定参数,VB会假设它是ByRef
。 (没有任何内容 - 这是你已经完成的 - 与ByRef
前缀相同。)例如,
existdate As Date
与
相同ByRef existdate As Date
但与
大不相同ByVal existdate As Date
您可以尝试制作参数ByVal
。或者您可以将参数类型更改为Variant(这实际上是Cell的值,以及我猜测您实际传入的内容)。
尝试将方法签名更改为:
Function DifferenceInYears(ByVal existdate As Date, ByVal estimdate As Date) As Double
......或者这个:
Function DifferenceInYears(existdate As Variant, estimdate As Variant) As Double
你可能不得不在函数内部或外部进行一些投射,但这应该让你更接近并解决你的By ref error
问题。