Function to count distinct values in a column range

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

    First Steps:
    Add Option Explicit to the header of all your modules. It will capture the difference between OneVariable and OneVarlable.
    Make your variables meaningful - will you know what x and i were for next time you look at this code?

    Your options for the count are

    1. user the worksheet function
    2. save the values, and only count those that don't match previous values

    Using the worksheet function,

    Option Explicit
    
    Function CountUnique(dataRange As Range) As Long
    Dim CheckCell
    Dim Counter As Double
    Counter = 0
    
    For Each CheckCell In dataRange.Cells
        Counter = Counter + (1 / (WorksheetFunction.CountIf(dataRange, CheckCell.Value)))
    Next
    ' Finally, set your function name equal to the Counter, 
    '   so it knows what to return to Excel
    CountUnique = Counter
    End Function
    

    Using the keeping track

    ...
    ' check out scripting dictionaries
    ' much more advanced - Keep it simple for now
    ...
    

提交回复
热议问题