Code an Excel VBA sort with a custom order and a value containing commas
It seems to be missing the Apply
. Can you Add
MyWorksheet.Sort.Apply
The custom order you have is working as is in my sample.
EDIT Updated based on OP updated question
Edit the macro to the following - using an array for the OrderCustom parameter.
Dim oWorksheet As WorksheetSet oWorksheet = ActiveWorkbook.Worksheets("Sheet1")Dim oRangeSort As RangeDim oRangeKey As Range' one range that includes all colums do sortSet oRangeSort = oWorksheet.Range("A1:B9")' start of column with keys to sortSet oRangeKey = oWorksheet.Range("B1")' custom sort orderDim sCustomList(1 To 3) As StringsCustomList(1) = "Cyberspace"sCustomList(2) = "Aerospace"sCustomList(3) = "Air, Land, or Sea"Application.AddCustomList ListArray:=sCustomList' use this if you want a list on the spreadsheet to sort by' Application.AddCustomList ListArray:=Range("D1:D3")oWorksheet.Sort.SortFields.ClearoRangeSort.Sort Key1:=oRangeKey, Order1:=xlAscending, Header:=xlGuess, _ OrderCustom:=Application.CustomListCount + 1, MatchCase:=False, _ Orientation:=xlTopToBottom, DataOption1:=xlSortNormal' clean upApplication.DeleteCustomList Application.CustomListCountSet oWorksheet = Nothing
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.