Automatically reordering columns

Hewso

New Member
Joined
Jun 26, 2020
Messages
1
Office Version
  1. 2016
Platform
  1. Windows
Hi, I'm struggling to find any solution and hoping there is one. Can I reorder columns based on an order in another list? For example I currently have columns ordered A,B,C,D,E,F but the list i want it to reference tells me the order should be B,E,A,F,C,D. I don't want to have to manually reorder columns every time as it's over 30 columns and is a regular report. Thanks for any help
 

Excel Facts

Ambidextrous Undo
Undo last command with Ctrl+Z or Alt+Backspace. If you use the Undo icon in the QAT, open the drop-down arrow to undo up to 100 steps.
Welcome to MrExcel

Here is one very simple way
Insert 2 rows at the TOP of your sheet
Row1 contains the numbers from 1 (in column A) to 34 in column AH (if that is last column used)
Row2 contains alternative sort (make sure that each number only appears ONCE!!)
Row3 contains data headers, row4 is where the data starts (see picture)

VBA Code:
Sub SortOnRow(aRow As Long)
    Dim x As Long: x = Cells(1, Columns.Count).End(xlToLeft)
    With ActiveSheet.Sort
        .SortFields.Clear
        .SortFields.Add2 Key:=Cells(aRow, 1).Resize(, x), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    End With
    With ActiveSheet.Sort
        .SetRange Range("A:A").Resize(, x)
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlLeftToRight
        .SortMethod = xlPinYin
        .Apply
    End With
End Sub

Call the sub like this
When the input box pops up... enter 1 to sort based on row1, enter 2 to sort based on row2
VBA Code:
Sub CallSub()
    On Error Resume Next
    Call SortOnRow(InputBox("1 or 2", "Rearrange Columns", 1))
    On Error GoTo 0
End Sub

ReOrderColumns.jpg
 
Upvote 0

Forum statistics

Threads
1,214,606
Messages
6,120,485
Members
448,967
Latest member
visheshkotha

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