vba get unique values from array
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Getting unique values from an array is a common VBA task in reporting, import cleanup, and worksheet automation. The most practical solution is usually Scripting.Dictionary, because it gives fast existence checks and a simple way to preserve first-seen order. Other patterns exist, but most of them are either slower or more awkward than a dictionary-based approach.
The standard solution: Scripting.Dictionary
The basic idea is straightforward: loop through the array, add each value as a dictionary key, and ignore keys that already exist.
This returns A, B, C in the order they first appeared. That ordering is often exactly what you want in Excel automation.
Case-insensitive uniqueness for text
If your array contains strings and "A" should be treated the same as "a", set the dictionary compare mode before you start inserting values.
Without CompareMode, VBA treats differently cased strings as distinct keys. That may be correct for IDs, but usually not for user-entered text.
Handle arrays coming from worksheet ranges
One subtle detail is that arrays built with Array(...) are one-dimensional, but values read from a worksheet range are usually two-dimensional and one-based. If your source is a single worksheet column, loop over the first dimension explicitly.
This matters because code written for a one-dimensional array will fail if you feed it a range value directly.
Why Collection is a weaker fallback
You may also see a Collection pattern that uses On Error Resume Next to ignore duplicates. It works, but it is less explicit and harder to maintain.
That style depends on duplicate-key errors for normal control flow. A dictionary is clearer because duplicate detection is an ordinary Exists check.
Common Pitfalls
The most common mistake is forgetting what kind of array you have. A worksheet range usually gives you a two-dimensional variant array, not the one-dimensional shape returned by Array(...).
Another issue is ignoring case-sensitivity requirements. If the business rule says "NY" and "ny" are the same value, set CompareMode before adding keys.
Mixed data types can also surprise you. Numeric 1 and string "1" are not necessarily the same key unless you normalize the values yourself.
Finally, if you use Collection plus On Error Resume Next, always restore normal error handling afterward.
Summary
- In VBA,
Scripting.Dictionaryis usually the cleanest way to get unique values from an array. - Add each unseen value as a dictionary key and return
dict.Keys. - Set
CompareModewhen text uniqueness should ignore case. - Treat worksheet range arrays differently from one-dimensional arrays built in code.
- Prefer explicit dictionary logic over
Collectionplus error-driven duplicate detection.

