我在运行下面的代码时出现问题,代码是计算两个日期数组之间的差异,值由行(CHR(10)
)分隔,例如在单元格A1
中有以下日期
A1
12/12/2012
11/12/2021
7/8/2015
9/4/2014
B1
12/12/2012
11/12/2021
7/8/2015
9/4/2014
C1
2D
1D
4D
10D
在D1
中的我在模块1中调用函数,如下所示
=calcSumDurations(A1,B1,C1)
它将始终返回0
当我尝试跟踪代码时,它只会进入for循环一次,甚至比intmax = 3
或4
或40
在某些情况下,我尝试过,因为,foreach,没有工作。
Function calcSumDurations(dateFrom, dateTo, dateDuration As String)
Dim intmax, intSum, i, intError As Integer
Dim varDateFrom, varDateTo, varDateDuration As Variant
intSum = 0
intmax = -1
i = 0
intError = 0
varDateFrom = Split(dateFrom, Chr(10))
varDateTo = Split(dateTo, Chr(10))
varDateDuration = Split(dateDuration, Chr(10))
intmax = UBound(varDateFrom)
If UBound(varDateFrom) = UBound(varDateTo) Then ' both are same lenght
If intmax >= 0 Then ' more than one line
For i = 0 To intmax
'While i < intmax
MsgBox (i)
If CInt(CDate(varDateTo(i))) >= CDate(varDateFrom(i)) Then 'check dates are more
If testDate(CStr(varDateTo(i))) And testDate(CStr(varDateFrom(i))) Then
intDuration = Abs(CInt(CDate(varDateTo(i)) - CDate(varDateFrom(i)))) + 1
intSum = intSum + intDuration
'strRes = strRes & CStr(intDuration) & Chr(10)
Else
intError = 1
'Exit For
End If
Else
intError = 2
End If
Next i
End If
Else
intError = 3
End If
calcSumDurations = intSum
End Function
答案 0 :(得分:1)
问题在于这行代码:
If CInt(CDate(varDateTo(i))) >= CDate(varDateFrom(i)) Then
一个整数太小而无法保存日期值并导致溢出异常。我不确定为什么你会尝试将其转换为整数,因为如果你这样做,比较肯定不会有效。
试试这个:
If CDate(varDateTo(i)) >= CDate(varDateFrom(i)) Then
它至少会开始越过循环。
我还定义了你希望函数返回的内容
Function calcSumDurations(dateFrom As String, dateTo As String, dateDuration As String) As Long