OilEconomist
Active Member
- Joined
- Dec 26, 2016
- Messages
- 439
- Office Version
- 2019
- Platform
- 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:
This is what I would like the final output to look like:
I am getting the error "Run-time error '9': Subscript out of Range" on the following line:
Code:
The following is a sample data set:
Stocks - Analysis Tool - (Active).xlsm | |||||
---|---|---|---|---|---|
C | D | E | |||
8 | Inventory | Region | Fruit | ||
9 | 22 | Nebraska | Pear | ||
10 | 100 | Texas | Apple | ||
11 | 2000 | Florida | Orange | ||
Test |
This is what I would like the final output to look like:
Stocks - Analysis Tool - (Active).xlsm | |||||
---|---|---|---|---|---|
J | K | L | |||
8 | Fruit | Inventory | Region | ||
9 | Pear | 22 | Nebraska | ||
10 | Apple | 100 | Texas | ||
11 | Orange | 2000 | Florida | ||
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