在列中获取10个最常见的名字

时间:2018-09-07 03:40:32

标签: excel vba

我一直在努力想出一个程序,该程序能够提取列中出现的10个最常见的名称并将它们存储到数组中以供进一步使用。

1 个答案:

答案 0 :(得分:3)

将列的值收集到数组中以加快处理速度。以频率作为每个键的项转移到词典的键。工作表的“大”可以轻松找到第十大频率。删除频率较低的任何东西。

Option Explicit

Sub gfdrew()
    Dim i As Long, j As Long, arr As Variant, k As Variant, dict As Object

    Set dict = CreateObject("scripting.dictionary")

    With Worksheets("sheet6")
        arr = .Range(.Cells(2, "A"), .Cells(.Rows.Count, "A").End(xlUp)).Value2
    End With

    For i = LBound(arr, 1) To UBound(arr, 1)
        dict.Item(arr(i, 1)) = dict.Item(arr(i, 1)) + 1
    Next i

    j = Application.Large(dict.items, Application.Min(10, dict.Count))

    For Each k In dict.keys
        If dict.Item(k) < j Then dict.Remove (k)
    Next k

    arr = dict.keys

    For i = LBound(arr) To UBound(arr)
        Debug.Print arr(i)
    Next i
End Sub