Excel VBA sort by multiple criteria by successive clicking on a cell/text
- You can improve your code by changing the use of
Range
inRange("active[#Headers]")
andRange("active").Sort
to the built-in properties and methods of aListObject
-ListObject.HeaderRowRange
andListObject.Sort
. Select Case
might be neater as well, instead of multipleIf
statements.Range(Target.Address)
is redundant - you can just useTarget
.Add
ing aSortField
will retain the existing sort options.
Making those changes, your code might look something like this:
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, Cancel As Boolean) Dim lObj As ListObject: Set lObj = Me.ListObjects("active") Dim SortOrder As Long If Not Intersect(Target, lObj.HeaderRowRange) Is Nothing Then Select Case Target.Value Case "Price", "Profit" SortOrder = xlDescending Case Else SortOrder = xlAscending End Select With lObj.Sort .SortFields.Add Key:=Target, SortOn:=xlSortOnValues, Order:=SortOrder .Apply End With End IfEnd Sub
Something along these lines may help you. The sort details are within the worksheet
object, so I've used the range.worksheet relationship, but you could easily declare this as the sheet rather than using this way
Dim r As Excel.RangeDim s As SortDim sf As SortFieldSet r = Range("a1:c7")Set s = r.Worksheet.SortSet sf = s.SortFields.Add(Range("b1"), XlSortOn.xlSortOnValues, XlSortOrder.xlAscending)
I'm not too sure how you'd go about removing specific sorts though, may have to loop them and get the key as s.SortFields.Item(x).Delete
uses an index number for x