将列中的单元格从A到Z排序

时间:2014-03-07 19:30:45

标签: excel vba excel-vba filter

代码来自略微编辑的宏。我试图删除“凌乱的代码”,但它无法正常工作。它的目的是将BF列中的数据从A到Z进行排序。

 Dim InSheet As Worksheet
    Set InSheet = ThisWorkbook.Worksheets("A to Z")
 Dim LastRow as Integer
   LastRow = InSheet.Cells(Rows.Count, 58).End(xlUp).Row

 InSheet.Select
     Columns("BF:BF").Select
 InSheet.Sort.SortFields.Clear
 InSheet.Sort.SortFields.Add Key:=Range( _
    "BF1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
  With InSheet.Sort
    .SetRange Range("A1:BF" & LastRow)
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

所以我尝试了这个并且它无法正常工作:

 Dim InSheet As Worksheet
    Set InSheet = ThisWorkbook.Worksheets("A to Z")
 Dim LastRow as Integer
   LastRow = InSheet.Cells(Rows.Count, 58).End(xlUp).Row

 InSheet.Columns("BF:BF")
 InSheet.Sort.SortFields.Clear
 InSheet.Sort.SortFields.Add Key:=Range( _
    "BF1"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
    xlSortNormal
  With InSheet.Sort
    .SetRange Range("A1:BF" & LastRow)
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

任何想法?我想真的避免。选择其他东西 - 因为它大大降低了性能。

非常感谢

2 个答案:

答案 0 :(得分:5)

您可以直接使用Key对Range进行排序,而不使用其他代码。

Range("A1:BF" & LastRow).SORT Key1:=Range("BF1"), Order1:=xlAscending_
        Header:=xlGuess, OrderCustom:=1, MatchCase:=False, Orientation:= _
        xlTopToBottom, DataOption1:=xlSortNormal

答案 1 :(得分:3)

所以我使用了你们两个人提供的建议,这最终很有效:

Dim InSheet As Worksheet
    Set InSheet = ThisWorkbook.Worksheets("A to Z")
    Dim LastRow As Integer
        LastRow = InSheet.Cells(Rows.Count, 58).End(xlUp).Row


With InSheet.Sort  ' sort data from A to Z
    .SetRange InSheet.Range("A1:BF" & LastRow)
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With