Function to count distinct values in a column range

后端 未结 7 1841
孤街浪徒
孤街浪徒 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:56

    Way late to the party, but I thought I would put in another VBA option that does not require adding a reference.

    In addition this touches on a neat function of excel VBA that I wish I had learn much earlier.

    My solution to this uses the Collection object in order to find distinct values.

    Option Explicit
    '^ As SeanC said, adding Option Explicit is a great way to prevent writing errors when starting out.
    Public Function CountDistinct(r As Range) As Long
    '' DIM = declare in memory
    
    Dim col As Collection
    Dim arr As Variant
    Dim x As Long
    Dim y As Long
    
    Set col = New Collection
    '' setting a Variant = Range will fill the Variant with a 2 dimensional array of the values of the range!
    arr = r
    '' skip the errors that are raised
    On Error Resume Next
    '' loop over all of the elements.
    '' UBound is a built in VBA Function that gives you the largest value of an array.
        For x = 1 To UBound(arr, 1)
            For y = 1 To UBound(arr, 2)
                '' try to add the value in arr to the collection
                col.Add 0, CStr(arr(x, y))
    
                '' every time the collection runs into a value it has already added,
                '' it will raise an error.
                'uncomment the below to see why we are turning off errors
                'Debug.Print Err.Number, Err.Description
    
            Next
        Next
    '' turn errors back on.
    On Error GoTo 0
    ''set the function name to the value you want the formula to return
    CountDistinct = col.Count
    '' The next parts should be handled by VBA automatically but it is good practise to explicitly clean up.
    Set col = Nothing
    Set arr = Nothing
    Set r = Nothing
    End Function
    

    I hope this helps someone down the line.

提交回复
热议问题