0

is there a quick and easy way to select all distinct values within a given selection in Excel with VBA?

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

-> the result should be {0,we,1}

Many thanks in advance

Tom Stevens
  • 195
  • 1
  • 1
  • 12

3 Answers3

2

Give this a try:

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
Gary's Student
  • 95,722
  • 10
  • 59
  • 99
2

by the way I've found another solution:

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
Zev Spitz
  • 13,950
  • 6
  • 64
  • 136
Tom Stevens
  • 195
  • 1
  • 1
  • 12
1

An alternative approach would be to create a user function. The following function will return a row-array with all distinct values in a selection.

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

The code takes advantage of the fact that you can only add distinct values to a collection. Otherwise it will return an error.

By using this function on a range at least big enough to contain the distinct values, it will list the distinct values from the input range. Remember to use Ctrl+Shift+Enter when working with functions that should return a matrix.

enter image description here

Netloh
  • 4,338
  • 4
  • 25
  • 38