我正在尝试删除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
然而,它并没有像我期望的那样对数据进行排序。我不确定我在这里缺少什么。
答案 0 :(得分:0)
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