Devil07
Devil07

Reputation: 141

Why is this UDF inconsistently adding numbers properly?

I can't figure out why this UDF is not adding numbers consistently. I color coded the output for illustrative purposes. It adds everything accurately, but for some reason it doesn't want to add the 4 numbers which should equal 64, but instead it outputs 46.5, but there is no combination of any numbers that comes out to 46.5.

enter image description here

This is the UDF I'm using.

    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

Upvotes: 0

Views: 42

Answers (1)

Scott Craner
Scott Craner

Reputation: 152450

No need for the complicated UDF, use SUMIFS():

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

enter image description here

Upvotes: 2

Related Questions