【问题标题】:Why isn't my VBA sorting my column data correctly?为什么我的 VBA 不能正确排序我的列数据?
【发布时间】:2018-02-15 00:01:12
【问题描述】:

我正在尝试删除 Excel 工作表的第一行并使用其名称“CUST_RELPO”对特定列进行排序。我正在使用列标题名称,因为名称可能会更改。

排序并从第二行复制列,因为我确实需要复制列标题。

Sub ClearFirstRow()
'
' ClearFirstRow Macro
'

'
Rows("1:1").Select
    Selection.Delete Shift:=xlUp
    Cells.Select
  Dim rngcustrelpo As Range
  xindex = Application.ActiveCell.Column
  Set rngcustrelpo = ActiveSheet.UsedRange.Find("CUST_RELPO")
  If rngcustrelpo Is Nothing Then
    MsgBox "CUST_RELPO column was not found."
    Exit Sub
    End If
    'Cells.Select
    Range(rngcustrelpo, rngcustrelpo.End(xlDown)).Select
    ActiveWorkbook.Worksheets("BACKORDER").Sort.SortFields.Add Key:=ActiveSheet.UsedRange, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortTextAsNumbers
    With ActiveWorkbook.Worksheets("BACKORDER").Sort
        .SetRange ActiveSheet.UsedRange
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Set rngcustrelpo1 = rngcustrelpo.Offset(1, 0)
    Range(rngcustrelpo1, rngcustrelpo1.End(xlDown)).Select
    Selection.Copy
End Sub

但是,它并没有像我期望的那样对数据进行排序。我不确定我在这里缺少什么。

【问题讨论】:

  • 我正在检查 CustRelPO 是否存在,然后继续排序...我在排序时指定范围有问题。
  • 多描述一下你的结果。列标题在第 2 行吗?如果您单步执行 (F8),它会到达排序的代码行吗?
  • 只是猜测-你能把ActiveSheet.UsedRange换成Selection试试吗?

标签: vba excel


【解决方案1】:

Key:=ActiveSheet.UsedRange是对排序方法的完全误解。 (Usedrange 覆盖了工作表上的整个使用区域——通常也是“空”单元格。)这同样适用于.SetRange ActiveSheet.UsedRange。这不是坏事,只是没必要。 SetRange 当你想限制要排序的区域时需要。如果您只想对一个键(列)进行排序,请更改此

ActiveWorkbook.Worksheets("BACKORDER").Sort.SortFields.Add Key:=ActiveSheet.UsedRange, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= xlSortTextAsNumbers
With ActiveWorkbook.Worksheets("BACKORDER").Sort
    .SetRange ActiveSheet.UsedRange
    .Header = xlYes
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

到这里:

With ActiveWorkbook.Worksheets("BACKORDER").Sort
    .Key rngcustrelpo
    .Header = xlYes
    .MatchCase = False
    .Order:=xlAscending
    .Orientation = xlTopToBottom
    .SortOn:=xlSortOnValues
    .DataOption:= xlSortTextAsNumbers
    .SortMethod = xlPinYin
    .Apply
End With

您可以在此处找到更多信息:Excel SortFields add then sort 和此处:Most efficient way to sort and sort syntax VBA

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-10-23
    • 1970-01-01
    相关资源
    最近更新 更多