By: Al Ikram Amit

In reply to Gracie.

Hi Gracie,

I see you encountered an issue with the formula provided earlier. The circular reference error occurs because the formula is attempting to reference the same range (M$4:M4) it’s currently located in, which creates a circular dependency.

To address this, I recommend using a VBA solution to find the top 5 most frequent numbers and their frequencies in the range M4:N9. VBA allows us to perform more complex calculations and avoid circular reference problems.

To use this VBA code, press Alt+F11 to open the VBA editor in Excel. Then, click Insert>> Module to insert a new module. Copy and paste the code into the module.

Sub FindTop5FrequentNumbers()
Dim dataRange As Range
Dim resultRange As Range
Dim frequencyRange As Range
Dim dict As Object
Dim cell As Range
Dim i As Integer
Dim keyArray As Variant
' Set the range that contains your sample data (E2:I57)
Set dataRange = ThisWorkbook.Worksheets("Sheet1").Range("E2:I57") ' Adjust the sheet name and range as per your data
' Set the range where you want to output the top 5 most frequent numbers (M4:M9)
Set resultRange = ThisWorkbook.Worksheets("Sheet1").Range("M4:M9") ' Adjust the sheet name and range as per your choice
' Set the range where you want to output the corresponding frequencies (N4:N9)
Set frequencyRange = ThisWorkbook.Worksheets("Sheet1").Range("N4:N9") ' Adjust the sheet name and range as per your choice
' Create a dictionary to store the frequencies of each number
Set dict = CreateObject("Scripting.Dictionary")
' Loop through each cell in the data range to count the occurrences of each number
For Each cell In dataRange
If IsNumeric(cell.Value) Then
If dict.Exists(cell.Value) Then
dict(cell.Value) = dict(cell.Value) + 1
Else
dict.Add cell.Value, 1
End If
End If
Next cell
' Convert the dictionary keys (numbers) to an array
keyArray = dict.keys
' Sort the array based on the frequencies in descending order
For i = LBound(keyArray) To UBound(keyArray) - 1
For j = i + 1 To UBound(keyArray)
If dict(keyArray(j)) > dict(keyArray(i)) Then
' Swap elements
temp = keyArray(i)
keyArray(i) = keyArray(j)
keyArray(j) = temp
End If
Next j
Next i
' Output the top 5 most frequent numbers and their frequencies to the result and frequency ranges
For i = 1 To 5
If i <= UBound(keyArray) + 1 Then
resultRange.Cells(i, 1).Value = keyArray(i - 1)
frequencyRange.Cells(i, 1).Value = dict(keyArray(i - 1))
Else
resultRange.Cells(i, 1).Value = ""
frequencyRange.Cells(i, 1).Value = ""
End If
Next i
End Sub

This VBA code will find the top 5 most frequent numbers in the data range E2:I57 and display them in the range M4:M9 and their corresponding frequencies in N4:N9. Remember to adjust the sheet name(We have used the sheet name “Sheet1“) and range references in the code are matched with your data.

If you have any further questions or need more assistance, feel free to ask.

Best regards,
Al Ikram Amit
Team ExcelDemy