Excel 2007 Read unique values from a range into an array

I'm trying to read unique values from an Excel 2007 named range into a VBA array,  I've figured out how to do this when reading from an access DB table but that's not an option here.

For example...

If I have a named range on Sheet1 in cells A1..A6 called Fruit
and Fruit contains:

the array should contain:
Apples, Oranges, Peaches, Kiwi

Any help would be greatly appreciated.

Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Patrick MatthewsCommented:

Must it be an array?  Arrays are tricky when it comes to distinct values; Collections and Dictionaries are much easier in that regard.

Here is a Dictionary approach:

Dim dic As Object
Dim LastR As Long
Dim Counter As Long
Dim arr As Variant

With ActiveSheet
    LastR = .Cells(.Rows.Count, "a").End(xlUp).Row
    arr = .Range(.[a2], .Cells(LastR, "a")).Value
End With

Set dic = CreateObject("Scripting.Dictionary")
dic.CompareMode = vbTextCompare 'vbBinaryCompare for case-sensitive matching

For Counter = 1 To UBound(arr, 1)
    dic.Item(arr(Counter, 1)) = arr(Counter, 1)

Open in new window

At that point, your Dictionary has the distinct values.  If you must have the array, add this at the end:

Dim DistinctValues As Variant
DistinctValues = dic.Keys

Open in new window

For more about the Dictionary class:



Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
CEB0827Author Commented:
Works perfectly, cant thank you enough, I hate working with arrays & now I have a better way to do this.
Patrick MatthewsCommented:

Glad to help!  If you have not already done so, I would really appreciate it if you could please return to my article
and click 'Yes' for the 'Was this helpful?' voting.

It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft Excel

From novice to tech pro — start learning today.