Code an Excel VBA sort with a custom order and a value containing commas

前端 未结 2 847
孤独总比滥情好
孤独总比滥情好 2020-11-28 14:57

In VBA, Excel allows sorting values using the CustomOrder parameter to choose the sequence items are ordered. Unfortunately, the sequence of items is delimited by commas and

2条回答
  •  攒了一身酷
    2020-11-28 15:19

    OK...based on the updated description, how about a formula for the column next to what you're sorting.

    So, if "Air, Land, or Sea" is in column B1, then C1 would have this:

    =SUBSTITUTE(B1,",","|")
    

    Then you could do your custom sort like so:

    MyWorksheet.Sort.SortFields.Add Key:=Range( _
    
            "B:B"), SortOn:=xlSortOnValues, Order:=xlAscending, _
            CustomOrder:= "Cyberspace,Air|Land|or Sea,Aerospace", _
            DataOption:=xlSortNormal  
        MyWorksheet.Sort.Apply
    

    Make sure to adjust the range appropriately.

提交回复
热议问题