Consulting

Results 1 to 2 of 2

Thread: data sorting macro question

  1. #1

    data sorting macro question

    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:
    [VBA]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
    [/VBA]

    Can anyone please help thanks.

  2. #2
    Distinguished Lord of VBAX VBAX Grand Master Bob Phillips's Avatar
    Joined
    Apr 2005
    Posts
    25,453
    Location
    Untested

    [vba]

    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[/vba]
    ____________________________________________
    Nihil simul inventum est et perfectum

    Abusus non tollit usum

    Last night I dreamed of a small consolation enjoyed only by the blind: Nobody knows the trouble I've not seen!
    James Thurber

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •