Sort Excel Tables by Double Clicking

How to sort Microsoft Excel Tables by double clicking on any cell

Sorting Oranges / Photographer: Jack DelanoOne of the most basic techniques in data analysis is sorting. And for sure it is one of the most helpful. If you are exploring a large data set for the very first time, I am pretty sure, sorting the data by certain fields is one of the first things you do.

Very often, you do one sort after the other. Let’s say you are looking at a large table of several hundreds of products and all their performance measures, like the unit price, the margin, the order quantities, etc. If you want to get an overview of the product portfolio, what do you need to know in the first step? The most expensive and the cheapest products, the products with the highest margins, the best selling products, etc.

So, what do you do? Sorting, again and again, right?

There is no data analysis or BI tool that doesn’t provide a sorting functionality. However, is it easy and fast to access? And even if it is? Couldn’t it be faster?

Today’s article provides a technique to sort Microsoft Excel tables by simply double clicking on a cell of the data table. As usual, including the workbook for free download.

Agreed, the time savings are humble, but give it a try. I guarantee, chances are high that you will love the feature.

The Idea

Sure, Microsoft Excel has a fast and powerful built-in sorting feature. Of course it has. However, you have to go to the home tab, click on Sort & Filter and select the sort order (or go to the data tab and click on one of the sort buttons). Mouse movements and up to three clicks necessary.

There is a nice option to build your own sorting procedure, even without VBA: If you want to provide a more user-friendly way of sorting (e.g. on a dashboard), I recommend having a look at part 2 of the KPI dashboard series on Chandoo’s blog. No VBA necessary, only some Excel formulas (SMALL, MATCH, INDEX) and radio buttons.

But what if you want to have a quick and intuitive way of sorting without

  • a lot of formulas and time / effort needed to set this up
    and without
  • spending some extra time for moving the mouse and clicking?

How about simply double clicking into the data table? Wouldn’t that be nice?

The Functionality

Well, not much to explain here. For the sake of completeness:

  • Double clicking on any cell sorts the table by this column.
  • If the column is not yet sorted, the default sort order is descending for numeric data and ascending for text.
  • Double clicking again toggles the sort order.
  • The sorted column is highlighted with a light grey fill color.

The Implementation

To trigger the sort procedure with every double click on the data table, we implement the code within the event driven standard sub Worksheet_BeforeDoubleClick of the sheet module containing the data table.

Here is the VBA procedure in pseudo code:

  1. Exit the sub if the user double clicked outside of the data table
  2. Define the data structure (ranges of the table and of the active column)
  3. Check if the active column contains numbers or alphanumeric data using the VBA function IsNumeric
  4. Check if the column is sorted and detect the existing sort order
    • Use the worksheet function AND and a greater or equal than / lesser than or equal sign to create strings with array formulas for sort order checking (see Chandoo’s excellent article Using Array Formulas to check if a list is sorted for a detailed explanation of this array formula)
    • Calculate the result of the array formula using the VBA function Evaluate
  5. Define the sort order (descending or ascending) depending on the existing sort order
  6. Sort the table by the active column in the detected sort order
  7. Set the fill color of the sorted column to a light grey (optional step)

It is a pretty lean VBA sub, only 50 lines of code (excluding empty lines and comments). If you are interested in the details, download the workbook and have a look.

A Variation

You may find it more intuitive to sort the columns only by double clicking on the headers of the columns, instead of sorting the table after a double click on any cell. If you prefer this option, simply replace the following line of code:

If Application.Intersect(ActiveCell, Range("myData").Cells) Is Nothing Then Exit Sub

by

If Application.Intersect( _
ActiveCell, Range("myData").Cells.Resize(1, Range("myData").Columns.Count)) _
Is Nothing Then Exit Sub

That’s all.

The Performance

I implemented and tested the VBA code using an extract of an example data set of the FIFA World Cup results, which I already used for a Tableau post here: FIFA World Cup Statistics with Tableau. The data has only 361 rows and I was not sure how the performance would be with a larger table.

Thus, I created a data set of 65,000 records and 30 columns using random numbers and texts and tested the workbook. The performance is still pretty good. On my machine, the sorting takes one or two seconds. Still acceptable, I think.

Download

Here is the Microsoft Excel workbook for free download:

Download Sort Excel Tables by Double Clicking (Microsoft Excel 2003, 97K)

How to use this in your own workbook

You need only 2 simple steps to transfer this feature to your own workbook:

  1. Assign the range name “myData” to your table (including the headers of the columns).
  2. Go to the VBE (ALT-F11) and copy and paste the code from the workbook provided above into the sheet module of the worksheet containing the data table.

Easy, isn’t it?

Enjoy…

…and stay tuned.

Comments

25 responses to “Sort Excel Tables by Double Clicking”

  1. Neil Avatar
    Neil

    Hi Robert!
    An excellent technique to sort, & will be one I will use in my daily grind..
    An observation however: once the header is doubleclicked, (& the data sorted), the cell goes into Edit mode, & takes an additional “Esc” to get back to the “Ready” state.

  2. Robert Avatar

    Neil,
    thanks for your comment. I am glad you liked it.
    It is a feature, not a bug.
    I suspect you have “allow editing directly in cell” activated in the advanced Excel options. Thus, when double clicking, the sorting procedure is executed first (we are using the event sub Worksheet_BeforeDoubleClick) and afterwards Excel is doing what it is supposed to do: it goes into edit mode to let you directly edit the cell.
    Simply uncheck “allow editing directly in cell” in the advanced Excel options to avoid this.

  3. Marko Avatar
    Marko

    great work Robert!
    Saves the hassle of creating sort buttons with this option!
    Keep it up!

  4. MHill Avatar
    MHill

    hi, can you tell me how to select VBE on a mac? I’m trying to sort by clicking on only the top cell in a column but Alt-F11 doesn’t take me to VBE on my mac.
    Thanks!

  5. Robert Avatar

    MHill,
    I do not have a Mac available, but as far as I know the shortcut to get to the VBE for a Mac Excel version (other than Mac Excel 2008, of course) is ALT-FN-F11.
    I think the ALT-key is called ‘Option’ on a Mac keyboard.

  6. EvR Avatar
    EvR

    or add:
    Cancel = True
    just before End Sub

  7. CC Avatar
    CC

    Awesome feature… really effective, question though moving onto the next step… how could we achieve the same functionality to sort the rows in the table? ie. you double click on a row header to sort horizontally and a column header to sort vertically?

  8. Robert Avatar

    CC,
    this is possible, of course. It is pretty much duplicating and adjusting the existing code. Have a look here:

    Download Sort table by double click enhanced (26.1K)

  9. asd@asd.com Avatar
    asd@asd.com

    Hello and thank you for your work. Spawned lots of ideas 🙂
    Here’s one for you. How about alternating between ascending and descending orders every time you double click?
    I do that using a toggle button. But I have to say double clicking on any cell is even easier!

  10. Robert Avatar

    asd,
    the workbook provided for download above already alternates the sort order after another double click.

  11. adam Avatar
    adam

    Great code – but what about modifying it to sort a range that is dynamic (e.g., sort rows 2 thru the last used row in column J)

  12. Robert Avatar

    Adam,
    you can, but you do not necessarily have to change the code. The technique uses the named range “myData” to define the range of the table which shall be sorted. You can replace the fixed range of this name by a formula making it dynamic, e.g. using a combination of OFFSET and COUNTA.

  13. kabirbaf@gmail.com Avatar
    kabirbaf@gmail.com

    Dear Sir/Madam,
    Could you please tell me how can I use the code for google sheet please and help me obtaining that . Thanks in advance.
    Regards,
    Mohammad Hossain

  14. Robert Avatar

    Mohammad,
    the features are implemented in VBA (Visual Basic for Applications), Microsoft’s programming language for Office applications. As is, they work in Excel only.
    It may be possible to rebuild the same functionality in Google Docs with Google’s Apps Script, but I do not know. I am not familiar with Apps Script.

  15. kabirbaf@gmail.com Avatar
    kabirbaf@gmail.com

    Yes it is working nicely for Excel sheet for Excel 2010 but when I upload that sheet for Google sheet it is not working at all. When I wish to insert that script editor, it shows lots of synthex error and could not save evem. If anyone have idea-please assist me

  16. Robert Avatar

    Mohammad,
    maybe my answer wasn’t precise enough. I am sorry.
    To be crystal clear: there is absolutely no way to make my code working on a Google docs sheet.
    My code is written in Visual Basic for Applications, the programming language dedicated to write code for Microsoft Office applications like Excel, Access, Word, etc.
    Google Apps script is a completely different programming language. If you want to have the functionality on a Google docs sheet, you can’t use anything of my VBA code in the Excel worksheet provided above, not one single line. You have to write your own Google Apps script code from scratch.

  17. Mohammad Avatar
    Mohammad

    Thanks. That is I wish from some one.

  18. Robert Avatar

    Mohammad,
    I suppose, my readers are – just like myself – primarily using Microsoft Excel and not Google docs. I would assume, your chances to find someone here transferring my code to Google Apps script are next to nothing. I recommend to publish your request on a Google Apps script forum.

  19. Anusha Avatar
    Anusha

    Hello Robert,
    This is a wonderful technique for sort in excel.
    But I have a question here. I have a data range where in one column contains drop down feature and rest of the columns are derived from the value which we select in the drop down fetching from another base table.
    This technique I tried implementing the macro is executing perfectly as I tried debugging and it runs till the end but the values are not sorted or not displayed.even the screenupdating is True at the end.
    So I am not sure if this technique will work for such data.Could you please help me in this regard ?
    Thanks,
    Anusha

  20. Robert Avatar

    Anusha,
    the technique also works for tables with data entered via a data validation list and/or formulas in columns. Thus, your data set up cannot be the root of the problem.
    I can think of two possible issues:
    1. The range name myData does not cover your entire range, i.e. you added rows at the end and/or columns to the right, but did not adjust the definition of myData. In this case, adjust the named range myData to cover the entire range where your data is.
    2. You are not using a simple data range, but a table (list object). In this case, you would have to change the code to refer to a list object instead of a simple range. The code always runs to the end, because all errors are skipped due to the On Error Resume Next statement.
    If this does not solve the problem, you can send me your workbook by email and I will have a look.

  21. Ernest Avatar
    Ernest

    Hello Robert,
    It seems the VBA doesn’t sort backward when I have negative numbers in the column. Is it possible?

  22. Ernest Avatar
    Ernest

    Hello Robert, It is my mistake. It doesn’t sort backward only when there is circular reference in it. It is my fault.

  23. Robert Avatar

    Ernest,
    I can’t reproduce the issue. The sorting works fine for me with negative numbers.
    All I can think of is this: the code uses the active region to determine the range which has to be sorted. Do you have an entirely empty row somewhere in your table? If this is the case and you double click somewhere above this empty row, all records beneath the empty row will not be included in the sorting. Maybe this is the problem?

  24. Robert Avatar

    Ernest,
    please ignore my previous comment. I didn’t see your second message when posting it. Glad you figured it out.

  25. Mark Avatar
    Mark

    This is fantastic, thanks so much!

Leave a Reply to Neil Cancel reply

Your email address will not be published. Required fields are marked *