To post as a guest, your comment is unpublished.· 4 months agoHi, Rob,The above code works well in my Excel, can you give your problem a screenshot here?
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:
You are guest
or post as a guest, but your post won't be published automatically.
To post as a guest, your comment is unpublished.· 4 months agoNo can do crackerjack - don't work
To post as a guest, your comment is unpublished.· 10 months agoDoesn't work, nothing happens, know how to create module in vba, did that, saved and nothing when header double clicked. Please fix it.
To post as a guest, your comment is unpublished.· 1 years agoWorks ok to ascend, double click a 2nd time as stated to descend does nothing