Function to count distinct values in a column range

后端 未结 7 1897
孤街浪徒
孤街浪徒 2021-01-06 19:35

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 | |-----

7条回答
  •  粉色の甜心
    2021-01-06 19:55

    There are (of course) other ways this could be done with VBA.

    Public Function CountDistinct(rng As Range) As Long
      Dim i As Long
      Dim Cnt As Double
      Cnt = 0
      For i = 1 To rng.Rows.Count
        Cnt = Cnt + 1 / WorksheetFunction.CountIf(rng, rng(i, 1))
      Next i
      CountDistinct = CLng(Cnt)
    End Function
    

提交回复
热议问题