Excel – unique count of values in a cell separated by comma in excel

microsoft excelmicrosoft-excel-2010

How do I get the unique count of values in a cell separated by comma in excel?

For example: cell B13 has the value

1,1,2,3,7,1

Using the below formula we get the count of values separated by , as 6.

=1+LEN(B13)-LEN(SUBSTITUTE(B13,";",""))

But I want to count the unique values in the cell B13, which is 4. Can someone help me achieve this?

Note: This question is similar to How can I count unique comma-separated values in Excel 2010. However, this is a special, restrictive case (the values are only single digits), which allows solutions that would not apply to the other question.

Best Answer

Install the following User Defined Function (UDF) in a standard module:

Public Function CountUnique(r As Range) As Long
    Dim c As Collection
    Set c = New Collection
    ary = Split(r.Text, ",")
    On Error Resume Next
    For Each a In ary
        c.Add a, CStr(a)
        If Err.Number = 0 Then
            CountUnique = CountUnique + 1
        Else
            Err.Number = 0
        End If
    Next a
    On Error GoTo 0
End Function

User Defined Functions (UDFs) are very easy to install and use:

  1. ALT-F11 brings up the VBE window
  2. ALT-I ALT-M opens a fresh module
  3. paste the stuff in and close the VBE window

If you save the workbook, the UDF will be saved with it. If you are using a version of Excel later then 2003, you must save the file as .xlsm rather than .xlsx

To remove the UDF:

  1. bring up the VBE window as above
  2. clear the code out
  3. close the VBE window

To use the UDF from Excel:

=CountUnique(A1)

To learn more about macros in general, see:

http://www.mvps.org/dmcritchie/excel/getstarted.htm

and

http://msdn.microsoft.com/en-us/library/ee814735(v=office.14).aspx

and for specifics on UDFs, see:

http://www.cpearson.com/excel/WritingFunctionsInVBA.aspx

Macros must be enabled for this to work!

For example:

enter image description here

Related Question