I am attempting to create a function in VBA that, when given a range of values, will return a Count Distinct of those values. For example:
| Column A |
|-----
First Steps:
Add Option Explicit
to the header of all your modules. It will capture the difference between OneVariable
and OneVarlable
.
Make your variables meaningful - will you know what x and i were for next time you look at this code?
Your options for the count are
Using the worksheet function,
Option Explicit
Function CountUnique(dataRange As Range) As Long
Dim CheckCell
Dim Counter As Double
Counter = 0
For Each CheckCell In dataRange.Cells
Counter = Counter + (1 / (WorksheetFunction.CountIf(dataRange, CheckCell.Value)))
Next
' Finally, set your function name equal to the Counter,
' so it knows what to return to Excel
CountUnique = Counter
End Function
Using the keeping track
...
' check out scripting dictionaries
' much more advanced - Keep it simple for now
...