在基于用户的选择中查找所有不同的值 - Excel VBA

时间:2014-01-16 18:22:44

标签: excel vba excel-vba selection distinct

有一种快速简便的方法可以在Excel中使用VBA选择给定选择中的所有不同值吗?

0 | we | 0
--+----+--
we| 0  | 1

- >结果应为{0,we,1}

非常感谢提前

3 个答案:

答案 0 :(得分:2)

尝试一下:

Sub Distinct()
    Dim c As Collection
    Set c = New Collection
    Dim r As Range
    Dim dis As Range
    Set dis = Nothing
    For Each r In Selection
        If r.Value <> "" Then
            On Error Resume Next
            c.Add r.Value, CStr(r.Value)
            If Err.Number = 0 Then
                If dis Is Nothing Then
                    Set dis = r
                Else
                    Set dis = Union(dis, r)
                End If
            End If
            Err.Number = 0
            On Error GoTo 0
        End If
    Next r
dis.Select
End Sub

答案 1 :(得分:2)

顺便说一句,我找到了另一种解决方案:

Option Explicit

Public Sub Test()
    Dim cell As Object
    Dim d As Object

    Set d = CreateObject("Scripting.Dictionary")    
    For Each cell In Selection
        d(cell.Value) = 1
    Next cell

    MsgBox d.count & " unique item(s) in selection (" & Join(d.Keys, ",") & ")"
End Sub

答案 2 :(得分:1)

另一种方法是创建用户功能。以下函数将返回一个行数组,其中包含选择中的所有不同值。

Function ReturnDistinct(InpRng)
    Dim Cell As Range
    Dim i As Integer
    Dim DistCol As New Collection
    Dim DistArr()

    If TypeName(InpRng) <> "Range" Then Exit Function

    'Add all distinct values to collection
    For Each Cell In InpRng
        On Error Resume Next
        DistCol.Add Cell.Value, CStr(Cell.Value)
        On Error GoTo 0
    Next Cell

    'Write collection to array
    ReDim DistArr(1 To DistCol.Count)
    For i = 1 To DistCol.Count Step 1
        DistArr(i) = DistCol.Item(i)
    Next i

    ReturnDistinct = DistArr
End Function

代码利用了这样一个事实,即您只能向集合中添加不同的值。否则会返回错误。

通过在至少足以包含不同值的范围内使用此函数,它将列出输入范围中的不同值。在处理应返回矩阵的函数时,请记住使用 Ctrl + Shift + 输入

enter image description here