I use VBA occasionally and I'm getting trapped in the syntax around ranges. I want to take an array as selected on the active sheet and sort each column one at a time returning an array of ordered columns. It seems simple with a for
loop, however, I keep getting errors which I think relate to the scope.
Public Sub Sortrange() 'sorts each column in a range individually low to high
Dim Rng, Sortcol As Range
HH = Selection.Rows.Count
Set Rng = Selection
Srow = Rng(1).Row
SCol = Rng(1).Column
With Rng
For i = 1 To .Columns.Count
A = Srow
B = SCol i - 1
Sortcol = Range(Cells(A, B), Cells(HH, B))
Sortcol.Sort key1:=Range(Cells(A, B))
Next
End With
End Sub
CodePudding user response:
Public Sub Sortrange() 'sorts each column in a range individually low to high
Dim Rng, Sortcol As Range
Dim Srow As Integer, Scol As Integer
Dim A, B, i As Integer
Set Rng = Selection
Dim selRows As Long: selRows = Rng.Rows.Count
Dim selCols As Long: selCols = Rng.Columns.Count
Srow = Rng(1).Row
Scol = Rng(1).Column
With Rng
For i = 1 To selCols
A = Srow
B = Scol i - 1
Set Sortcol = Range(Cells(A, B), Cells(selRows 1, B))
' Sort Column
ActiveSheet.Sort.SortFields.Clear
ActiveSheet.Sort.SortFields.Add2 Key:=Sortcol _
, SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortTextAsNumbers
With ActiveSheet.Sort
.SetRange Sortcol
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
Next
End With
End Sub