2

I have data like this in Excel:

Person1    A    A    B    A         C    3
Person2                                  0
Person3    A    B    C    D    E    F    6
Person4              A    A    A         1

I am trying to find a formula that replicates the number in the last cell of each row, the number of unique elements associated with that person, excluding blanks. So for example Person1 has 3 since there is A, B, and C even though there are three A's. The number of columns is fixed / the same for everyone. The values A, B, C, etc, are strings (as opposed to numerics).

Can this be done using a formula?

ashleedawg
  • 20,365
  • 9
  • 72
  • 105
user51819
  • 315
  • 5
  • 11

3 Answers3

7

This should work for you:

=SUMPRODUCT((B1:G1<>"")/COUNTIF(B1:G1,B1:G1&""))
tigeravatar
  • 26,199
  • 5
  • 30
  • 38
  • 3
    @user51819 The numerator `(B1:G1<>"")` takes each cell and checks if it's blank, if it is blank it fails the check and gets counted as a 0, otherwise 1. Then the denominator gets the total count of each element in the range. The division then applies 1/Count for each element, such that if you have 3 of one element it becomes 1/3+1/3+1/3. For example, on sample line 1, the breakdown is: 1/3+1/3+1/1+1/3+0/1+1/1 = 0.333+0.333+1+0.333+0+1 = 3 – tigeravatar Jul 25 '18 at 13:42
  • Really cool. Is there any risk of precision issues with this approach since it's working with fractions? – user51819 Jul 25 '18 at 13:45
  • 1
    @user51819 There can be, but you can wrap the formula in `ROUND` if you run into any issues with that. – tigeravatar Jul 25 '18 at 13:46
  • 2
    I prefer doing these with FREQUENCIES for that reason but COUNTIF does work surprisingly well :-) – Tom Sharpe Jul 25 '18 at 14:02
  • 2
    FRQUENCY I mean – Tom Sharpe Jul 25 '18 at 14:08
  • 1
    Plz see https://exceljet.net/formula/count-unique-text-values-in-a-range – Tom Sharpe Jul 25 '18 at 14:47
4

This is what I found:

=SUMPRODUCT(1/COUNTIF(B1:F1,B1:F1&""))

It works quite interestingly:

product

It sums the results of the countifs, and it divides each one by 1.Thus, if you have the above example, it returns 4, because it sums:

1/1 + 1/3 + 1/3 + 1/1 + 1/3 + 1/3

Vityata
  • 42,633
  • 8
  • 55
  • 100
3

An UDF to use in sheet

Public Function GetUniqueCount(ByVal rng As Range) As Long
    Dim dict As Object, currCell As Range
    Set dict = CreateObject("Scripting.Dictionary")
    For Each currCell In rng
        If Not IsEmpty(currCell) Then dict(currCell.Value) = 1
    Next currCell
    GetUniqueCount = dict.Count
End Function

In sheet use:

Sheet

QHarr
  • 83,427
  • 12
  • 54
  • 101