Excel VBA: Sort a Dictionary by Key (Step by Step)
In this article
A VBA Dictionary does not keep its keys in alphabetical order, so there is no built-in "sort" method to call. To sort a Dictionary by key you copy its keys into a one-dimensional array, sort that array (with a simple loop, or by writing the keys to a worksheet range and using Excel's own Sort feature), then either read the keys back in sorted order or rebuild a new Dictionary by inserting the keys in ascending sequence. Time to allow: about 15 minutes for a reusable routine you can paste into any workbook.
What You'll Need
- Excel on Windows, with the Visual Basic Editor available (Alt+F11). The Scripting.Dictionary object is a Windows component, so this approach is for the desktop Windows version; on Excel for Mac the Dictionary class is not available through the same reference.
- A reference to Microsoft Scripting Runtime, or late binding with
CreateObject("Scripting.Dictionary"). Late binding is the safer choice for workbooks shared with other people because it needs no reference set. - A workbook saved as .xlsm or .xlsb so your macro code is kept. A plain .xlsx will discard it.
- Macro settings that allow macros to run (trusted location or a deliberate "Enable Content" click). Your organisation may restrict this; ask IT if the buttons are greyed out.
- A scratch area or a new worksheet you can write to and clear, if you choose the worksheet-sort method.
Step-by-Step
- Open the editor. Press Alt+F11, then in the Project pane right-click your workbook and choose Insert > Module. Everything below goes in that module. Menu wording can differ slightly between Excel versions and builds.
- Decide how you will build the Dictionary. Each key must be unique and each key needs an item value. For testing, write a small routine that adds four or five entries:
d.Add "banana", 3,d.Add "apple", 5,d.Add "cherry", 1and so on. Used.Exists(key)before adding if your source data might repeat a key, becauseAddon an existing key raises an error. - Pull the keys into an array. The Dictionary exposes a
Keysmethod that returns a zero-based array. Assign it to a Variant:Dim k As Variantthenk = d.Keys. At this pointk(0)is the first key you inserted, not the alphabetically first key. Confirm this with a quickDebug.Printloop so you can see the unsorted order before you change anything. - Sort the array with a simple loop. For small-to-medium sets (a few hundred keys) a bubble or insertion sort is easy to read and plenty fast. Loop
ifromLBound(k)toUBound(k) - 1, loopjfromi + 1toUBound(k), and swapk(i)andk(j)whenStrComp(k(i), k(j), vbTextCompare) > 0. UsingStrCompwithvbTextComparegives case-insensitive alphabetical order; usevbBinaryCompareif you need a strict character-code order. Use a temporary Variant for the swap. - Rebuild the Dictionary in sorted order. Create a second Dictionary with
Dim sorted As ObjectandSet sorted = CreateObject("Scripting.Dictionary"), then loop through the sorted array and add each key with its original item:sorted.Add k(i), d(k(i)). Because the Dictionary preserves insertion order, the new Dictionary now iterates alphabetically by key. Keepsorted.CompareMode = vbTextCompareif you want lookups to ignore case, matching the sort you just applied. - Alternative: let Excel do the sorting. If you already have hundreds or thousands of keys, write them to a column on a scratch sheet with a loop, write the matching values in the next column, then sort that two-column range with the worksheet's own sort (Data > Sort, or the
Range.Sortmethod in code with the keys column as the sort field). Read the rows back into your new Dictionary, then clear the scratch range. This is usually faster than a hand-written loop sort on large sets and avoids sorting bugs in your own code. - Use the sorted result. To list keys in order, loop
For Each k In sorted.Keysand write to a cell or build a string. To output into cells quickly, assignsorted.Keysstraight to a range withRange("A2").Resize(sorted.Count, 1).Value = Application.Transpose(sorted.Keys). Note thatApplication.Transposehas a length limit on very long arrays, so loop-and-write for large sets. - Test edge cases before trusting it. Add keys with mixed case ("Apple" and "apple"), numbers stored as text, and leading spaces. Run the routine and check the printed order. Then delete one entry and re-run to make sure your loop does not assume a fixed key count.
Common Mistakes
Assuming .Keys is already sorted. It is not; it reflects insertion order. Any code that relies on it being alphabetical will break the moment the source data changes.
Sorting the array but not the values. If you sort keys and then read items from the original Dictionary by key, that is fine. If you keep items in a separate parallel array and forget to swap them alongside the keys, every key ends up paired with the wrong value.
Using Application.WorksheetFunction.Small or similar on text. Worksheet sort functions work on numbers; text keys need text comparison. StrComp is the reliable choice.
Mixing compare modes. A case-insensitive sort with a case-sensitive Dictionary (or the reverse) produces a confusing result where "Apple" and "apple" sort together but look up as different keys. Set CompareMode deliberately.
Missing the Scripting reference. If you used early binding and the workbook is opened on a machine without the reference set, it fails to compile. Late binding avoids that.
Forgetting Option Explicit. Add it at the top of the module so undeclared variables are caught at compile time instead of silently becoming Empty.
Tips
- Wrap the sort in its own function that takes a Dictionary and returns a new sorted Dictionary. Then every procedure in the workbook can reuse it.
- Use
vbTextComparefor human-readable alphabetical lists andvbBinaryCompareonly when you need exact character ordering (for example, matching a sort done elsewhere). - For numeric-looking keys, decide early whether "10" should come before "9". Text sorting puts "10" first; if you need numeric order, store real numbers as keys instead of strings.
- Turn off
ScreenUpdatingwhile a routine writes to a scratch sheet, and turn it back on in an error handler so the screen does not stay frozen if something fails. - Sort on a copy. Keeping the original Dictionary intact lets you compare sorted and insertion order, which makes debugging far easier.
Troubleshooting
"Subscript out of range" when reading the array. The array from .Keys is zero-based even if your module has Option Base 1. Always use LBound and UBound rather than hard-coded 0 or 1.
"This key is already associated with an element" on Add. You are inserting a duplicate. In the rebuild loop this should not happen if your source had unique keys, so check whether the original Dictionary was built with a case-insensitive compare mode that merged entries.
Output order looks random. Check that you are looping the new Dictionary and not the old one, and that you rebuilt with Add rather than assigning items into the original.
Compile error: user-defined type not defined. You used As Dictionary without the Scripting Runtime reference. Either add the reference (Tools > References in the editor) or switch to As Object with CreateObject.
Nothing happens at all. Macros may be disabled. Save as .xlsm, place the file in a trusted location, and reopen. If the VBA project is password-protected or locked by policy, you cannot edit it without the owner's help.
If that did not work, step back and test in isolation: one module, five hard-coded keys, a Debug.Print of the sorted array. When that prints correctly, move your real data in one piece at a time.
Frequently Asked Questions
Does a VBA Dictionary sort itself?
No. It stores entries in the order you add them. Sorting requires copying the keys out and reinserting them in order.
Can I sort by value instead of key?
Yes, using the same technique: copy keys and items into a two-column array or worksheet range, sort on the item column, then rebuild the Dictionary. The loop-sort approach needs comparing d(k(i)) instead of k(i).
Why not just use a Collection?
A Collection has no Exists check and no direct key lookup by name with the same clarity. A Dictionary gives you fast key checks, which matters when deduplicating a list before sorting.
Will this work on Excel for Mac?
Not with the Scripting.Dictionary object. On Mac you would use a Collection and a sorting routine, or the worksheet sort method, instead.
How slow is a loop sort?
Negligible for a few hundred keys. For several thousand, the worksheet sort is noticeably faster and less error-prone.
Can I sort descending?
Yes, reverse the comparison in your swap condition (use < 0 instead of > 0), or rebuild by looping the sorted array from top to bottom.