murdoc98
murdoc98

Reputation: 11

Sort ascending/descending in Excel using VBA sub

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

Upvotes: 0

Views: 1453

Answers (1)

VBasic2008
VBasic2008

Reputation: 54807

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

Upvotes: 0

Related Questions