【问题标题】:Count the number of unique strings, separated by spaces, in a single cell计算单个单元格中以空格分隔的唯一字符串的数量
【发布时间】:2014-12-05 19:01:47
【问题描述】:

我需要计算 Excel 中单个单元格中唯一字符串的数量。

例如,
“apple pear pear grape”将是 3
“苹果梨葡萄”将是 3
“橙橙香蕉”的计数为 2

任何可以产生此结果的公式或 VBA 代码?

编辑:我将 CountUnique 子转换为一个函数,它也可以工作

Function CountUnique(s As String)
  Dim c As Collection
  Set c = New Collection
  ary = Split(s, " ")
  On Error Resume Next
  For Each a In ary
    c.Add a, CStr(a)
  Next a
  On Error GoTo 0
  CountUnique = c.Count
End Function

【问题讨论】:

  • 我在 Google 上进行了一些搜索,但到目前为止我还没有找到任何适合这种情况的公式。
  • 我确实找到了一个计算单词的公式,但不是唯一的单词 =IF(LEN(TRIM(LV2))=0,0,LEN(TRIM(LV2))-LEN(SUBSTITUTE(LV2, " ",""))+1)

标签: excel vba


【解决方案1】:

选择单元格并运行:

Sub CountUnique()
    Dim c As Collection
    Set c = New Collection
    ary = Split(ActiveCell.Value, " ")
    On Error Resume Next
    For Each a In ary
        c.Add a, CStr(a)
    Next a
    On Error GoTo 0
    MsgBox c.Count
End Sub

【讨论】:

  • 您将如何处理单元格范围以及将代码打印在范围内每个单元格的相邻单元格中的结果?
【解决方案2】:

您可以使用字典来实现您的结果:

Sub test()
     c = CountDistinct("apple pear pear grape")
End Sub

Public Function CountDistinct(s As String)
    On Error Resume Next

    Dim hash As New Dictionary
    For Each x In Split(s, " ")
        hash.Add x, False
    Next

    CountDistinct = hash.Count
End Function

只需添加对 Microsoft Scripting Runtime 库的引用

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多