使用sub

时间:2019-03-17 22:16:08

标签: excel vba sorting

我想在Excel中对大量数据进行排序。每次点击时,它应该在升/降之间切换。

我在下一个线程中发现了此问题: sort ascending/descending vba excel

但是我想对代码进行一些更改。 我想使用单击的当前栏目(标题)进行排序,我不知道是否可以仅使用一个宏并将该单元格发送给我调用事件的地方,谢谢高级。 这是我正在使用的代码。

工作表(我称其为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 个答案:

答案 0 :(得分:0)

更改选择时排序

Sheet模块,例如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

标准模块,例如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