View Single Post
  #5   Report Post  
Posted to microsoft.public.excel.programming
John Coleman John Coleman is offline
external usenet poster
 
Posts: 274
Default Count duplicates in an array?


quartz wrote:
I am using Office 2003 on Windows XP.

I need to be able to count the number of each item in a single element
array, then write out the counts.

For example, if the array contains:
Red, Blue, Red, Orange, Orange, Red, Green, Blue

My result would be:
A1: Red B1: 3
A2: Blue B2: 2
A3: Orange B3: 2
A4: Green B4: 1

If anyone has a function to which I could pass my array to output the counts
or could share some code I could adapt it would be most appreciated.

Thanks much in advance.


If you include a reference to the Scripting Runtime Library (which is
included in XP) you can use the dictionary object:

Sub CountDuplicates(A As Variant)
'needs to include a reference to Microsoft Scripting Runtime
'go to Tools/Refrences

Dim D As Dictionary
Dim i As Long, key As Variant

Set D = New Dictionary
For i = LBound(A) To UBound(A)
key = A(i)
If D.Exists(key) Then
D.Item(key) = D.Item(key) + 1
Else
D.Add key, 1
End If
Next i
i = 0
For Each key In D.Keys
Range("A1").Offset(i).Value = key
Range("B1").Offset(i).Value = D.Item(key)
i = i + 1
Next key
End Sub

Hope that helps

-John Coleman