首页 > 解决方案 > 按值排序

问题描述

我有这个代码:

Private Sub Worksheet_Change(ByVal Target As Excel.Range)

    If Target.Column = 1 Then

        Dim lastRow As Long
        lastRow = Cells(Rows.Count, 1).End(xlUp).Row
        Range("A5:J33" & lastRow).Sort key1:=Range("A5:A33" & lastRow), order1:=x1Ascending, Header:=xlNo

    End If

End Sub

我要排序的范围是 A5:J33,我希望它的排序方式是输入后 A5:A33 中的数据

任何帮助,将不胜感激

标签: excelvbasorting

解决方案


您在 A 列中获得了 lastRow lastRow = Cells(Rows.Count, 1).End(xlUp).Row,但您没有正确实现结果:

Range("A5:J33" & lastRow)并且Range("A5:A33" & lastRow)应该是Range("A5:J" & lastRow)Range("A5:A" & lastRow)

试试下面的修改代码:

Private Sub Worksheet_Change(ByVal Target As Excel.Range)

    If Target.Column = 1 Then

        Dim lastRow As Long

        lastRow = Cells(Rows.Count, 1).End(xlUp).Row

        ActiveSheet.Sort.SortFields.Clear
        ActiveSheet.Sort.SortFields.Add Key:=Range("A1:A" & lastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
        With ActiveSheet.Sort
            .SetRange Range("A1:J" & lastRow)
            .Header = xlGuess
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With

    End If

End Sub

推荐阅读