为什么此 UDF 不一致地正确添加数字?
Why is this UDF inconsistently adding numbers properly?
我不明白为什么这个 UDF 不能始终如一地添加数字。为了便于说明,我对输出进行了颜色编码。它准确地添加了所有内容,但出于某种原因,它不想添加应该等于 64 的 4 个数字,而是输出 46.5,但没有任何数字的组合得出 46.5。
这是我正在使用的 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
不需要复杂的UDF,使用SUMIFS():
=SUMIFS(C:C,A:A,E2,B:B,F2)
我不明白为什么这个 UDF 不能始终如一地添加数字。为了便于说明,我对输出进行了颜色编码。它准确地添加了所有内容,但出于某种原因,它不想添加应该等于 64 的 4 个数字,而是输出 46.5,但没有任何数字的组合得出 46.5。
这是我正在使用的 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
不需要复杂的UDF,使用SUMIFS():
=SUMIFS(C:C,A:A,E2,B:B,F2)