逗号分隔单元格的唯一计数

时间:2019-02-22 21:46:19

标签: excel excel-formula

说我有一个包含以下内容的单元格:[A, B, C, B, A]。如何获得唯一值及其计数?例如A = 2B = 2C = 1

1 个答案:

答案 0 :(得分:0)

选择包含数据的单元格并运行此简短的VBA宏:

Sub WhatsInIt()
    Dim s As String, arr
    Dim c As Collection, a
    Dim i As Long, msg As String

    Set c = New Collection
    msg = ""
    s = ActiveCell.Text
    s = Mid(s, 2, Len(s) - 2)

    arr = Split(s, ",")
    On Error Resume Next
        For Each a In arr
            c.Add a, CStr(a)
        Next a
    On Error GoTo 0

    For i = 1 To c.Count
        msg = msg & vbCrLf & c.Item(i) & vbTab & aCount(c.Item(i), arr)
    Next i

    MsgBox msg
End Sub


Public Function aCount(st As String, ary As Variant) As Long
    Dim ar
    aCount = 0
    For Each ar In ary
        If ar = st Then aCount = aCount + 1
    Next ar
End Function

enter image description here

EDIT#1:

此版本将结果放入单元格中

Sub WhatsInIt2()
    Dim s As String, arr
    Dim c As Collection, a
    Dim i As Long, msg As String

    Set c = New Collection
    msg = ""
    s = ActiveCell.Text
    s = Mid(s, 2, Len(s) - 2)

    arr = Split(s, ",")
    On Error Resume Next
        For Each a In arr
            c.Add a, CStr(a)
        Next a
    On Error GoTo 0

    With ActiveCell
        For i = 1 To c.Count
            .Offset(i - 1, 1).Value = c.Item(i)
            .Offset(i - 1, 2).Value = aCount(c.Item(i), arr)
        Next i
    End With

End Sub

Public Function aCount(st As String, ary As Variant) As Long
    Dim ar
    aCount = 0
    For Each ar In ary
        If ar = st Then aCount = aCount + 1
    Next ar
End Function

(aCount()函数不变)

相关问题