我正在尝试使用公式在列中显示第1、2和3个最常见的文本字符串。该公式有效,但前提是我指定一个没有空白单元格的特定范围。问题在于,通常通过在底部添加一行来更新列表,因此范围需要是动态的(或整个列,这是我要尝试的操作)。
=IFERROR(INDEX(C:C,MODE(IF(COUNTIF(U$1:U1,C:C)=0,MATCH(C:C,C:C,0)+{0,0}))),"")
任何见识都会受到赞赏。
答案 0 :(得分:0)
首先在标准模块中输入以下VBA代码:
Public Function MostCommon(rng As Range) As Variant
Dim rng2 As Range, r As Range, C As Collection, arr(), arr2
Dim cKount As Long, i As Long, Kaller As Range, HowBig As Long
Set rng2 = Intersect(rng, rng.Parent.UsedRange)
Set C = New Collection
Set Kaller = Application.Caller
For Each r In rng2
If r.Value <> "" Then
On Error Resume Next
C.Add r.Value, CStr(r.Value)
On Error GoTo 0
End If
Next r
cKount = C.Count
ReDim arr(1 To cKount, 1 To 2)
For i = 1 To cKount
arr(i, 1) = C.Item(i)
arr(i, 2) = Application.WorksheetFunction.CountIf(rng2, arr(i, 1))
Next i
Call VBA_Sort(arr)
HowBig = Application.WorksheetFunction.Max(cKount, Kaller.Rows.Count)
ReDim arr2(1 To HowBig, 1 To 2)
For i = 1 To HowBig
arr2(i, 1) = ""
arr2(i, 2) = ""
Next i
For i = 1 To cKount
arr2(i, 1) = arr(i, 1)
arr2(i, 2) = arr(i, 2)
Next i
MostCommon = arr2
End Function
Public Sub VBA_Sort(InOut())
Dim i As Long, J As Long, Low As Long, _
Hi As Long, Temp As Variant
Low = LBound(InOut, 1)
Hi = UBound(InOut, 1)
J = (Hi - Low + 1) \ 2
Do While J > 0
For i = Low To Hi - J
If InOut(i, 2) < InOut(i + J, 2) Then
Temp = InOut(i, 2)
InOut(i, 2) = InOut(i + J, 2)
InOut(i + J, 2) = Temp
Temp = InOut(i, 1)
InOut(i, 1) = InOut(i + J, 1)
InOut(i + J, 1) = Temp
End If
Next i
For i = Hi - J To Low Step -1
If InOut(i, 2) < InOut(i + J, 2) Then
Temp = InOut(i, 2)
InOut(i, 2) = InOut(i + J, 2)
InOut(i + J, 2) = Temp
Temp = InOut(i, 1)
InOut(i, 1) = InOut(i + J, 1)
InOut(i + J, 1) = Temp
End If
Next i
J = J \ 2
Loop
End Sub
然后选择一个两列的块(例如 E1 到 F50 ),并输入以下内容:
=MostCommon(C:C)
如您所见,该函数返回一个短频表,最频繁的项目位于顶部。
数组公式必须使用 Ctrl + Shift + Enter 输入,而不仅仅是 Enter 键。如果正确完成此操作,则公式将显示在公式栏中,并带有大括号。