excel - 如何将列中的单元格从 A 到 Z 排序?

标签 excel vba

该代码来自稍微编辑过的宏。我尝试删除“困惑代码”,但它不起作用。其目的是将 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

有什么想法吗?我真的想避免 .select 其他东西,因为它会极大地降低性能。

最佳答案

您可以直接使用键对范围进行排序,而无需使用其余代码。

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

关于excel - 如何将列中的单元格从 A 到 Z 排序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22259045/

相关文章:

excel - 根据单元格值在下面插入行

vba - 使用 For 循环在多个工作表上运行具有 1、2、3、4 等有序名称的宏

vba - Countifs VBA 计算非空白单元格

vba - Excel VBA 中的定时警报

VBA Find 函数忽略百分比 -> 只查找小数

excel - 如何计算一个范围内值小于excel中另一个单元格的单元格?

vba - "if not instr"无法像我想象的那样在 vba 中工作

python - 如何使用Python循环遍历多个Excel工作表并对数据进行排序?

excel - 在 Excel 的 Power Query 中将日期转换为序列号

excel - 如何在Excel生成Jasper报告中添加VBA Excel脚本?