首页 > 解决方案 > 从excel中的单元格计算Unqiue值

问题描述

我在单元格 A2 中有一个值为India,China,India Australia. 我希望 Cell B2 的结果为India,China,Australia.

注意我想要一个公式来从不在单元格范围内的单个单元格中找到唯一值。既然回复了这么多,countif就可以不计其数了。我不想要这样的事情,我希望计算公式以仅从单个单元格中找到唯一值。
请清楚地查看我的问题并提出答案。

标签: excel

解决方案


VBA 不同的 UDF

这是一个用户定义的公式,用于查找一串单词中的不同单词。

  • 唯一的单词分隔符是逗号和/或空格。

放置在标准 VBA 模块中

  • 不是类模块,也不是工作表模块。
  • 添加到现有模块或创建新模块。

使用该函数的方式与使用其他单元格公式函数的方式相同。

  • =Distinct("a,a,b,c, d e f f f")
    • 输出a, b, c, d, e, f
  • A1= Apples, App Pear Apples Pear Bees,B1=Distinct(A1)
    • 输出Apples, App, Pear, Bees

VBA 代码

Public Function Distinct(ByVal s As String) As String
    Dim found As Boolean
    Dim f As Variant
    Dim w As Variant
    Dim a() As String
    a = Split("") 'empty array
    For Each w In Split(WorksheetFunction.Trim(Replace(s, ",", " ")), " ")
        found = False
        For Each f In a
            If f = w Then found = True
        Next f
        If Not found Then
            ReDim Preserve a(UBound(a) + 1)
            a(UBound(a)) = w
        End If
    Next w
    Distinct = Join(a, ", ") ' Change to "," to remove space in output.
End Function

可以使用以下公式找到不同的字数:
=IF( Distinct(A1)="", 0, LEN( Distinct(A1)) - LEN( SUBSTITUTE( Distinct(A1), ",", "")) + 1)
计数逗号(并忽略空格),因此即使将 VBA 代码修改为 output ,它仍然有效a,b,c


推荐阅读