VBA Code to Sort Columns Based on Custom List

OilEconomist

Active Member
Joined
Dec 26, 2016
Messages
439
Office Version
  1. 2019
Platform
  1. Windows
Hello and thanks in advance for any assistance. I am trying to sort a data set in terms of columns based on a Custom List, but I am getting an error which I have posted below.

The following is a sample data set:
Stocks - Analysis Tool - (Active).xlsm
CDE
8InventoryRegionFruit
922NebraskaPear
10100TexasApple
112000FloridaOrange
Test


This is what I would like the final output to look like:
Stocks - Analysis Tool - (Active).xlsm
JKL
8FruitInventoryRegion
9Pear22Nebraska
10Apple100Texas
11Orange2000Florida
Test


I am getting the error "Run-time error '9': Subscript out of Range" on the following line:
VBA Code:
       RngSort.Sort.SortFields.Add2 Key:=RngHdg, SortOn:=xlSortOnValues, _
        Order:=xlAscending, CustomOrder:=ArrayList(), DataOption:=xlSortNormal

Code:
VBA Code:
Option Explicit

Sub SortTest()

 'Dimensining
    Dim ShtNmTest As String
    Dim RngHdg As Range, RngSort As Range, RngKey As Range
    Dim ArrayList() As Variant


  'Code
    
    'Setting sheet name
     ShtNmTest = "Test"
    
    
    'Setting ranges
     With Sheets(ShtNmTest)
        Set RngHdg = .Range(.Cells(8, 3), .Cells(8, 5))
        Set RngSort = .Range(.Cells(8, 3), .Cells(11, 5))
        Set RngKey = .Cells(8, 3) 'I probably don't need this line since I used RngHdg as the key, but here in the case that's part of the issue.
     End With

    
    'Custom List - the order I would like the columns to be re-arranged
     ReDim ArrayList(1 To 3) As Variant
     ArrayList(1) = "Fruit"
     ArrayList(2) = "Inventory"
     ArrayList(3) = "Region"
     
     SortPerHeaderF ShtNmTest, ArrayList, RngHdg, RngSort, RngKey
    
 'Display Updates On
    Application.DisplayAlerts = True

End Sub



Function SortPerHeaderF(ShtNm As String, ArrayList As Variant, RngHdg As Range, RngSort As Range, RngKey As Range) As Variant


 'Display Updates Off
    Application.DisplayAlerts = False
    
    
    'Custom List to Array
     Application.AddCustomList ListArray:=ArrayList


 'Code
 
    'Sort
     With Sheets(ShtNm)
        .Sort.SortFields.Clear
        RngSort.Sort.SortFields.Add2 Key:=RngHdg, SortOn:=xlSortOnValues, _
        Order:=xlAscending, CustomOrder:=ArrayList(), DataOption:=xlSortNormal
        
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlLeftToRight
        .SortMethod = xlPinYin
        .Apply
     End With
    
    'Clean-up
     Application.DeleteCustomList Application.CustomListCount


 'Display Updates On
    Application.DisplayAlerts = True

End Function
 

Excel Facts

Can Excel fill bagel flavors?
You can teach Excel a new custom list. Type the list in cells, File, Options, Advanced, Edit Custom Lists, Import, OK
You're using more code than I would for this task. Please try the following (change the sheet name to suit).

VBA Code:
Option Explicit
    Sub Custom_Sort()
    Dim Ws As Worksheet, LRow As Long, Rng As Range
    
    Set Ws = Worksheets("Test") '<< Change to actual sheet name
    LRow = Ws.Range("C:E").Find("*", , xlFormulas, , 1, 2).Row
    Set Rng = Ws.Range(Ws.Cells(8, 3), Ws.Cells(LRow, 5))
    
    Application.AddCustomList ListArray:=Array("Fruit", "Inventory", "Region")
    With Ws.Sort
        .SortFields.Clear
        .SortFields.Add2 Key:=Range(Ws.Cells(8, 3), Ws.Cells(8, 5)), _
        CustomOrder:=Application.CustomListCount
        .SetRange Rng
        .Orientation = xlLeftToRight
        .Apply
    End With
End Sub
 
Upvote 0
Solution
Excellent news, thanks for the feedback 🙂
Thanks once again @kevin9999. You indicated "You're using more code than I would for this task." It may seem that way because this was part of a much larger code. I simplified where I could and left other instances the same so I did not change the objective to where when I incorporated it into the original, it would work.
 
Upvote 0
Actually, I just noticed that your preferred column order is in alphabetical order left to right anyway (Fruit, Inventory, Region) so I'm guilty of using too much code myself. The following would work just as well:

VBA Code:
Sub test()

    Worksheets("Test").Range("A:C").Sort Key1:=Range("A8:C8"), Order1:=xlAscending, Orientation:=xlLeftToRight

End Sub

Unless of course, you have data above or below the sample you provided...
 
Upvote 0
Actually, I just noticed that your preferred column order is in alphabetical order left to right anyway (Fruit, Inventory, Region) so I'm guilty of using too much code myself. The following would work just as well:

VBA Code:
Sub test()

    Worksheets("Test").Range("A:C").Sort Key1:=Range("A8:C8"), Order1:=xlAscending, Orientation:=xlLeftToRight

End Sub

Unless of course, you have data above or below the sample you provided...
Thanks @kevin9999, but I think my example coincidentally had the data that way, so I needed what your original solution provided.
 
Upvote 0

Forum statistics

Threads
1,223,896
Messages
6,175,262
Members
452,627
Latest member
KitkatToby

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top