Browse » Home
Sunday, October 28, 2012
How to Use the Range.sort Method in VBA
1. Open the Excel 2010 spreadsheet that you want to sort using VBA. Press 'Alt' and 'F11' simultaneously to bring up the VBA editor.
2. Double-click on the module, which is located on the left side of the editor, where you are writing your VBA code. Your code will appear on the right side of the screen. Place your cursor into an empty line of code where you want to use the Sort method.
3. Enter the following code into the VBA editor, without quotes: 'Range('A:B').Sort key1:=Range('A1'), Order1:=xlAscending'. Change 'A:B' to the Excel range that you want to sort and change 'A1' to the first cell in the column you want to use to sort by. Change 'xlAscending' to 'xlDescending' if you want to sort from high to low, instead of low to high.
4. Place a comma and a space at the end of your code if you want to add more parameters to the sort method. Enter the name of the parameter, followed by ':=' and then the value for the parameter. Place another comma and a space after each parameter, except for the last one.
5. Use the 'Key 2,' 'Order 2,' 'Key 3' and 'Order 3' parameters to set up additional sorting rules for when the first key find identical values. Use the 'Type' parameter to determine whether to sort the range by labels or values, and use 'xlSortLabels' and 'xlSortValues,' respectively. Use the 'Header' parameter, set as either 'xlYes,' 'xlNo' or 'xlGuess' to let the sort function know if your data has headers or not.Use the OrderCustom parameter, using an integer as the value, to use a preset custom sort order that you created. Use the 'MatchCase' parameter, setting it to either 'True' or 'False' to determine whether to make the sort case sensitive. Use the 'Orientation' parameter, set as either 'xlSortRows' or 'xlSortColumns' to determine how your data table is orientated. Use the 'SortMethod' parameter, set as 'xlStroke' or 'xlPinYin' if you are sorting Chinese characters. Finally, use the 'DataOption1,' 'DataOption2,' or 'DataOption3' parameters, set as 'xlSortTextAsNumbers' or 'xlSortNormal' to determine whether the respective key will have its text be treated as numbers for the sort.