Determine the most frequent item in an array.

JohnSeito

Active Member
Joined
Nov 19, 2007
Messages
390
Hello,

Does anyone have a readily code or function that determines the most frequent item in the array ?
I think it will take me a while to come up with it.

I created an array

Dim ar(50)

It stored up to 50 items, sometimes the items can all be the same, other times it could be different.
I just want to find the item that stored in there the most frequent time.
This array can be 50 or 60 or 100, I just decided to set it to 50 but maybe I will change this to more if I decided I needed to for some reason.
Thanks
 

Excel Facts

What is =ROMAN(40) in Excel?
The Roman numeral for 40 is XL. Bill "MrExcel" Jelen's 40th book was called MrExcel XL.
My assumption is that there could be more than one item that occurs the most number of times. See if you can use this code snippet. At the end of this snippet, the variable ItemsList should contain the most frequent item(s)

Code:
Dim i As Long, maxVal As Long
Dim d As Object
Dim ItemsList As String

Set d = CreateObject("Scripting.Dictionary")
For i = LBound(ar) To UBound(ar)
  If Not IsEmpty(ar(i)) Then d(ar(i)) = d(ar(i)) + 1
Next i

For i = 1 To d.Count
  If d.Items()(i - 1) > maxVal Then
    maxVal = d.Items()(i - 1)
    ItemsList = d.Keys()(i - 1)
  ElseIf d.Items()(i - 1) = maxVal Then
    ItemsList = ItemsList & ", " & d.Keys()(i - 1)
  End If
Next i
 
Upvote 0

Forum statistics

Threads
1,215,543
Messages
6,125,429
Members
449,223
Latest member
Narrian

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top