PDA

View Full Version : data sorting macro question



puppy123
08-13-2011, 08:38 PM
I want to record a macro which sorts a range of data in ascending order. The macro must work on any selected data, not just on the cells where it was recorded. I can only make the macro work on the cell where it was recorded, not sure how to make it work on any selected data. Below is my code:
Sub Macro5()
'
' Macro5 Macro
'
' Keyboard Shortcut: Ctrl+s
'
Range("A4").Select
ActiveWorkbook.Worksheets("samp").Sort.SortFields.Clear
ActiveWorkbook.Worksheets("samp").Sort.SortFields.Add Key:=Range("A4"), _
SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
With ActiveWorkbook.Worksheets("samp").Sort
.SetRange Range("A2:B4")
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End Sub


Can anyone please help thanks.

Bob Phillips
08-14-2011, 04:29 AM
Untested



Sub Macro5()

With ActiveSheet

.Sort.SortFields.Clear
.Sort.SortFields.Add Key:=Selection.Cells(1, 1), _
SortOn:=xlSortOnValues, _
Order:=xlAscending, _
DataOption:=xlSortNormal
With .Sort

.SetRange Selection
.Header = xlNo
.MatchCase = False
.Orientation = xlTopToBottom
.SortMethod = xlPinYin
.Apply
End With
End With
End Sub