0
votes

I want to sort an amount of data in Excel. It should toggle between ascending and descending on every click.

I'd found this problem solved in the next thread: sort ascending/descending vba excel.

But I want to do some changes in the code. I want to sort using the current column where I clicked (the headers). I don't know if this is possible using just one macro and sending the cell where I call the event.

Here is the code that I'm using:

Worksheet (where I call the Sub):

Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range("A2:C2")) Is Nothing Then
            Call sort_table(Target)
        End If
    End If
End Sub

Sub:

Sub sort_by_letters(Order As Range)
    Dim dataRange As Range
    Dim fieldOrder As Range
    Dim xlSort As XlSortOrder
    Dim LastRow As Long

    With ActiveSheet
        Set LastRow = .Cells(.Rows.Count, Order).End(xlUp).Row
    End With

    If (Order.Value > Range(Column(Order) & CStr(LastRow))) Then
        xlSort = xlAscending
    Else
       xlSort = xlDescending
    End If

    Set dataRange = Range("A2:C" & LastRow)
    Set campoOrden = Order

    dataRange.Sort key1:=fieldOrder, order1:=xlSort, Header:=xlYes

End Sub
1
Can you provide an example? What are the headers looking like, and how could they drive the way of sorting another column?Matteo NNZ
This is the example that I'm using, when I click the headers this shoukd be taken as the pivot column, and toggle between ascendenc and descendent sorting. Here is the table's example imgur.com/a/NQA5oikmurdoc98

1 Answers

0
votes

Sort on Selection Change

Sheet Module e.g. Sheet1

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Selection.Count = 1 Then
        If Not Intersect(Target, Range(strHeaders)) Is Nothing Then
            SortTable Target
        End If
    End If
End Sub

Standard Module e.g. Module1

Public Const strHeaders As String = "A2:C2"

Sub SortTable(Target As Range)

    Dim LuCell As Range         ' Last Used Cell Range
    Dim rngS As Range           ' Sort Range
    Dim xlSort As XlSortOrder   ' Sort Order

    ' In Target Worksheet
    With Target.Worksheet
        ' Calculate last used cell in Target Column.
        Set LuCell = .Cells(.Rows.Count, Target.Column).End(xlUp)
        ' Check if value in first row below Headers in Target Column is greater
        ' than value in Last Used Cell Range.
        If Target.Offset(1) > LuCell Then
            xlSort = xlAscending
        Else
            xlSort = xlDescending
        End If
        ' In Headers Range
        With .Range(strHeaders)
            ' Calculate Sort Range.
            ' Create a reference to Sort Range.
            Set rngS = .Resize(LuCell.Row - .Row + 1)
        End With
    End With
    ' Sort Sort Range.
    rngS.Sort Key1:=Target, Order1:=xlSort, Header:=xlYes

 End Sub