How to sort column data by clicking on header in Excel?
Supposing, I have a range of data, now, I would like to sort the data in ascending or descending order by clicking on any column header to get the following screenshot shown. How could you solve this job in Excel?
Enable you to do smarter, faster and better
Normally, in Excel, you can apply the Sort feature to sort the data quickly and easily, but, to sort data by just clicking on a cell, the following VBA code can do you a favor.
1. Right click the sheet tab that you want to sort data by clicking on a cell, and choose View Code from the context menu, and in the opened Microsoft Visual Basic for applications window, copy and paste the following code into the blank Module:
VBA code: Sort data by click on a cell or column header:
Public blnToggle As Boolean Private Sub Worksheet_BeforeDoubleClick _ (ByVal Target As Range, Cancel As Boolean) 'Updateby Extendoffice 20161123 Dim LastColumn As Long, keyColumn As Long, LastRow As Long Dim SortRange As Range LastColumn = _ Cells.Find(What:="*", After:=Range("A1"), _ SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column keyColumn = Target.Column If keyColumn > LastColumn Then Exit Sub Application.ScreenUpdating = False Cancel = True LastRow = Cells(Rows.Count, keyColumn).End(xlUp).Row Set SortRange = Target.CurrentRegion blnToggle = Not blnToggle If blnToggle = True Then SortRange.Sort _ Key1:=Cells(2, keyColumn), Order1:=xlAscending, Header:=xlYes Else SortRange.Sort _ Key1:=Cells(2, keyColumn), Order1:=xlDescending, Header:=xlYes End If Set SortRange = Nothing Application.ScreenUpdating = True End Sub
2. And then save and close the code window, now, when you double click any cell or column header within the data range, the column will be sorted in ascending order, if you double click it again, the column will be sorted descending at once.
More related articles: