To receive an array with data sorted alphabetically in Excel, I always use something like this:
With ThisWorkbook.Worksheets("data")
LastRow = .Cells.Find(what:="*", searchorder:=xlByRows, searchdirection:=xlPrevious).Row
.Range("a2:b" & LastRow).Sort key1:=.Range("a1"), order1:=xlAscending
vData = .Range("a2:b" & LastRow)
End With
I can have up to 3 sorting criteria, an infinite number if I run sort multiple times with different sort parameters.
The problem is that it takes time. The worst is when I receive an array as a result of operations within the code and I must first paste the array into worksheet, then sort. With a few hundred thousands of rows, it will take a few seconds.
I used my modifications of QuickSort algorithms to sort numbers, but I imagine that sorting text alphabetically would require 'StrComp', which from my experience is relatively time consuming.
Have you seen or do you think it possible to create a VBA 2 dimensional array alphabetical sorting algorithm (can even be 1 criteria column), which will perform faster than Range.Sort
(or pasting huge array + sort)? If yes, how would the strings be compared?
You can try using methods from the
ADODB
library and simply do aSELECT
query on your data where youORDER BY
the text columns in the data which negates the need to write a custom sorting function.Using this approach will allow you to scale to any number of text columns without worrying how the custom function will deal with multiple columns of text data.
Sample data and output:
Sample code for above - please follow the comments.
Note the following: