Using different range to sort numerous columns with different row lengths

CBlauv

New Member
Joined
Jul 9, 2022
Messages
3
Office Version
  1. 365
Platform
  1. Windows
I am using this snippet from recorder.

VBA Code:
Columns("O:O").Select 
Dim SortO As Long
   SortO = Range("O" & Rows.Count).End(xlUp).Row
  
   ActiveWorkbook.Worksheets("data").Sort.SortFields.Clear
   ActiveWorkbook.Worksheets("data").Sort.SortFields.Add2 Key:=Range("O2:O" & SortO) _
       , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
   With ActiveWorkbook.Worksheets("data").Sort
       .SetRange Range("O1:O" & SortO)
       .Header = xlYes
       .MatchCase = False
       .Orientation = xlTopToBottom
       .SortMethod = xlPinYin
       .Apply
   End With
Columns("P:P").Select


I added the Row length part since each column I need to sort has a different length. I need to sort from column O all they way to column CJ.
I'm sure there is an easier way other then writing a block for each column, I am fairly new and looking for a better solution.
In advance any and all help is appreciated.
 

Excel Facts

Create a chart in one keystroke
Select the data and press Alt+F1 to insert a default chart. You can change the default chart to any chart type
The following code assumes you don't have any data located below the range in each column. Please try it on a copy of your data.

VBA Code:
Option Explicit
Sub Sort_Many()
    Application.ScreenUpdating = False
    Dim ws As Worksheet, lr As Long, i As Long
    Set ws = Worksheets("data")
    ws.Sort.SortFields.Clear
    
    For i = 15 To 88
        ws.Columns(i).Sort Key1:=Cells(1, i), order1:=1, Header:=1
        ws.Sort.SortFields.Clear
    Next i
    
    Application.ScreenUpdating = True
End Sub
 
Upvote 0

Forum statistics

Threads
1,215,766
Messages
6,126,761
Members
449,336
Latest member
p17tootie

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