Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate unique values into a VBA array from Excel

Tags:

Can anyone give me VBA code that will take a range (row or column) from an Excel sheet and populate a list/array with the unique values, i.e.:

table
table
chair
table
stool
stool
stool
chair

when the macro runs would create an array some thing like:

fur[0]=table
fur[1]=chair
fur[2]=stool
like image 957
DevilWAH Avatar asked May 04 '11 21:05

DevilWAH


People also ask

How do I get unique values from an Excel spreadsheet?

In Excel, there are several ways to filter for unique values—or remove duplicate values: To filter for unique values, click Data > Sort & Filter > Advanced. To remove duplicate values, click Data > Data Tools > Remove Duplicates.

What is array variant in Excel VBA?

Arrays are a variant type variable that you can use in VBA coding to store a list of data. Think of it as a mini-spreadsheet inside of a single variable. You store data into an array by referring to a reference number that corresponds with the location that the piece of data is positioned in.

How do I remove duplicates in Excel VBA?

VBA Remove duplicates – Example #1Step 1: Start the sub procedure by giving a Macro code name. Step 2: Mention the range of data by using the VBA Range object. Step 3: After mentioning the range access VBA “RemoveDuplicates” method. Step 4: First argument in which column we need to remove the duplicate values.


1 Answers

Sub GetUniqueAndCount()

    Dim d As Object, c As Range, k, tmp As String

    Set d = CreateObject("scripting.dictionary")
    For Each c In Selection
        tmp = Trim(c.Value)
        If Len(tmp) > 0 Then d(tmp) = d(tmp) + 1
    Next c

    For Each k In d.keys
        Debug.Print k, d(k)
    Next k

End Sub
like image 57
Tim Williams Avatar answered Oct 24 '22 18:10

Tim Williams