简体   繁体   English

使用 VBA sub 在 Excel 中升序/降序排序

[英]Sort ascending/descending in Excel using VBA sub

I want to sort an amount of data in Excel.我想在 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 .我发现这个问题在下一个线程中得到了解决: 排序升序/降序 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):工作表(我称之为 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

Sort on Selection Change按选择更改排序

Sheet Module eg Sheet1片模块例如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 eg Module1标准模块,例如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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM