Google Exceltip.com
Account Icon
Shopping Cart
CheckOut

» Count unique values using VBA in Microsoft Excel

VBA macro tip contributed by Erlandsen Data Consulting offering Microsoft Excel Application development, template customization, support and training solutions
The custom function below counts the unique values only from a given range.
This function uses the fact that a collection can only hold items with unique identifications keys.
If you try to add an item with a key that already exists in the collection, an error will occur.
Function CountUniqueValues(InputRange As Range) As Long
Dim cl As Range, UniqueValues As New Collection
    Application.Volatile
    On Error Resume Next ' ignore any errors
    For Each cl In InputRange
        UniqueValues.Add cl.Value, CStr(cl.Value) ' add the unique item
    Next cl
    On Error GoTo 0
    CountUniqueValues = UniqueValues.Count
End Function


Example:
=CountUniqueValues(A1:A100) will count the unique values in the range A1:A100.
Rate this tip
12 34 5
  RATING: 4.06
  VIEWS: 45533
  No comments have been submitted.


REGISTERED USERS click here to post comments


GUESTSclick here to Register
Name
Comment Title
Comments


Terms and Conditions of use
The applications/code on this site are distributed as is and without warranties or liability. In no event shall the owner of the copyrights, or the authors of the applications/code be liable for any loss of profit, any problems or any damage resulting from the use or evaluation of the applications/code.

Copyright © 2003 ExcelTip.com
Microsoft, Microsoft Excel is a U.S. registered trademark of Microsoft Corporation