Smart Systems for Home

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

Excel VBA Sort Collection: A Complete Guide and Tutorial

· 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

To sort a collection in Excel VBA, you must implement a custom sorting algorithm (such as a Bubble Sort) because the native VBA Collection object does not provide a built-in Sort method. You achieve this by iterating through the collection, comparing items, and moving them into a new, ordered collection or transferring them to an array for sorting before reloading them back into a collection.

What You'll Need

  • Microsoft Excel installed on a Windows PC.
  • The Visual Basic for Applications (VBA) editor enabled (accessible via Alt + F11).
  • A basic understanding of how to declare variables (Dim) and create loops (For...Next).
  • A dataset or a list of items that you intend to store in a Collection object.

Step-by-Step

  1. Open the VBA Editor: Launch Excel and press Alt + F11 to open the Visual Basic Editor. From the top menu, go to Insert > Module to create a new code module where your sorting logic will reside.
  2. Declare Your Collections: You need two collections: one to hold your unsorted data and one to hold the sorted results. Declare them using Dim myColl As New Collection and Dim sortedColl As New Collection.
  3. Populate the Initial Collection: Use a loop or manual .Add statements to fill your first collection. For example, if you are pulling names from a worksheet, loop through the range and add each cell value to the collection.
  4. Implement the Bubble Sort Logic: Since you cannot swap items within a VBA Collection (they are read-only once added), the most straightforward approach for small to medium lists is the Bubble Sort. You will need to create a temporary array or a secondary collection to handle the movement of items.
  5. Create a Temporary Array: Transfer the items from the Collection into a dynamic array. This is necessary because arrays allow for index-based swapping, which is the core of sorting. Use ReDim tempArray(1 To myColl.Count) and a loop to assign tempArray(i) = myColl(i).
  6. Execute the Comparison Loop: Create a nested loop. The outer loop tracks the number of passes through the list, and the inner loop compares adjacent elements. Use an If statement to check if the current element is greater than the next element (for ascending order).
  7. Swap the Elements: When the If condition is met, use a temporary variable to swap the two values in the array. For example: tempVar = tempArray(j): tempArray(j) = tempArray(j + 1): tempArray(j + 1) = tempVar.
  8. Rebuild the Collection: Once the array is fully sorted, clear your target collection (or create a new one) and loop through the sorted array, adding each element back into the collection using sortedColl.Add tempArray(i).
  9. Verify the Result: Use a For Each loop to print the contents of the sorted collection to the Immediate Window (Ctrl + G) to ensure the order is correct.

Common Mistakes

One of the most frequent errors is attempting to use a .Sort method on a Collection object. Many developers coming from other languages assume this exists in VBA, but calling it will result in a "Object does not support this property or method" runtime error. Always remember that VBA Collections are designed for fast addition and retrieval, not for manipulation of order.

Another common mistake is failing to handle case sensitivity. By default, VBA compares strings in a case-sensitive manner (e.g., "Apple" comes before "apple"). If you want a true alphabetical sort regardless of case, you must use the UCase() or LCase() functions during the comparison step of your sorting loop.

Developers also often forget to use Option Explicit at the top of their modules. When dealing with the multiple index variables (i, j, k) required for sorting algorithms, a single typo in a variable name can create a new empty variable on the fly, leading to a loop that never executes or a logic error that is incredibly difficult to debug.

Finally, using a Bubble Sort on extremely large datasets (thousands of items) can lead to significant performance lag. Bubble Sort has a time complexity of O(n²), meaning the time it takes to sort grows quadratically with the number of items. For very large lists, transferring the data to a worksheet range and using Excel's built-in Range.Sort method is significantly faster.

Tips

To make your sorting logic reusable, wrap the entire process into a dedicated function. Create a function that accepts a Collection as an argument and returns a new, sorted Collection. This prevents you from having to rewrite the sorting loops every time you need to organize a different list of data.

If you are sorting objects rather than simple strings or integers, you cannot compare them directly. Instead, you must compare a specific property of the object. For example, if your collection contains custom Class objects, your comparison line should look like If coll(i).Name > coll(j).Name Then.

Consider using a System.Collections.ArrayList if you are on a Windows environment that supports .NET Framework. The ArrayList object is available via COM and includes a native .Sort method, which eliminates the need to write manual sorting loops entirely. You can add a reference to the "mscorlib.tlb" library to enable this.

When sorting in descending order, simply flip the comparison operator in your If statement from greater than (>) to less than (<). This is the fastest way to change the sort direction without altering the rest of the algorithm.

Troubleshooting

If your code is running but the collection remains unsorted, first check your loop boundaries. A common error is setting the inner loop to To myColl.Count, which causes an "Index out of range" error when the code tries to compare the last item with a non-existent item following it. Ensure your inner loop ends at myColl.Count - 1.

If you encounter a "Type Mismatch" error, it usually means your collection contains a mix of data types (e.g., some strings and some numbers). VBA cannot compare a string to a number using the greater than or less than operators. Ensure all items in the collection are of the same data type, or use CStr() to cast all elements to strings before comparison.

If the VBA editor freezes or Excel becomes unresponsive during the sort, you are likely dealing with an infinite loop. This happens if your loop counters are not incrementing correctly. Press Ctrl + Break to stop the execution and step through the code using F8 to identify where the loop is getting stuck.

If the items are sorted but in a strange order (e.g., 1, 10, 2, 20), you are performing a text sort on numbers. To fix this, ensure the variables used for comparison are declared as Double or Long rather than String or Variant.

Frequently Asked Questions

Can I sort a collection without using an array?

Yes, but it is inefficient. You would have to repeatedly remove items from one collection and add them to another in a specific order, which is significantly slower than using a temporary array for swapping.

Is there a faster way than Bubble Sort for VBA?

Yes, QuickSort or MergeSort are much faster for large datasets. However, they are more complex to code. For most Excel tasks involving under 1,000 items, Bubble Sort is sufficient and easier to maintain.

Does the sort affect the original collection?

Depending on how you write the code, it can. If you transfer the data to an array, sort it, and then clear and refill the original collection, the original is modified. If you add the sorted items to a new collection, the original remains unchanged.

How do I sort a collection of objects by a specific property?

In your comparison loop, instead of comparing the items themselves, refer to the property of the item. For example, use If coll(i).Price > coll(j).Price Then to sort a collection of product objects by their price.

Can I use the Excel worksheet sort on a collection?

Not directly. You must first output the collection items to a range of cells, use the Range.Sort method provided by Excel, and then read the sorted values back into your collection.