0 votes
in VBA by Expert (798 points)

Hello everyone

In the code I expect to get the unique items in range (A1:A7) to be 3

The values in the range are A, B, C, A, B.C, a

Sub Test()
    Dim v, dic As Object
    Set dic = CreateObject("Scripting.Dictionary")
    
    For Each v In Range("A1:A" & Cells(Rows.Count, 1).End(xlUp).Row)
        If Not dic.Exists(v) Then dic.Add v, v
    Next v
    
    MsgBox "Unique Count: " & dic.Count
End Sub

I got the result 7 not 3 or even 4 .. How can I control the case sensitive and also how to get the number of unqiue items?

3 Answers

+1 vote
by Skilled (376 points)
selected by
 
Best answer

Try this:

Sub Test()
    Dim v As Range, dic As Object
    Set dic = CreateObject("Scripting.Dictionary")
    
    For Each v In Range("A1:A" & Cells(Rows.Count, 1).End(xlUp).Row)
        If Not dic.Exists(v.Value) Then dic.Add v.Value, v.Value
    Next v
    
    MsgBox "Unique Count: " & dic.Count
End Sub

 

by Expert (798 points)

Thank you very much JWoolley 

As I have noticed, you have declared v as range instead of Variant and this worked ..

So you inspired me to modify the original code in this line

For Each v In Range("A1:A" & Cells(Rows.Count, 1).End(xlUp).Row).Value

and this worked fine instead of declaring the v as Range ..

Thanks a lot for awesome help

+2 votes
by Beginner (8 points)
Sub Unique_Value_Using_Dictionary_Object()
    'prakash b bajaj
    Dim it, y
    With CreateObject("scripting.dictionary")
        .CompareMode = 1: ' with comparemode = 0 it will print 8 values
        For Each it In Array("aa1", "AA1", "Aa1", "aA1", "bb1", "BB1", "Bb1", "bB1")
            y = .Item(it)
        Next

        Debug.Print .Count ' 2 unique keys

        Debug.Print Join(.Keys, vbLf)
    End With
End Sub
by Expert (798 points)
Thanks a lot Prakash for sharing.
+1 vote
by Beginner (16 points)

This worksheet formula will return 3 for your range

=SUMPRODUCT(1/COUNTIF(A1:A7,A1:A7))

 

Welcome to wellsr Q&A
wellsr Q&A is the VBA and Python programming community that rewards you for learning how to code.

Getting Started
Register
VBA Cheat Sheets (On Sale Now)

Earn free prizes for asking VBA and Python questions and for answering questions asked by others in our community.

Looking for something else? Hire our professional VBA Help, instead.

What makes us different?
Our points system rewards you with a chance for free gifts based on the quality of your questions and answers. All you have to do is post and you could get rewarded, like these members:

ParserMonster $25 Amazon Gift Card
Hightree $10 Amazon Gift Card
Thales1 $10 Amazon Gift Card
runfunke $10 Amazon Gift Card
coolag $10 Amazon Gift Card
Siew Hun $10 Amazon Gift Card

So, why don't you join us? It really is an encouraging way to motivate members in our VBA and Python community.

Register

For more programming tips visit the VBA Tutorials Blog and the Python Tutorials Blog.

...