循环不工作在UDF函数Excel VBA?

我有一个运行下面的代码的问题,代码是计算两个date数组之间的差异,值是由线运输( CHR(10) ),例如在单元格A1我有以下date

 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 ,或者在某些情况下是440 ,我尝试了while,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 

问题在于这行代码:

 If CInt(CDate(varDateTo(i))) >= CDate(varDateFrom(i)) Then 

一个整数太小,不能保存date值,并导致溢出exception。 我不知道为什么你试图把它转换成一个整数,因为如果你这样做,比较将不起作用。

尝试这个:

 If CDate(varDateTo(i)) >= CDate(varDateFrom(i)) Then 

它至less会开始通过循环。

我也要定义你想要的函数返回

 Function calcSumDurations(dateFrom As String, dateTo As String, dateDuration As String) As Long