计算单个单元格中由空格分隔的唯一string的数量

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

例如,
“苹果梨梨子葡萄”会算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 

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

 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脚本运行时库的引用即可

select单元格并运行:

 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