Sorting columns based on date in vba

Sayan2795

New Member
Joined
Sep 8, 2018
Messages
13
Hi,
I need to sort columns of data which are arranged as following

B1-10/2/2018
C1-11/2/2018
D1-12/2/2018

AND BELOW THEM IS DATA
The dates are the data headers
I need to sort the columns A,B,C,D such that the column with recent date comes first with the data and so on
Please help
Thank you
 

Excel Facts

Last used cell?
Press Ctrl+End to move to what Excel thinks is the last used cell.
Assuming ...
- no blanks in the header row to the right of B1
- that the dates are actual dates (numbers) not text
- no duplicate date headers
... see if this does what you want.

Test in a copy of your workbook.

Code:
Sub Sort_Columns()
  Dim rHdrs As Range
  Dim SL As Object
  Dim i As Long, cols As Long
  Dim sNewHdrs
  
  Set SL = CreateObject("System.Collections.Sortedlist")
  Set rHdrs = Range("B1", Range("B1").End(xlToRight))
  cols = rHdrs.Columns.Count
  For i = 1 To cols
    SL.Add rHdrs.Cells(i).Value, i
  Next i
  Application.ScreenUpdating = False
  Columns("B").Resize(, cols).Insert
  sNewHdrs = rHdrs.Address
  For i = 0 To SL.Count - 1
    Range(sNewHdrs).Columns(SL.getbyindex(i)).EntireColumn.Cut Destination:=Range("B1").Offset(, cols - 1 - i)
  Next i
  Application.ScreenUpdating = True
End Sub
 
Upvote 0

Forum statistics

Threads
1,214,905
Messages
6,122,175
Members
449,071
Latest member
cdnMech

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