Coincidentally, this post relates to two previous posts — which happen to be unrelated to each other:
- Dynamic Text Sorting – An array formula that sorts data in a range as it’s entered.
- Modifying Shapes (and Charts) With UDFs – A user-defined function that modifies objects on a worksheet.
Excel 2007 has a new Sort object. I discovered that this object does its thing even when it’s called by a UDF function used in a formula. In other words, yet another example of a UDF that changes the spreadsheet.
The figure below shows an example. The data in columns A and B is sorted immediately (by column B) whenever a change is made within the range A1:B50. So, if I change Anne’s score to 71, her row would move down between Paul and Oscar’s data.
Cell D2 contains a formula that uses the SortRange function:
‘ Excel 2007 only
‘ Order: 1=ascending, 2=descending
If IsMissing(order) Then order = 1
.SortFields.Add Key:=rngToSort.Cells(1, 2), order:=order
.Header = xlYes
SortRange = .Rng.Address(False, False) ‘Range actually sorted
This function takes two arguments: The range to sort, and the sort order (an optional argument). The Sort object is a member of the Worksheet, so I use the Parent property to get that object, and enclose all of the object manipulations inside of a With-End With structure.
The function does this…
- Clears the SortFields (which is a collection)
- Adds a key. In this case, the sort key is the second column of the data, and it’s sorted in the order specified by the second argument.
- Gets the range to be sorted, using the SetRange method.
- Specifies that the range has a header row, via the the Header property.
- Does the sorting, via the Apply method
- Gets the address of the range that was actually sorted, and assigns it to the function (this is the text returned by the formula). The function is passing a 50-row range, but it only has 13 rows of data.
You can accomplish the same effect with a WorksheetChange event, but this technique allows the user to specify some options without modifying the code. The function, of course, could include more arguments that control how the sorting is done.
Practical applications, anyone?