COUNT key in dictionary collection

User avatar
sal21
PlatinumLounger
Posts: 4362
Joined: 26 Apr 2010, 17:36

COUNT key in dictionary collection

Post by sal21 »

I use thi code to add key in dic:

If DIC.Exists(C) Then
X = X + 1
DIC(C) = DIC(C) + IMPORTO
Else
Y = Y + 1
DIC.Add C, IMPORTO
End If

and loop with:

Dim KEY As Variant
Dim lngValue As Long
For Each KEY In DIC.Keys
lngValue = DIC(KEY)
Debug.Print KEY & "-" & lngValue & "-" & KEY.Count
Next KEY

Set DIC = Nothing

i need to count how many times is added the sinle KEY? possible?

naturally in this line have error in & "-" & KEY.Count
Debug.Print KEY & "-" & lngValue & "-" & KEY.Count

User avatar
HansV
Administrator
Posts: 78545
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: COUNT key in dictionary collection

Post by HansV »

You'll have to create a second dictionary DIC2 to store the counts:

Code: Select all

    If DIC.Exists(C) Then
        X = X + 1
        DIC(C) = DIC(C) + IMPORTO
        DIC2(C) = DIC2(C) + 1
    Else
        Y = Y + 1
        DIC.Add C, IMPORTO
        DIC2.Add C, 1
    End If
In the loop:

Code: Select all

        Debug.Print KEY & "-" & lngValue & "-" & DIC2(KEY)
Best wishes,
Hans

User avatar
sal21
PlatinumLounger
Posts: 4362
Joined: 26 Apr 2010, 17:36

Re: COUNT key in dictionary collection

Post by sal21 »

HansV wrote:You'll have to create a second dictionary DIC2 to store the counts:

Code: Select all

    If DIC.Exists(C) Then
        X = X + 1
        DIC(C) = DIC(C) + IMPORTO
        DIC2(C) = DIC2(C) + 1
    Else
        Y = Y + 1
        DIC.Add C, IMPORTO
        DIC2.Add C, 1
    End If
In the loop:

Code: Select all

        Debug.Print KEY & "-" & lngValue & "-" & DIC2(KEY)

WORK PERFECT!

I dont remeber if i have just post a question to sort the dictionay by Key...
perphs i need to fill an Array during the first block of code?

User avatar
HansV
Administrator
Posts: 78545
Joined: 16 Jan 2010, 00:14
Status: Microsoft MVP
Location: Wageningen, The Netherlands

Re: COUNT key in dictionary collection

Post by HansV »

Best wishes,
Hans