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 |
|----------|
| 1 |
| 2 |
| 3 |
| 3 |
| 3 |
| 3 |
| 4 |
| 4 |
| 5 |
| 5 |
| 6 |
Count of Rows = 11
Distinct values = 6
Here is the structure of the VBA code I'm trying to use to build a function I can call in Excel:
Function CountDistinct(dataRange As Range)
Dim x As Double
x = 0
For i = 1 To dataRange.Rows.Count
x = x + (1 / (CountIf(dataRange, dataRange(i))))
Next i
End Function
I'm completely new to VBA programming, so apologies for all of the obvious, glaring mistakes made in the code above, if it can even be called that.
I know there are other ways to arrive at the correct answer, but I'm interested in learning how to create custom Excel functions.
Also, the pseudo-logic behind my approach is as follows:
- Give the function CountDistinct a range of cells dataRange
- Loop through the range
- For each cell in the range, perform a COUNTIF on that value across the range (so in the example above, rows 3-6 would each return 4, since the number 3 appears 4 times in the range).
- For each cell in the range, add 1/(the result of step 3) to the result variable x
| Values | CountIF(Value) | 1/CountIF(Value) |
|--------|----------------|-----------------------------|
| 1 | 1 | 1 |
| 2 | 1 | 1 |
| 3 | 4 | 0.25 |
| 3 | 4 | 0.25 |
| 3 | 4 | 0.25 |
| 3 | 4 | 0.25 |
| 4 | 2 | 0.5 |
| 4 | 2 | 0.5 |
| 5 | 2 | 0.5 |
| 5 | 2 | 0.5 |
| 6 | 1 | 1 |
| | | SUM of 1/CountIF(Value) = 6 |
This will return the Count of Distinct values in column A == 6.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…