[英]Why isn't my VBA sorting my column data correctly?
I am trying to delete the first row of the Excel sheet and sort a specific column using its name "CUST_RELPO". 我正在尝试删除Excel工作表的第一行,并使用其名称“ CUST_RELPO”对特定列进行排序。 I am using the column header name since the name may change.
我正在使用列标题名称,因为名称可能会更改。
Sorting and copying the column from the second row since I do need to copy the column header. 由于我确实需要复制列标题,因此对第二行的列进行排序和复制。
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
However, it is not sorting the data like I am expecting. 但是,它并没有像我期望的那样对数据进行排序。 I am not sure what I am missing here.
我不确定我在这里缺少什么。
Key:=ActiveSheet.UsedRange
is a complete misunderstanding of the sort method. Key:=ActiveSheet.UsedRange
是对排序方法的完全误解。 (Usedrange covers the whole used area on the sheet - often "empty" cells, too.) The same applies to .SetRange ActiveSheet.UsedRange
. (Usedrange覆盖了工作表上的整个已用区域-通常也为“空”单元格。).
.SetRange ActiveSheet.UsedRange
。 It is not bad just needless. 没必要,这还不错。
SetRange
is needed when you want to limit the area to be sorted. 当您想限制要排序的区域时,需要
SetRange
。 If you want to sort on only one key (column), then change this 如果您只想按一个键(列)排序,请更改此键
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
to this: 对此:
With ActiveWorkbook.Worksheets("BACKORDER").Sort
.Key rngcustrelpo
.Header = xlYes
.MatchCase = False
.Order:=xlAscending
.Orientation = xlTopToBottom
.SortOn:=xlSortOnValues
.DataOption:= xlSortTextAsNumbers
.SortMethod = xlPinYin
.Apply
End With
And you can find more info here: Excel SortFields add then sort and here: Most efficient way to sort and sort syntax VBA 您可以在此处找到更多信息: Excel SortFields添加然后排序,并在这里: 排序和排序语法VBA的最有效方法
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.