我希望在某些标准种类的最后选择范围内进行自定义排序。首先,我们对范围进行排序" C"然后" R"然后" G"最后我希望对状态进行排序 - 这是自定义排序部分。但这是非常错误的。我知道我需要一个List数组,除此之外我不确定如何解决这个问题...请帮忙!
Dim keyRange(1 To 5) As String
keyRange(1) = "L-2sd"
keyRange(2) = "L-1sd"
keyRange(3) = "P"
keyRange(4) = "U+1sd"
keyRange(5) = "U+2sd"
Application.AddCustomList ListArray:=keyRange
sortNum = Application.CustomListCount
'Dim sortNum As Long
ThisWorkbook.Sheets("Order").Activate
ThisWorkbook.Sheets("Order").Range("A1:" & Letter & 10000).Select
Selection.Sort key1:=Range("C"), Order1:=xlAscending,key2:=Range("R"), order2:=xlAscending, key3:=Range("G"), order3:=xlAscending,
key4:=Range("status"), Order1:=xlAscending, OrderCustom:=Application.CustomListCount + 1
答案 0 :(得分:4)
您可以对VBA中的多个列进行排序,超过3个,但您必须使用不同的方法:
With ThisWorkbook.Worksheets("Order")
.Sort.SortFields.Clear
.Sort.SetRange .Range("A1:" & Letter & 10000)
.Sort.SortFields.Add .Columns("C")
.Sort.SortFields.Add .Columns("R")
.Sort.SortFields.Add .Range("status").EntireColumn
' You can add many more fields... for sorting
.Sort.Apply
End With
修改强>
要使用自定义顺序对字段进行排序,您需要将自定义顺序设置为以逗号分隔的字符串:
Dim custom As String: custom = "L-2sd, L-1sd, P, U+1sd, U+2sd"
...
.Sort.SortFields.Add Key:=Range("D2:D10000"),..., CustomOrder:=custom
答案 1 :(得分:1)
这个建议很有效。我仍然有个性化订单的问题。 我的代码:
Dim keyRange As Variant
Dim KeyRange1 As Variant
Dim sortNum As Long
Dim SortNum1 As Long
keyRange = Array("L-2sd", "L-1sd", "P", "U+1sd", "U+2sd")
KeyRange1 = Array("A", "D", "S", "T", "F")
Application.AddCustomList ListArray:=KeyRange
sortNum = Application.CustomListCount
Application.AddCustomList ListArray:=KeyRange1
SortNum1 = Application.CustomListCount
With ThisWorkbook.Worksheets("Order")
.Sort.SortFields.Clear
.Sort.SetRange .Range("A1:" & Letter & 10000)
.Sort.SortFields.Add Key:=Range("A2:A10000"), SortOn:=xlSortOnValues, Order:=xlAscending, _
DataOption:=xlSortNormal
.Sort.SortFields.Add Key:=Range("B2:B10000"), SortOn:=xlSortOnValues, Order:=xlAscending, _
DataOption:=xlSortNormal
.Sort.SortFields.Add Key:=Range("C2:C10000"), SortOn:=xlSortOnValues, Order:=xlAscending, _
DataOption:=xlSortNormal
.Sort.SortFields.Add Key:=Range("D2:D10000"), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:=SortNum1, DataOption:=xlSortNormal
.Sort.SortFields.Add Key:=Range("E2:E10000"), SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:=SortNum DataOption:=xlSortNormal
' You can add many more fields... for sorting
.Sort.Apply
End With
我无法按照我的意愿将最后一列排序。目前它只是按字母顺序排序。我希望它按照与KeyRange
相同的顺序排序