How to Sort a Column Using VBA in Excel (4 Methods)

Range.Sort Method in Excel VBA

The Range.Sort method in Excel VBA allows you to sort a range of values. The Range object variable specifies the cells you want to sort, either in ascending or descending order.

Below are the parameters that you need to know about while working with this method.

Parameter Required/ Optional Data Type Description
Key Optional Variant Specifies the range or the column whose values are to be sorted.
Order Optional XlSortOrder Specifies the order in which the sorting will be performed.

  • xlAscending = To sort in ascending order.
  • xlDescending = To sort in descending order.
Header Optional XlYesNoGuess Specifies whether the first row contains headers or not.

  • xlNo = When the column doesn’t have any headers, default value.
  • xlYes = When the columns have headers.
  • xlGuess = To let Excel determine the headers.

Method 1 – Sort a Single Column without Header 

  • Open the Visual Basic Editor by pressing Alt + F11 or navigating to the Developer tab and clicking Visual Basic.

  • In the code window, click Insert and choose Module.

  • Copy and paste the following code:
Sub SortSingleColumnWithoutHeader()
Range("B5:B15").Sort Key1:=Range("B5"), Order1:=xlAscending, Header:=xlNo
End Sub

Here,

  • Key1:=Range(“B5”) → Specifies the column to sort (in this case, column B).
  • Order1:=xlAscending → Sorts the column in ascending order. Use xlDescending for descending order.
  • Header:= xlNo → Since the column has no header, we set this option.

Embed VBA to Sort a Single Column without Header in Excel

  • Press F5 or click the Run Sub/UserForm icon to execute the macro.

  • Your column will be sorted in ascending order.

Result of Embed VBA to Sort a Single Column without Header in Excel

Note that the data range was defined manually as Range(“B5:B15”).

Note: If your data range changes dynamically (e.g., by adding or deleting values), use the following code instead:

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

Note that instead of defining range manually by Range(“B5:B15”), we have written, Range(“B5”, Range(“B5”).End(xlDown)).

This code sorts based on the last consecutively filled cell in the column, considering only non-blank cells.

Read More: Excel VBA to Sort Column Ascending


Method 2 – Sort a Single Column with Header

  • Open the Visual Basic Editor as before.
  • Insert a new module.
  • Copy and paste this code:
Sub SortSingleColumnWithHeader()
Range("B5:B16").Sort Key1:=Range("B5"), Order1:=xlDescending, Header:=xlYes
End Sub

Here,

  • Key1:=Range(“B5”) → Specifies the column to sort (column B).
  • Order1:=xlDescending → Sorts the column in descending order.
  • Header:= xlYes → Since the column has a header, we set this option.

Insert VBA Macro to Sort a Single Column with Header

  • Run the code, and your column with a header will be sorted in descending order.

Result of Insert VBA Macro to Sort a Single Column with Header

Read More: Excel VBA to Sort by Column Header Name


Method 3 – Sort Multiple Columns with or without Header

 

Follow these steps to sort multiple columns using VBA:

  • Open the Visual Basic Editor by going to the Developer tab and clicking Visual Basic.
  • Insert a new module in the code window.
  • Copy and paste the following code:
Sub SortMultipleColumnsWithHeaders()
With ActiveSheet.Sort
     .SortFields.Add Key:=Range("B4"), Order:=xlAscending
     .SortFields.Add Key:=Range("C4"), Order:=xlAscending
     .SetRange Range("B4:D15")
     .Header = xlYes
     .Apply
End With
End Sub

Here,

.SortFields.Add Key:=Range(“B4”), Order:=xlAscending and .SortFields.Add Key:=Range(“C4”), Order:=xlAscending: Define cells B4 and C4 as the keys for sorting the associated columns in ascending order.

Since our dataset has headers, we specify Header = xlYes.

VBA Macro to Sort Multiple Column with or without Header

  • Run this code, and your columns with header will be sorted in ascending order.

Result of VBA Macro to Sort Multiple Column with or without Header

Read More: How to Sort Multiple Columns with Excel VBA


Method 4 – Sort Data by Double-Clicking on Header in Excel

If you want to sort data easily by double-clicking on the header, use this VBA code:

Steps:

  • Right-click on the sheet tab.
  • Select View Code from the options.
  • In the code window, paste the following code
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Dim iRange As Range
    Dim iCount As Integer
    iCount = Range("B4:D15").Columns.Count
    Cancel = False
    If Target.Row = 4 And Target.Column <= iCount Then
    Cancel = True
    Set iRange = Range(Target.Address)
    Range("B4:D15").Sort Key1:=iRange, Header:=xlYes
    End If
End Sub
  • Save the code.

VBA Macro to Sort Column by Double Clicking on Header in Excel

  • Return to the worksheet and double-click on the headers to see the columns reorganize.

Result of VBA Macro to Sort Column by Double Clicking on Header in Excel


Things to Remember

  • You can create a named range (e.g., SortRange) and use it instead of specifying cell references directly in the Range.Sort method.
  • If you’re unsure whether your dataset has headers, use the xlGuess parameter to let the system determine it.

Download Workbook

You can download the practice workbook from here:


Related Articles

Get FREE Advanced Excel Exercises with Solutions!

Tags:

Sanjida Ahmed
Sanjida Ahmed

Sanjida Ahmed, who graduated from Daffodil International University with a degree in Software Engineering, has worked with SOFTEKO since 2021. She has written over 100 articles on Excel & VBA and, since 2022, has worked as the Project Manager of the Excel Extension Development Project in the Software Development Department. Since starting this software development, she has established an outstanding workflow encompassing a full SDLC. She always tries to create a bridge between her skills and interests in... Read Full Bio

6 Comments
  1. Thank you for sharing this. These few code snippets helped me improve a working task list shared by my team. I am grateful! Here is my modified code to sort by header a wider list with an unknown amount of rows.

    Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
    Dim iRange As Range
    Dim iCount As Integer
    iCount = Range(“A2”, Range(“I2”).End(xlDown)).Columns.Count
    Cancel = False
    If Target.Row = 1 And Target.Column <= iCount Then
    Cancel = True
    Set iRange = Range(Target.Address)
    Range("A2", Range("I2").End(xlDown)).Sort Key1:=iRange, Header:=xlNo
    End If
    End Sub

  2. Hi is there anyway to sort columns in descending order?? I tried to change the Ascending word to Descending but it doesn’t seem to work

    • Reply Avatar photo
      Naimul Hasan Arif Aug 30, 2022 at 12:27 PM

      Yeah. There are ways to sort columns in descending order.
      You can apply the following VBA in the dataset used in the first method to sort the data in descending order.

      Sub SortSingleColumnWithoutHeader()
      Range(“B5”, Range(“B5”).End(xlDown)).Sort Key1:=Range(“B5”), Order1:=xlDescending, Header:=xlNo
      End Sub

  3. Is there a way to apply the double click to a few selected columns only (e.g. columns C, G and L) but still sort the entire range from A4 to L60?

    • Hi PIET,
      Thanks for your comment. I am replying to you on behalf of ExcelDemy. You can apply the following code. By using this code, you will be able to double-click on any cell from columns C, G, or L and the entire range (A4:L60) will be sorted based on the column of the selected cell.

      Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean)
          Dim srt_rng As Range
          Dim srt_col As Range
          Set srt_rng = Range("A4:L60")
          If Not Intersect(Target, srt_rng) Is Nothing Then
              If Target.Column = 3 Or Target.Column = 7 Or Target.Column = 12 Then
                  Set srt_col = Target.EntireColumn
                  With srt_rng
                      .Sort key1:=srt_col, Order1:=xlAscending, Header:=xlYes
                  End With
                  Cancel = True
              Else
              Exit Sub
              End If
          End If
      End Sub

      I hope this will help you to solve your problem. Please let us know if you have other queries.
      Regards
      Mashhura Jahan
      ExcelDemy.

Leave a reply

Advanced Excel Exercises with Solutions PDF

 

 

ExcelDemy
Logo