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?
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 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:
Best Office Productivity Tools
Supercharge Your Excel Skills with Kutools for Excel, and Experience Efficiency Like Never Before. Kutools for Excel Offers Over 300 Advanced Features to Boost Productivity and Save Time. Click Here to Get The Feature You Need The Most...
Office Tab Brings Tabbed interface to Office, and Make Your Work Much Easier
- Enable tabbed editing and reading in Word, Excel, PowerPoint, Publisher, Access, Visio and Project.
- Open and create multiple documents in new tabs of the same window, rather than in new windows.
- Increases your productivity by 50%, and reduces hundreds of mouse clicks for you every day!