How to Sort Data in Excel Using VBA (Ranges, Columns & Tables)

Sumit Bansal
Written by

Sumit Bansal is the founder of TrumpExcel.com and a 13-time Microsoft Excel MVP. He started this site in 2013 to share his passion for Excel through easy tutorials, tips, and training videos, helping you master Excel, boost productivity, and maybe even enjoy spreadsheets!

Last updated

Excel already has a couple of ways to sort data quickly.

You can easily sort a data set by using the sort icons in the ribbon or the sort dialog box.

Sort A to Z, Sort Z to A and the Sort button in the Sort & Filter group of the Data tab

Then why do you need to know how to do this using VBA?

Knowing how to sort data using VBA can be helpful when included as a part of your code. For example, suppose you get a data set daily/weekly that you need to format and sort in a specific order.

You can create a macro to do all this for you with a single click. That will save you a lot of time and effort every time you do it.

Also, if you create Excel dashboards, you can take Excel sorting capability to a new level by allowing the user to sort the data just by double-clicking on the header (as shown below).

Double-clicking the State, Sales and Store headers sorts the data by that column and moves the arrow and yellow highlight to the clicked header

I will cover how to create this later in this tutorial, along with how to sort an Excel Table with VBA. Let’s first quickly get the basics straight.

Follow along with the example file

Sort Data Using VBA Excel.xlsm

Download

Understanding the Range.Sort Method in Excel VBA

When sorting using VBA, you need to use the Range.Sort method in your code.

The ‘Range’ would be the data that you’re trying to sort. For example, if you’re sorting the data in A1:A10, then ‘Range’ would be Range(“A1:A10”).

You can also create a named range and use it instead of the cell references. For example, if I create a named range ‘DataRange’ for the cells A1:A10, then I can also use Range(“DataRange”).

With the sort method, you need to provide some additional information through parameters. Below are the key parameters you need to know:

  • Key1 – here you need to specify the column that you want to sort. For example, if you want to sort column A, you need to use Key1:=Range(“A1”)
  • Order1 – here you specify whether you want the sorting in an ascending order or the descending order. For example, if you want the sorting in ascending order, you will use Order1:=xlAscending
  • Header – here you specify whether your data set has headers or not. If it has headers, the sorting starts from the second row of the data set, else it starts from the first row. To specify that your data has headers, you will use Header:=xlYes

While these three suffice in most of the cases, you can read more about the other parameters (such as Key2 and MatchCase) in Microsoft’s Range.Sort documentation.

The macros in this tutorial work in the desktop version of Excel. Excel for the web can’t run VBA macros.

Now let’s see how to use the Range.Sort method in VBA to sort data in Excel.

Sorting a Single Column Without Header

Suppose you have a single column of names without a header (as shown below), and you want to sort it in alphabetical order.

A single column of 12 unsorted names in A1:A12 with no header

You can use the below code to sort it in ascending order.

Sub SortDataWithoutHeader()
    Range("A1:A12").Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlNo
End Sub
The 12 names sorted A to Z by the SortDataWithoutHeader macro

Note that I have specified the data range manually as Range(“A1:A12”).

In case there might be changes in the data and values might be added/deleted, you can use the below code that automatically adjusts based on the filled cells in the dataset.

Sub SortDataWithoutHeaderDynamic()
    Range("A1", Range("A1").End(xlDown)).Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlNo
End Sub

Note that instead of Range(“A1:A12”), I have used Range(“A1”, Range(“A1”).End(xlDown)).

This will check the last consecutively filled cell in the column and include it in sorting. In case there are blanks, it will only consider data till the first blank cell.

Another option is Range(“A1”).CurrentRegion, which picks up the whole block of data around A1. It gets past a blank cell when another cell in that row has data, but it also stops at a completely blank row.

You can also create a named range and use that named range instead of the cell references. For example, if the named range is DataRange (covering the names in A1:A12), your code would now be as shown below.

Sub SortDataWithoutHeaderNamedRange()
    Range("DataRange").Sort Key1:=Range("A1"), Order1:=xlAscending, Header:=xlNo
End Sub

Now let me quickly explain the parameters used in the above examples:

  • Key1:=Range(“A1”) – Specified A1 so that the code would know which column to sort.
  • Order1:=xlAscending – Specified the order as xlAscending. If you want it to be in the descending order, use xlDescending.
  • Header:=xlNo – Specified that there are no headers. This is also the default value. So even if you omit this, your data will be sorted considering it has no headers.

There is also a third option, Header:=xlGuess, where Excel tries to work out whether the first row is a header. When you already know whether your data has a header, xlYes or xlNo is safer, because the result then doesn’t depend on Excel’s guess.

Wondering where to put this VBA code and how to run the macro? Read this tutorial!

Also, note that these macros sort whatever sheet is active when you run them. In the example file, each sheet lists the macros meant for it, so run each macro while its own sheet is selected.

Sorting a Single Column With Header

In the previous example, the data set did not have a header.

When your data has headers, you need to specify that in the code so that the sorting can start from the second row of the dataset.

Suppose you have a dataset of store sales by state as shown below, and you want to sort it by sales in descending order.

Store sales data with State, Store and Sales headers, unsorted

Below is the code that will sort the data in descending order based on the sales of the stores.

Sub SortDataWithHeader()
    Range("DataRange").Sort Key1:=Range("C1"), Order1:=xlDescending, Header:=xlYes
End Sub
Store sales sorted by Sales, largest first, with the header row still on top

Note that I have created a named range – ‘DataRange’ (A1:C13), and used this named range in the code.

Important: Always add Header:=xlYes when your data has a header row. Without it, Excel treats the header row as data, so if you sort this data by Sales in ascending order, the ‘State’, ‘Store’, and ‘Sales’ row gets sorted down into the data.

Sorting Multiple Columns With Headers

So far in this tutorial, we have seen how to sort a single column (with and without headers).

Now, what if you want to sort based on multiple columns?

For example, in the below data set, what if I want to first sort by the state code, and then by the store.

Store sales data with State, Store and Sales headers, unsorted

Here is the code that will sort multiple columns at one go.

Sub SortMultipleColumns()
    With ActiveSheet.Sort
        .SortFields.Clear
        .SortFields.Add Key:=Range("A1"), Order:=xlAscending
        .SortFields.Add Key:=Range("B1"), Order:=xlAscending
        .SetRange Range("A1:C13")
        .Header = xlYes
        .Apply
    End With
End Sub

Below is the result that you will get.

Store sales sorted by State and then by Store

In the above example, the data is first sorted by the state code (column A). Then within the state code data, it is again sorted by the Store (Column B).

This order is determined by the order in which you mention it in the code.

Note that this code doesn’t use Range.Sort. It uses the worksheet’s own Sort object (ActiveSheet.Sort), where each .SortFields.Add line adds one sort level, in the order you want them applied.

The .SetRange line tells Excel which cells to sort, .Header = xlYes says the first row has headers, and .Apply runs the sort.

You need the .SortFields.Clear line. Excel remembers the sort fields from the last sort on that sheet (even one done with Range.Sort), and without this line, the new fields get added after the old ones, so you get the wrong order.

If you only need two or three levels, Range.Sort can also do this in one line with Key2 and Order2:

Sub SortMultipleColumnsKey2()
    Range("A1:C13").Sort Key1:=Range("A1"), Order1:=xlAscending, _
        Key2:=Range("B1"), Order2:=xlAscending, Header:=xlYes
End Sub

This gives the same result. Range.Sort takes up to three keys (Key1, Key2, and Key3), while the SortFields approach lets you add as many levels as you need.

Sort an Excel Table Using VBA

If your data is in an Excel Table, you can sort the Table itself instead of a fixed range. This is useful because a Table grows as you add rows, and the code keeps working without any change.

Below I have the same store sales data converted into an Excel Table named SalesTable, and I want to sort it by sales in descending order.

Store sales data in an Excel Table named SalesTable

Here is the code that will do this:

Sub SortExcelTable()
    With ActiveSheet.ListObjects("SalesTable").Sort
        .SortFields.Clear
        .SortFields.Add Key:=Range("SalesTable[Sales]"), Order:=xlDescending
        .Header = xlYes
        .Apply
    End With
End Sub
The Excel Table sorted by Sales, largest first, by the SortExcelTable macro

In VBA, an Excel Table is a ListObject, so ListObjects(“SalesTable”) picks the Table by its name. Range(“SalesTable[Sales]”) refers to the Sales column of the Table, so you don’t need to know which cells it covers.

The multiple-column macro needed .SetRange to tell the worksheet’s Sort object which cells to sort. The Table’s own Sort object (ListObjects(“SalesTable”).Sort) already knows the Table’s range, so you don’t need .SetRange here.

This also means the sort always covers the whole Table, no matter how many rows it has.

To use this with your own data, replace SalesTable with your Table’s name (you can see it in the Table Design tab) and Sales with the column you want to sort by.

Sorting Data Using Double Click on Header

If you’re creating a dashboard or want more ease of use in your reports, you can write a VBA code that will sort the data when you double click on the headers.

Something as shown below:

Double-clicking the Store, Sales and State headers sorts the data by that column

Below is the code that will allow you to do this:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Dim KeyRange As Range
    Dim ColumnCount As Long
    ColumnCount = Range("DataRange").Columns.Count
    Cancel = False
    If Target.Row = 1 And Target.Column <= ColumnCount Then
        Cancel = True
        Set KeyRange = Range(Target.Address)
        Range("DataRange").Sort Key1:=KeyRange, Header:=xlYes
    End If
End Sub

Note that I have created a named range (“DataRange”) and have used it in the code instead of using the cell references.

As soon as you double-click on any of the headers, the code disables the usual double-click functionality (which is to get into the edit mode) and uses that cell as the key while sorting the data.

Also note that as of now, this code will sort all the columns in ascending order only.

Note that double-click is a trigger that allows Excel to run the specified code. These triggers such as double-click, opening a workbook, adding a new worksheet, changing a cell, etc. are called events and can be used to run macros in Excel.

You can read more about Excel VBA events here.

Where to put this code?

You need to paste this code into the code window of the sheet in which you want this double click sort functionality. Here are the steps to do this:

  1. Right-click on the sheet tab.
Right-click menu of the Double Click Sort sheet tab
  1. Click on View Code.
The sheet tab's right-click menu with View Code highlighted
  1. Paste the code in the code window of the sheet in which your data resides.
The double-click sort code pasted in the Double Click Sort sheet's code window

Since the workbook now has a macro, save it as a macro-enabled workbook (.xlsm). A regular .xlsx file doesn’t keep the code.

Now what if you want to sort the first two columns (‘State’ and ‘Store’) in ascending order, but ‘Sales’ column in descending order?

This code replaces the earlier one in the sheet’s code window, because a sheet can have only one Worksheet_BeforeDoubleClick procedure. The same goes for the other double-click codes below (in the example file, each version is on its own sheet).

Here is the code that will do it:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Dim KeyRange As Range
    Dim ColumnCount As Long
    Dim SortOrder As Long
    ColumnCount = Range("DataRange").Columns.Count
    Cancel = False
    If Target.Row = 1 And Target.Column <= ColumnCount Then
        Cancel = True
        Set KeyRange = Range(Target.Address)
        If Target.Value = "Sales" Then
            SortOrder = xlDescending
        Else
            SortOrder = xlAscending
        End If
        Range("DataRange").Sort Key1:=KeyRange, Header:=xlYes, Order1:=SortOrder
    End If
End Sub

In the above code, it checks if the cell that is double-clicked is the Sales header or not. If yes, then it assigns the xlDescending value to the variable SortOrder, else it makes it xlAscending.

Note that the variables are declared with Dim. This way, the code also works when Option Explicit is turned on at the top of the module.

Double-Click Again to Reverse the Sort Order

The codes above always sort a column in the same direction. In most apps, clicking the same header again flips the order, and you can make your Excel data work the same way.

Below is the same store sales data, and I want a double-click on a header to sort that column in ascending order, and a second double-click on the same header to sort it in descending order.

Store sales data with State, Store and Sales headers, unsorted

Here is the code that will do this:

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Static LastColumn As Long
    Static LastOrder As Long
    Dim SortOrder As Long
    Cancel = False
    If Target.Row = 1 And Target.Column <= Range("DataRange").Columns.Count Then
        Cancel = True
        If Target.Column = LastColumn And LastOrder = xlAscending Then
            SortOrder = xlDescending
        Else
            SortOrder = xlAscending
        End If
        Range("DataRange").Sort Key1:=Target, Order1:=SortOrder, Header:=xlYes
        LastColumn = Target.Column
        LastOrder = SortOrder
    End If
End Sub
Store sales sorted by Sales, largest first, after the second double-click on Sales

The two Static variables remember which column was sorted last and in which order, even after the macro finishes.

If you double-click the same header again and it was sorted ascending last time, the code sorts it descending. Any other header starts with ascending.

Static variables reset when the workbook is closed, so the first double-click after you reopen the file always sorts in ascending order.

Show an Arrow on the Sorted Header

Now let’s take this a notch further and show a visual marker (arrow and colored cell) in the header when it is sorted.

This version builds on the first double-click code, so it always sorts in ascending order (a second double-click doesn’t reverse it).

Something as shown below:

Double-clicking State and then Sales moves the arrow and yellow highlight to the sorted header

To get this, I have added a new worksheet and made the following changes in it (you can download the example file above and follow along):

  • Changed the name of the new sheet to ‘BackEnd’.
  • In cell B1, entered an arrow symbol (to do this, go to Insert and click on ‘Symbol’ option).
  • Copy and paste the headers from the data set to cell A3:C3 in the ‘BackEnd’ sheet.
  • Use the following function in cell A4:C4 (the below formula goes in A4, and B4 and C4 get the same formula for their own column):
=IF(A3=$C$1,A3&" "&$B$1,A3)
  • Rest of the cells will automatically get filled by the VBA code when you double click on the headers to sort the column.

The IF function checks if the header in row 3 is the one that was sorted (the macro puts its name in C1). If it is, it adds the arrow from B1 after the header text, else it returns the header as it is.

Your backend sheet would look something as shown below:

BackEnd sheet: sorted column number 1 in A1, the arrow in B1, State in C1, plain headers in row 3 and the IF formulas in row 4

Now you can use the below code to sort the data by double-clicking on the headers. When you double-click on a header, it will automatically get the arrow in the header text.

Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Dim KeyRange As Range
    Dim ColumnCount As Long
    Dim i As Long
    ColumnCount = Range("DataRange").Columns.Count
    Cancel = False
    If Target.Row = 1 And Target.Column <= ColumnCount Then
        Cancel = True
        'Take the plain header name from BackEnd row 3 (the clicked cell may already show the arrow)
        Worksheets("BackEnd").Range("C1").Value = Worksheets("BackEnd").Range("A3").Offset(0, Target.Column - 1).Value
        Set KeyRange = Range(Target.Address)
        Range("DataRange").Sort Key1:=KeyRange, Header:=xlYes
        Worksheets("BackEnd").Range("A1").Value = Target.Column
        For i = 1 To ColumnCount
            Range("DataRange").Cells(1, i).Value = Worksheets("BackEnd").Range("A4").Offset(0, i - 1).Value
        Next i
    End If
End Sub
Data sorted by State after a double-click, with the State header showing the arrow and a yellow highlight

The code writes the name of the sorted header in C1 and its column number in A1 of the BackEnd sheet. It then copies the headers from A4:C4 back into the data, so the sorted one shows the arrow.

The code takes the header name from row 3 of the BackEnd sheet, not from the cell you double-clicked. Once a header shows the arrow, its text is ‘State ↓’, so if the code copied the clicked cell, C1 would hold ‘State ↓’.

That no longer matches the plain ‘State’ in A3, so the IF formula would drop the arrow on the next double-click. Reading the plain name from row 3 keeps C1 matching.

Note that I have also used conditional formatting to highlight the cell as well. The rule is applied to A1:C1 with the formula =COLUMN(A1)=BackEnd!$A$1, so it colors the header whose column number is in A1 of the BackEnd sheet.

Note that this code works well for the way my data and workbook is constructed. If you change the structure of the data, you will have to modify the code accordingly.

Follow along with the example file

Sort Data Using VBA Excel.xlsm

Download

So these are the ways you can sort data in Excel using VBA. If you don’t need a macro and just want a sorted copy of your data, the SORT function can do that with a formula.

I hope you found this Excel tutorial useful.

You May Also Like the Following Excel Tutorials:

Sumit Bansal

Sumit Bansal

13x Microsoft Excel MVP

Hey! I'm Sumit Bansal, founder of trumpexcel.com and a Microsoft Excel MVP. I started this site in 2013 because I genuinely love Microsoft Excel (yes, really!) and wanted to share that passion through easy Excel tutorials, tips, and Excel training videos. My goal is straightforward: help you master Excel skills so you can work smarter, boost productivity, and maybe even enjoy spreadsheets along the way!

21 thoughts on “How to Sort Data in Excel Using VBA (Ranges, Columns & Tables)”

  1. If you want to protect the sheet is it possible or does this not work with protected sheets? can I add the password to the code?

    Reply
  2. Sorting Multiple Columns With Headers
    I copied this code and table, but it does not work. Is there a problem with the code?

    Reply
  3. Very helpful post. I suggest to add a ‘SortFields.Clear’ if you want to run it more than once.

    Sub SortMultipleColumns()
    With ActiveSheet.Sort
    .SortFields.Clear ‘<— ***HERE***
    .SortFields.Add Key:=Range("A1"), Order:=xlAscending
    .SortFields.Add Key:=Range("B1"), Order:=xlAscending
    .SetRange Range("A1:C13")
    .Header = xlYes
    .Apply
    End With
    End Sub

    Reply
  4. Is there a way to sort a portion of a single row over multiple columns, without having to specify a Sort by column?

    I have individual words in several columns, and I want to sort the columns alphabetically, regardless of which column the words are in.

    For example, each column from M to W has a single word. I want to sort that portion of the row so that the words are rearranged in the columns alphabetically, lowest in M, highest in W.

    Thank you.

    Reply
  5. Great explanation. Very Clear. Using your example of sorting the 3 column data set by column “A”, my need is to sort A1:C20 then move to column E and sort E1:E20 and repeat “X” number of times (where X is variable) moving to the right 4 columns each time.

    Reply
    • This is John R. Forget my request. Just figured it out thanks to your wonderful explanation. The code is as follows for anyone else interested.
      Enter the number of times you want to move to the right and sort a new data set in Cell “A4”. Put cursor on first cell of data set you want to start with and macro will sort that data set, move 4 cells to the right (ActiveCell.Offset line) and repeat sort.

      Sub SortDataWithoutHeader()
      ActiveCell.Range(“A1:C30”).Select
      Dim i As Long
      For i = 1 To Range(A4).Value
      Selection.Sort
      Key1:=ActiveCell.Range(“A1”), Order1:=xlAscending, Header:=xlNo
      ActiveCell.Offset(0, 4).Range(“A1”).Select
      Next i
      End Sub

      Reply
  6. Getting Method ‘Range’ of object ‘_Worksheet’ failed on this line:

    ColumnCount = Range(“DataRange”).Columns.Count

    Reply
    • Because Writer use “DateRange” as variable for range, please use your own data range / table range for getting desired result.

      Reply
  7. Re:
    Sub SortMultipleColumns()
    With ActiveSheet.Sort
    .SortFields.Add Key:=Range(“A1”), Order:=xlAscending
    .SortFields.Add Key:=Range(“B1”), Order:=xlAscending
    .SetRange Range(“A1:C13”)
    .Header = xlYes
    .Apply
    End With
    End Sub

    I use .SetRange Columns(“A:B”)
    This gets all the data in the column(s)

    Reply
    • Quite sure that if your data is in four columns you will need to change the Range from A1:C?? to A1:D??.
      I would recommend that you set the range first and assign it to a variable and then use that variable name in the sort code.

      Reply
  8. Sub SortMultipleColumns()
    With ActiveSheet.Sort
    .SortFields.Add Key:=Range(“A1”), Order:=xlAscending
    .SortFields.Add Key:=Range(“B1”), Order:=xlAscending
    .SetRange Range(“A1:C13”)
    .Header = xlYes
    .Apply
    End With
    End Sub

    this isn’t working for 4 columns. It sorts my data for the first 2 columns I specify, but not after that.

    Reply
  9. Interesting. Is there an approach that would allow sorting as described here but a) contents of cells to be protected. b) some visible data columns to be excluded as sorting by options? i.e. double clicking on some headers does nothing because we don’t want the user to break the data set, but they do need to be able to see it. Thanks.

    Reply
  10. very helpful. Thank you. I had found some older macro code with “key1:” but that doesn’t appear to work anymore so it was helpful to see “add key” in your code.

    Reply
  11. Hi,
    My profile is RTA in a bpo and I need your help. Hope you don’t mind.

    Question – We do have Forecast volume from client and actual volume is refreshed every 5 second and is updated in excel. Based on that I can judge in which span the number of calls / chats were high/low.
    According to that I have to send an e-mail… for ex:-
    Low volume observed in Pay&Go
    High volume observed in Business, Sales Skills.

    I have used the formulas which will filter both of the values (greater than 10% as high volume and less than -10% as low volume.
    I need to send an e-mail which will filter and write automatically as mentioned above.

    Pls let me know how this can be done

    Reply

Leave a Comment

Get the FREE 51 Excel Tips Ebook

Enter your details and the free PDF is on its way to your inbox.

Hmm, that didn't go through. Please check your email and try again.

No spam. You'll also get my weekly Excel newsletter. Unsubscribe anytime.

Check your inbox!

The ebook is on its way to your email. It usually lands within a couple of minutes.