Sub Main()
Sort Range(”A2:C5″), “C”, xlAscending
End Sub
Sub Sort(DataRangeWithoutHeader As Range, ColumnLetterToSort As String, SortOrder As XlSortOrder)
Dim OriginalSelectedRange As Range
Dim keyRange As Range
Dim Column As Variant
Dim ColumnVisibility As New Collection
‘Remeber what was selected
Set OriginalSelectedRange = Selection
‘prevent user from watching the screen update
Application.ScreenUpdating = False
‘unhide any hidden cols and add to Collection Variable
For Each Column In DataRangeWithoutHeader.Columns
If Column.EntireColumn.Hidden = True Then
Column.EntireColumn.Hidden = False
ColumnVisibility.Add Column
End If
Next Column
‘clear
ActiveSheet.Sort.SortFields.Clear
’sort
Set keyRange = Range(ColumnLetterToSort & DataRangeWithoutHeader.Row & “:” & ColumnLetterToSort & DataRangeWithoutHeader.End(xlDown).Row)
ActiveSheet.Sort.SortFields.Add key:=keyRange, SortOn:=xlSortOnValues, order:=SortOrder, DataOption:=xlSortNormal
With ActiveSheet.Sort
.SetRange DataRangeWithoutHeader
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
‘put back any hidden columns
Do While ColumnVisibility.Count > 0
Set Column = ColumnVisibility.Item(1)
Column.EntireColumn.Hidden = True
ColumnVisibility.Remove (1)
Loop
‘Select the original range
OriginalSelectedRange.Select
‘Restore Default
Application.ScreenUpdating = True
End Sub
Filed under: Columns, General
Trackback Uri