自定义sorting与自定义sorting

我想根据列G的值对行进行sorting。 有3个可能的值: 绿色红色黄色 。 我想要在绿色顶部sorting的行,然后是黄色 ,然后是红色

我尝试的所有结果都按字母顺序排列: 绿色红色, 黄色 。 列R有一个二级sorting,但是工作正常。

我的最新代码如下。 rr是最后一行的编号。 我已经尝试过,没有Order1:=xlAscending

sCustomList =“绿色”“黄色”“红色”

 Application.AddCustomList ListArray:=sCustomList Range("A3:T" & rr).Sort Key1:=Range("G3:G" & rr), Order1:=xlAscending, _ OrderCustom:=Application.CustomListCount + 1, MatchCase:=False, _ DataOption1:=xlSortNormal, Key2:=Range("R3:R" & rr), Order2:=xlAscending 

看看你的代码, sCustomList看起来像一个stringtypesvariables,而不是一个变体数组。 自定义sorting列表的成功是每次创build一个新列表并使用最高索引号引用它。

 Sub custom_sort() Dim vCustom_Sort As Variant, rr As Long vCustom_Sort = Array("green", "yellow", "red", Chr(42)) Application.AddCustomList ListArray:=vCustom_Sort With Worksheets("Sheet2") '<~~ set this properly! .Sort.SortFields.Clear rr = .Cells(Rows.Count, "G").End(xlUp).Row With .Range("A3:T" & rr) 'use this to presort one or more secondary fields before the primary custom sort '.Cells.Sort Key1:=.Columns(18), Order1:=xlAscending, _ Key2:=.Columns(1), Order2:=xlDescending, _ Orientation:=xlTopToBottom, Header:=xlYes .Cells.Sort Key1:=.Columns(7), Order1:=xlAscending, _ Orientation:=xlTopToBottom, Header:=xlYes, MatchCase:=False, _ OrderCustom:=Application.CustomListCount + 1 End With .Sort.SortFields.Clear End With End Sub 

.Cells.Sort.SortFields.Add.Cells.Sort之间有一个扭曲,通常会产生一些混淆。 .SortFields.Add方法使用CustomOrder:=参数,而Range.Sort方法使用OrderCustom:=参数。 这两者绝对不是一回事,而是经常交替使用,造成灾难性后果。

如果使用SortFields对象,则不必引用自定义列表:在下面哪里更改各种范围引用应该是显而易见的。 我还在G之外的其中一列上添加了按字母sorting的sorting


 Option Explicit Sub TrafficLightSort() Dim WS As Worksheet Dim rSortRange As Range, rSortKey As Range Const sSortOrder As String = "Green,Yellow,Red" Set WS = Worksheets("sheet1") With WS Set rSortRange = Range("E1", .Cells(.Rows.Count, "E").End(xlUp)).Resize(columnsize:=3) Set rSortKey = rSortRange.Columns(3) With .Sort.SortFields .Clear .Add Key:=rSortKey, _ SortOn:=xlSortOnValues, _ Order:=xlAscending, _ CustomOrder:=sSortOrder .Add Key:=rSortRange.Columns(1), _ SortOn:=xlSortOnValues, _ Order:=xlAscending End With With .Sort .SetRange rSortRange .Header = xlNo .MatchCase = False .Orientation = xlTopToBottom .Apply End With End With End Sub 

我build议添加一个明确的sorting顺序到您的工作表(绿色= 1,黄色= 2等)表。 然后将一列添加到您的sorting范围,使用查找函数返回sorting值,并使用VBA运行基于该列的标准sorting。 这将使您得到更容易让开发人员阅读的VBA代码,允许不阅读VBA的Excel用户查看您的sorting顺序,并避免在您的macros中埋藏硬编码值。