In Excel, I’m writing a custom function in VBA that needs to take a criteria string and criteria range like the built-in SUMIF function. Does Excel expose the functionality to test a criteria string anywhere in its API or do I have to write it myself?
In case it’s relevant, I’m writing a “CountUniquesIf” formula, that counts the unique values in a range if they meet a criterion. This is what I have so far.
Function CountUniquesIf(CondRange As Range, Criteria As String, _
Range As Range) As Long
Static dict As New Scripting.Dictionary
Dim index As Long
index = 1
For Each Cell In Range.Cells
If CondRange(index).Value = Criteria And Cell.Value <> "" Then
dict(Cell.Value) = Empty
End If
index = index + 1
Next Cell
CountUniquesIf = dict.Count
dict.RemoveAll
End Function
You can actually do the whole thing with just regular formulas if you want.
Please see:
http://www.officearticles.com/excel/count_unique_values_in_microsoft_excel.htm
or
http://office.microsoft.com/en-us/excel/HP030561181033.aspx
You will need to modify the formula slightly, though, to cover the “if” part of your scenario:
Remember to enter this as an array formula (paste the formula and press Ctrl-Shift-Enter instead of just Enter).
That said, I think your VBA formula is a good solution too (probably more user-friendly than creating a monster array formula every time you need this type of count).
Update
Given your clarification, I really don’t think there’s a built-in “criterion analyzer”, but I don’t think it would be too difficult to enhance your formula to cover the different possible criteria. That way, your
CountUniquesIfformula will really do what people think it does. Specifically, you could do a little parsing that checks for all the possible operators (is there anything besides “=”, “>”, “>=”, “<“, “<=”?) that could be prefixed before the value.