Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Excel VBA: Sort a Dictionary by Value (Step-by-Step)

· 6 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

Excel VBA has no built-in method to sort a Dictionary by its values, but you can do it reliably by copying the keys and values into arrays, sorting those arrays with a simple algorithm, and then rebuilding a new Dictionary in the sorted order. This guide shows a complete, working approach you can paste into a standard module, plus the mistakes that cause blank results, type mismatches, and lost data.

What You'll Need

  • Excel on Windows or Mac with the Visual Basic Editor available (Alt+F11 on Windows, or the Developer tab).
  • A reference to the Microsoft Scripting Runtime library, or late binding using CreateObject("Scripting.Dictionary"). Early binding gives you IntelliSense; late binding avoids missing-reference errors when the workbook is opened on another machine.
  • A basic understanding of how to insert a module (Insert > Module) and run a macro.
  • Your data already loaded into a Dictionary, or a range you want to load into one.

Step-by-Step

  1. Decide on early or late binding. For early binding, open Tools > References in the Visual Basic Editor and tick Microsoft Scripting Runtime. For late binding, skip the reference and declare your variable as Object, then create it with CreateObject("Scripting.Dictionary"). Late binding is safer if the workbook will be shared, because a missing reference produces a compile error on other machines.
  2. Load your data into a Dictionary. A Dictionary stores key-value pairs. Keys must be unique; values can repeat. For example, to count occurrences of names in column A, loop through the range and use the name as the key and the count as the value. If you already have a Dictionary, skip this step.
  3. Copy the keys and values into arrays. You cannot sort a Dictionary in place, so transfer its contents. Use dict.Keys and dict.Items to return arrays, then copy them into two separate Variant arrays sized with LBound and UBound. Keep the two arrays aligned by index so key i always matches value i.
  4. Sort the arrays together. A simple bubble sort or insertion sort works for typical dictionary sizes. Compare the value array elements, and when a swap is needed, swap both the value and the matching key so the pairing stays correct. Do not sort the keys array on its own, or the values will no longer line up with their keys.
  5. Handle mixed value types. If your values are all numbers, compare numerically. If they are all text, compare with StrComp and choose binary or text comparison. If values are mixed (some numbers, some text), decide a rule first, such as converting everything to text with CStr, otherwise comparisons can behave unpredictably.
  6. Rebuild a new Dictionary in sorted order. Create a second Dictionary, then loop through the sorted arrays from lowest index to highest and add each key and value with newDict.Add keyArray(i), valueArray(i). Adding in sorted order means the new Dictionary's Keys collection is already in the order you want.
  7. Choose ascending or descending. For descending order, either reverse the comparison in the sort loop or loop through the sorted arrays from UBound down to LBound when rebuilding the new Dictionary.
  8. Output the result. Write the sorted keys and values to a worksheet range, a message box, or a collection for further processing. A quick way is to loop through newDict.Keys and write each key and its value to successive rows.
  9. Test with a small sample first. Use five or six entries with known values, including at least one duplicate value, and confirm the output order is correct before running it on a large dataset.

Common Mistakes

  • Sorting only the values. If you sort the values array without swapping the matching keys, the keys and values become mismatched and your output is wrong.
  • Assuming Dictionary preserves insertion order. The Scripting Dictionary does preserve insertion order in practice, but that is not a sorting mechanism. You still need to sort explicitly.
  • Using dict.Add with an existing key. This raises a runtime error. Use dict(key) = value to overwrite, or check dict.Exists(key) first.
  • Forgetting the reference. Early binding without the Scripting Runtime reference produces a compile error on another machine. Late binding avoids this.
  • Comparing numbers as text. Text comparison of "10" and "9" puts "10" before "9". Convert values to the correct type before comparing.
  • Ignoring empty dictionaries. Sorting code that assumes at least one item will fail on an empty Dictionary. Add a guard that exits if dict.Count = 0.

Tips

  • Write the sort as a reusable function that accepts a Dictionary and returns a new sorted Dictionary, so you can call it from any macro.
  • Use Application.ScreenUpdating = False around large output loops, then set it back to True, to keep the macro fast.
  • For large dictionaries, a bubble sort is slow. An insertion sort or a quicksort routine is noticeably faster once you have hundreds or thousands of entries.
  • Keep a parallel array of original indexes if you need to trace results back to source rows.
  • Comment your comparison rule at the top of the function so future readers know whether it sorts numerically or alphabetically.

Troubleshooting

  • Compile error: user-defined type not defined. The Scripting Runtime reference is missing. Add it via Tools > References, or switch to late binding with CreateObject.
  • Runtime error 457: This key is already associated with an element of this collection. You are adding a duplicate key. Check Exists before adding, or assign directly with dict(key) = value.
  • Output is blank. Confirm the source Dictionary actually contains items and that you are writing to the correct worksheet and starting row. Check dict.Count before and after sorting.
  • Values appear in the wrong order. Verify that keys and values were swapped together during the sort, and that the comparison type matches the data.
  • Macro runs but nothing changes. Make sure you are reading from the new sorted Dictionary, not the original one.
  • Works on one PC, fails on another. This is almost always the early-binding reference. Switch to late binding or ensure the reference is set on every machine.

Frequently Asked Questions

Can I sort a Dictionary directly in VBA?

No. The Scripting Dictionary has no Sort method. You must extract keys and values into arrays, sort them, and rebuild a new Dictionary.

Does the Dictionary keep the order I add items in?

In practice the Scripting Dictionary preserves insertion order, but that is not the same as sorting. If you add items in sorted order, the keys collection will reflect that order.

How do I sort by value in descending order?

Reverse the comparison in your sort routine, or rebuild the new Dictionary by looping from the highest array index down to the lowest.

What if my values are dates or decimals?

Compare them as their native type. Dates compare chronologically and decimals compare numerically, so avoid converting them to text before sorting.

Can I sort by value and then by key for ties?

Yes. In your comparison, when two values are equal, compare the corresponding keys as a secondary rule. This gives a stable, predictable order.

Is there a faster way for very large dictionaries?

Yes. Replace the bubble sort with an insertion sort or quicksort, or write the data to a worksheet range and use Excel's built-in sort, then read it back into a Dictionary.