我需要计算Excel中单个单元格中唯一字符串的数量。
例如,
"苹果梨梨葡萄"将是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
答案 0 :(得分:1)
您可以使用字典来实现结果:
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库的引用
答案 1 :(得分: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