为什么这个UDF不正确地添加数字?

时间:2017-07-12 22:05:57

标签: excel-vba user-defined-functions excel-2011 vba excel

我无法弄清楚为什么这个UDF不能一致地添加数字。我为了说明目的对输出进行了颜色编码。它准确地添加了所有内容,但由于某种原因,它不想添加应该等于64的4个数字,而是输出46.5,但没有任何数字的组合出现到46.5。

enter image description here

这是我正在使用的UDF。

    Function TEXTJOINSUM(delim As String, skipblank As Boolean, arr)
Dim d As Long
Dim c As Long
Dim arr2()
Dim t As Long, y As Long
t = -1
y = -1
If TypeName(arr) = "Range" Then
    arr2 = arr.Value
Else
    arr2 = arr
End If
On Error Resume Next
t = UBound(arr2, 2)
y = UBound(arr2, 1)
On Error GoTo 0

If t >= 0 And y >= 0 Then
    For c = LBound(arr2, 1) To UBound(arr2, 1)
        For d = LBound(arr2, 1) To UBound(arr2, 2)
            If arr2(c, d) <> "" Or Not skipblank Then
                TEXTJOINSUM = TEXTJOINSUM & arr2(c, d) & delim
            End If
        Next d
    Next c
Else
    For c = LBound(arr2) To UBound(arr2)
        If arr2(c) <> "" Or Not skipblank Then
            TEXTJOINSUM = TEXTJOINSUM & arr2(c) & delim
        End If
    Next c
End If
    TEXTJOINSUM = Left(TEXTJOINSUM, Len(TEXTJOINSUM) - Len(delim))
    'add the below loop to add each number together
    Dim total As Double
    Dim txtPart
    For Each txtPart In Split(TEXTJOINSUM, delim)
        total = total + CDbl(txtPart)

    Next txtPart
    TEXTJOINSUM = total
End Function

1 个答案:

答案 0 :(得分:2)

不需要复杂的UDF,请使用SUMIFS():

=SUMIFS(C:C,A:A,E2,B:B,F2)

enter image description here