Find most frequently occuring text in range that consist of multiple rows and colums

后端 未结 2 480
栀梦
栀梦 2021-01-22 22:33

My question is closely related to the following topics:

  • Excel: Find most frequent occurring value in a range?
  • https://exceljet.net/formula/most-frequentl
2条回答
  •  滥情空心
    2021-01-22 23:28

    You could try using a UDF. This returns a single value or a comma separated list depending on how many ties there are. I can update for more than 2 columns if required.

    Option Explicit
    
    Public Sub Test()
        Dim rng As Range
        Set rng = [D2:E7]
    
        Debug.Print MaxRepeating(rng)
    End Sub
    
    Public Function MaxRepeating(ByVal rng As Range) As String
        Dim arr(), outputArr(), i As Long, counter As Long, dict As Object, maxValue As Long
        Set dict = CreateObject("Scripting.Dictionary")
        counter = 1
        arr = rng.Value
        ReDim outputArr(1 To UBound(arr, 1) + UBound(arr, 2))
    
        For i = LBound(arr, 1) To UBound(arr, 1)
            dict(arr(i, 1)) = dict(arr(i, 1)) + 1
            dict(arr(i, 2)) = dict(arr(i, 2)) + 1
        Next
    
        For i = LBound(arr, 1) To UBound(arr, 1)
            If dict(arr(i, 1)) > maxValue Then maxValue = dict(arr(i, 1))
            If dict(arr(i, 2)) > maxValue Then maxValue = dict(arr(i, 2))
        Next
    
        For i = LBound(arr, 1) To UBound(arr, 1)
            If dict(arr(i, 1)) = maxValue Then
                If IsError(Application.Match(arr(i, 1), outputArr, 0)) Then
                    outputArr(counter) = arr(i, 1)
                    counter = counter + 1
                End If
            End If
            If dict(arr(i, 2)) = maxValue Then
                If IsError(Application.Match(arr(i, 2), outputArr, 0)) Then
                    outputArr(counter) = arr(i, 2)
                    counter = counter + 1
                End If
            End If
        Next
        ReDim Preserve outputArr(1 To counter - 1)
        Select Case UBound(outputArr)
        Case 1
            MaxRepeating = outputArr(1)
        Case Else
            MaxRepeating = Join(outputArr, ",")
        End Select
    End Function
    

    In sheet:

提交回复
热议问题