Determining Sorting Criteria

by Allen Wyatt
(last updated October 12, 2013)

2

Suppose that a co-worker gives you have a worksheet that has several hundred rows of data in 27 columns. Before you start working with the data, you might want to know if it has previously been sorted. Knowing the information may not only remove the need to resort the data, but will also give you an idea as to what your co-worker felt was the most important way to look at the data.

Unfortunately, Excel doesn't have a built-in way to determine the sorting criteria used for a range of data. You could theoretically write a macro that would check each column and see if it were in ascending or descending order. This will tell you if that single column was sorted, but that doesn't necessarily mean that the entire data table was sorted by that column—it could just be coincidence that the column is in sorted order, and the sort was done by some other column. The task of checking gets even trickier when you start considering secondary and tertiary sorts.

There is one thing you can try, however, to determine if a particular column is sorted and whether it is sorted in ascending or descending order. (Remember: this won't tell you if the particular column was the primary column used for sorting, it will only tell you if the column is sorted.)

The idea behind the macro is to copy the contents of the column to a temporary worksheet, two times. For instance, if you want to check out column F, the macro copies column F to columns A and B on the temporary worksheet. The macro then sorts column B in ascending order and compares it to column A. If the sorted and unsorted columns are the same, then the original column was in ascending order. Then column B is sorted in descending order and the comparison done again. Again, if the columns are equal then the column is in descending order.

Sub TestIfSorted(i)
    Dim CColumn as Number
    Dim CSheet as String
    Dim FlagSort as String

    'Identify Current Column and Current Sheet
    CColumn = i
    CSheet = ActiveSheet.Name
    FlagSort = ""

    'Add a temporary sheet to test for sorting
    Sheets.Add
    ActiveSheet.Name = "TempSort"

    'Copy CURRENT column to Columns A,B in Current Sheet
    Sheets(CSheet).Select
    Columns(CColumn).Select
    Selection.Copy

    Sheets("TempSort").Select
    Range("A1").Select
    ActiveSheet.Paste
    Range("B1").Select
    ActiveSheet.Paste
    Application.CutCopyMode = False

    'In Column C test for equality of Columns A/B
    'If Sum in C1=0 then OK otherwise Col A<>Col B
    Range("B2").Select
    Selection.End(xlDown).Select
    Bottom = ActiveCell.Row
    Range(Cells(2, 3), Cells(Bottom, 3)).Select
    Selection.FormulaArray = "=IF(RC[-2]=RC[-1],0,1)"
    Range("C1").Select
    ActiveCell.FormulaR1C1 = "=SUM(R[1]C:R[6535]C)"

    'Sort Column B--Ascending - See if c1=0
    Columns("B:B").Select
    Selection.Sort Key1:=Range("B2"), Order1:=xlDescending, _
      Header:=xlYes, OrderCustom:=1, MatchCase:=False, _
      Orientation:=xlTopToBottom, DataOption1:=xlSortNormal
    If Cells(1, 3).Value = 0 Then FlagSort = "Ascending"

    'Sort Column B--Descending - See if c1=0
    Columns("B:B").Select
    Selection.Sort Key1:=Range("B2"), Order1:=xlAscending, _
      Header:=xlYes, OrderCustom:=1, MatchCase:=False, _
      Orientation:=xlTopToBottom, DataOption1:=xlSortNormal
    If Cells(1, 3).Value = 0 Then FlagSort = "Descending"

    If FlagSort = "Ascending" Then
        'Color Header on original sheet yellow
        Sheets(CSheet).Cells(1, CColumn).Interior.ColorIndex = 36
    End If

    If FlagSort = "Descending" Then
        'Color Header on original sheet orange
        Sheets(CSheet).Cells(1, CColumn).Interior.ColorIndex = 44
    End If

    'Delete temporary sheet
    Sheets("TempSort").Select
    ActiveWindow.SelectedSheets.Delete
End Sub

Once it is determined whether the original column was in ascending or descending order, then the first cell of the column in the original worksheet is set to yellow or orange, respectively. Finally, the temporary worksheet is deleted.

This macro could be modified so that it was called once for each column in a data table. Running the macro for an entire table wouldn't take that long, but would provide a colorful representation as to whether individual columns are sorted in ascending or descending order.

Of course, any macro like this is not trivial, so it may just be easier for you to figure out how you want to sort the data, and then sort it that way from the get-go.

ExcelTips is your source for cost-effective Microsoft Excel training. This tip (2395) applies to Microsoft Excel 97, 2000, 2002, and 2003.

Author Bio

Allen Wyatt

With more than 50 non-fiction books and numerous magazine articles to his credit, Allen Wyatt is an internationally recognized author. He  is president of Sharon Parq Associates, a computer and publishing services company. ...

MORE FROM ALLEN

Making Live URLs Into Normal Text

Convert those URLs into regular text! It's easy to do when you follow the steps in this tip.

Discover More

Incrementing References by Multiples when Copying Formulas

You can easily set up a formula to perform some calculation on a range of cells. When you copy that formula, the copied ...

Discover More

Stopping a Workbook from Persistently Auto-Loading

Excel has the capability to automatically open workbooks when you first start the program. You may not want to have one (or ...

Discover More

Excel Smarts for Beginners! Featuring the friendly and trusted For Dummies style, this popular guide shows beginners how to get up and running with Excel while also helping more experienced users get comfortable with the newest features. Check out Excel 2013 For Dummies today!

More ExcelTips (menu)

Sorting Data Containing Merged Cells

When formatting the layout of your worksheet, Excel allows you to easily merge adjacent cells together. This can cause havoc ...

Discover More

Fixing Odd Sorting Behavior

When you sort data that contains both numbers and text, you may not get exactly the result that you expected. To know what is ...

Discover More

Moving Cell Borders when Sorting

Sort your data and you may be surprised at what Excel does to your formatting. (Some formatting may be moved in the sort and ...

Discover More
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

View most recent newsletter.

Comments

If you would like to add an image to your comment (not an avatar, but an image to help in making the point of your comment), include the characters [{fig}] in your comment text. You’ll be prompted to upload your image when you submit the comment. Maximum image size is 6Mpixels. Images larger than 600px wide or 1000px tall will be reduced. Up to three images may be included in a comment. All images are subject to review. Commenting privileges may be curtailed if inappropriate images are posted.

What is four less than 9?

2014-11-13 17:59:03

wschloss

Anyone know what **criteria** Excel uses to **color sort and filter**? I experimented; it's not RGB or a permutation, and it doesn't seem related to default color scheme, nor does it seem related to light or dark that I perceive, nor anything like that; nor does it separate grey scales; nor finally does it seem related to the color selected for "top" or "bottom."
I even calculated the RGB sums and products but it's not that. (And therefore I know it's not least squares, or the difference in hypotenum / hypotenooses / hypotenuses. :)
I suppose for most, the fact that it puts colors "together" is sufficient, but I am the sort of geek who needs to know. ha-ha
Please note I am not asking HOW to color sort which is simple and amply covered 100 places.
Thanks.


2013-10-13 04:58:08

Thomas Papavasiliou

Considering thet the data has labels and starts from row 1,another method is to fill an empty column (suppose column W) with a series of numbers from 1 to the last row, then sort the whole data to the column you want to check. In another empty column (suppose Z) in cell Z3 you type the formula =w2-w1 and fill to the bottom.
Highlight the column Z and via the status bar indications check the maximum.
If it is 1 than the data was already sorted and of course if it is different than 1 data was unsorted.
The advantage is that you can return to the original configuration by re-sorting on column W.


This Site

Got a version of Excel that uses the menu interface (Excel 97, Excel 2000, Excel 2002, or Excel 2003)? This site is for you! If you use a later version of Excel, visit our ExcelTips site focusing on the ribbon interface.

Newest Tips
Subscribe

FREE SERVICE: Get tips like this every week in ExcelTips, a free productivity newsletter. Enter your address and click "Subscribe."

(Your e-mail address is not shared with anyone, ever.)

View the most recent newsletter.