【问题标题】:Excel VBA: Sort rows Numerically (by column value) THEN sort by one specific stringExcel VBA:对行进行数字排序(按列值)然后按一个特定字符串排序
【发布时间】:2016-06-05 17:37:51
【问题描述】:

我不知道这是否是正确的方法。但是这里。我有一些excel数据:

Column 1 |  Column 2
1        |   open
3        |   issue
7        |   closed
8        |   open

我需要按第 2 列排序(列表顶部带有“open”的所有列,但也使用数字排序,因此带有“8,Open”的行将位于顶部)然后其余行需要排序只有数字最高的数字。

导致:

Column 1 |  Column 2
8        |   open
1        |   open
7        |   closed
3        |   issue

以下是我仅用于数字的代码(第 12 列)。我需要其他方面的帮助。

With ActiveSheet.Sort
    .SortFields.Clear
    .SortFields.Add Key:=Selection.EntireRow.Columns(12), SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
    .SetRange ActiveSheet.Range(Data)
    .Header = xlGuess
    .MatchCase = False
    .Orientation = xlTopToBottom
    .SortMethod = xlPinYin
    .Apply
End With

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    试试这个:

    ActiveSheet.Sort.SortFields.Clear
    ActiveSheet.Sort.SortFields.Add Range("B1"), xlSortOnValues, xlAscending, "Open"
    ActiveSheet.Sort.SortFields.Add Range("A1"), xlSortOnValues, xlDescending
    With ActiveSheet.Sort
        .SetRange Range(Data)
        .Header = xlGuess
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    

    编辑
    _________________________________________________________________________________

    Dim SortStr As Variant
    Dim SortNum As Long
    
    'change below array as per your requirement
    SortStr = Array("Open", "in progress", "almost finished")   
    Application.AddCustomList ListArray:=SortStr
    SortNum = Application.CustomListCount
    
    ActiveSheet.Sort.SortFields.Clear
    ActiveSheet.Sort.SortFields.Add Range("B1"), xlSortOnValues, xlAscending, SortNum
    ActiveSheet.Sort.SortFields.Add Range("A1"), xlSortOnValues, xlDescending
    With ActiveSheet.Sort
        .SetRange Range(Data)
        .Header = xlGuess
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    
    Application.DeleteCustomList Application.CustomListCount
    

    【讨论】:

    • 如果我想按“进行中”之类的附加关键字进行排序,那么“几乎完成”我将如何添加这些元素。所以所有的“在顶部打开”,然后都是“进行中”的数字,等等。
    • 好吧,数字排序工作正常,但是空白字段位于顶部,如果我希望空白字段位于底部,我该怎么办?
    【解决方案2】:

    你可以使用Range对象的Sort方法

    Dim iniRow As Long
    
    With Range("Data")
        .Sort key1:=.Range("B1"), order1:=xlDescending, Header:=xlYes '<~~ first sort by column 2 ("B" in my test)
        iniRow = Application.CountIf(.Columns(2).Cells, "open") '<~~ then count how many "open" are there
        .Offset(iniRow + 1).Resize(.Rows.Count - (iniRow + 1)).Sort key1:=.Range("A" & iniRow + 2), order1:=xlDescending, Header:=xlNo '<~~ finally order remaining by column 1 ("A" in my test)
    End With
    

    【讨论】:

    • @user937036:你试一试了吗?
    猜你喜欢
    • 2015-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-25
    • 1970-01-01
    • 1970-01-01
    • 2014-01-10
    • 2021-07-26
    相关资源
    最近更新 更多