Log in

View Full Version : VBA - Sorting by columns



Rasm
09-21-2012, 03:34 AM
I use the code below to sort my data by rows -- is there a way I can sort columns - based upon numeric values in a row --- I suppose I could transpose the data then sort - then transpose the data again





Public HeaderRow as long
Sub SortAscending()
Select Case ActiveCell.Row
Case HeaderRow
If IsEmpty(ActiveCell.Value) Then Exit Sub
Static MySortType As Integer
MySortType = xlAscending
ActiveCell.CurrentRegion.Offset(1).Sort Key1:=ActiveCell, Order1:=MySortType, Header:=xlYes
End Select
End Sub

snb
09-23-2012, 02:39 AM
The sorting orientation is one of the sort method's arguments.
To sort by columns use:


Sub SortAscending()
Sheet1.Cells(1).CurrentRegion.Sort Sheet1.Cells(1), 2, , , , , , 1, , , 2
End Sub

princ_wns
09-24-2012, 04:18 PM
Hi Rasm,

Here is my code that i had used in one of my project where i had to sort the Columns based on the date in their first cell value that were containing date in. As you see the range starts at G1 upto it last non blank cell to its right.Then this range got sorted on the behalf of the data in it . Date as data in my case.




Public Sub SortDate_Columns()

Dim rngDate As Range
Dim rngCell As Range
Dim intCol As Integer

With ThisWorkbook.Worksheets("TempCalls")
Set rngDate = .Range("G1", .Range("G1").End(xlToRight))
Set rngDate = Intersect(rngDate.CurrentRegion, rngDate.CurrentRegion.Offset(0, 6))
With rngDate
.Sort .Cells(1), 1, , , , , , xlYes, , , 2
End With
End With
Set rngDate = Nothing
Set rngCell = Nothing
End Sub