Reputation: 105
I am pretty new to Excel and VBA, but I was trying to make a function that would provide this result.
A B
-----------
1 | A | 1 |
2 | B | 2 | =TotalItems("A", A1:A4, B1:B4)
3 | C | 3 | =5
4 | A | 4 |
-----------
It searches through an array to find all occurrences, and then sums up the corresponding values in another array. I'm not sure if there is already a function to do this, but I tried creating one. Here's the code:
Function TotalItems(itemToFind, itemsToReference, resultArr)
Dim i As Integer
Dim total As Double
Dim r As Integer
For i = 1 To UBound(itemsToReference)
If StrComp(itemToFind, itemsToReference(i)) = 0 Then
total = total + CDbl(resultArr(i))
End If
Next i
TotalItems = total
End Function
It returns #VALUE!
whenever I run it. I'm not sure what the problem is, and all help will be appreciated.
Upvotes: 0
Views: 481
Reputation: 96753
You are passing Ranges
, not arrays, so:
Function TotalItems(itemToFind As String, itemsToReference As Range, resultArr As Range) As Long
Dim i As Long, rng As Range
Dim total As Long
For i = 1 To (itemsToReference.Rows.Count)
If StrComp(itemToFind, itemsToReference(i, 1)) = 0 Then
total = total + CLng(resultArr(i, 1))
End If
Next i
TotalItems = total
End Function
(based on your example, I DIM
ed Long
rather than Double
)
(note I index the ranges just like 2-D arrays)
In a worksheet cell, you could use:
=SUMPRODUCT(--(A1:A4="A")*(B1:B4))
Upvotes: 1