按特定行排序列

时间:2016-02-03 07:31:28

标签: vba sorting

我想按升序对“E列”排序“lastColumn”。 用于排序的值在第14行中 数据集位于单元格E8到“lastColumn”“lastRow”。

以下是我到目前为止所得到的内容,但我收到的错误是该引用无效。我猜我没有使用& lastRow&正确地说,更不用说试图插入“lastColumn”的值。

我使用lastColumn和lastRow作为忽略空白单元格的方法。

Sub SortColumns()

Dim lastColumn As Long
Dim lastRow As Long

lastColumn = Sheet1.Cells(8, Columns.Count).End(xlToLeft).Column
lastRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row

ActiveWorkbook.ActiveSheet.Sort.SortFields.Clear

ActiveWorkbook.ActiveSheet.Sort.SortFields.Add Key:=Range( _
    "E14:Z" & lastRow&), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.ActiveSheet.Sort
    .SetRange Range("E8:I" & lastRow)
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlLeftToRight
    .SortMethod = xlPinYin
    .Apply
End With

End Sub

1 个答案:

答案 0 :(得分:0)

我认为你只有一个小错误。我添加了一些代码,因为您应始终具体说明哪个工作簿以及您正在使用哪个工作表。试试这个:

Dim lastColumn As Long
Dim lastRow As Long

Dim Sht1 As Worksheet
Sht1 = ActiveWorkbook.Sheets("Sheet1")

lastColumn = Sht1.Cells(8, Sht1.Columns.Count).End(xlToLeft).Column
lastRow = Sht1.Cells(Sht1.Rows.Count, 1).End(xlUp).Row

Sht1.Sort.SortFields.Clear

Sht1.Sort.SortFields.Add Key:=Range( _
    "E14:Z" & lastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With Sht1.Sort
    .SetRange Range("E8:I" & lastRow)
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlLeftToRight
    .SortMethod = xlPinYin
    .Apply
End With