Custom order sort

前端 未结 2 1795
温柔的废话
温柔的废话 2021-01-16 09:38

Hi I would like to sort the whole C column based on the values(Critical, high, medium,low). I am running this code on macro enabled worksheet

Here is my code.

<
相关标签:
2条回答
  • 2021-01-16 09:59

    Your custom sort criteria needs to be in an array. Try,

    Sub runSortC()
        Dim vCustom_Sort As Variant, rr As Long
    
        vCustom_Sort = Array("Critical","High","Medium","Low", Chr(42))
        Application.AddCustomList ListArray:=vCustom_Sort
    
        with Range("C:C")
            .parent.Sort.SortFields.Clear
    
            'sort on custom order with header
            .Cells.Sort Key1:=.Columns(1), Order1:=xlAscending, _
                        Orientation:=xlTopToBottom, Header:=xlYes, MatchCase:=False, _
                        OrderCustom:=Application.CustomListCount + 1
    
            .parent.Sort.SortFields.Clear
    
        End With
    
    End Sub
    

    If this is in a public module, a qualified parent worksheet reference would help.

    0 讨论(0)
  • 2021-01-16 10:12

    Try:

    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add2 Key:=Range("A:A") _
        , SortOn:=xlSortOnValues, Order:=xlAscending, CustomOrder:= _
        "Critical,High,Medium,Low", DataOption:=xlSortNormal
    
        With ActiveWorkbook.Worksheets("Sheet1").Sort
        .SetRange Range("A:A")
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    
    0 讨论(0)
提交回复
热议问题