Home » excel » vba – Macro to sort Excel only on highlighted text

vba – Macro to sort Excel only on highlighted text

Posted by: admin May 14, 2020 Leave a comment


So this is literally the first time I’ve ever attempted to create a macro in Excel, so wondering if anyone can help me out. I’ve got a spreadsheet that is several pages long, with several different, yet similar sets of data. The different data sets are for different customers, and I need to keep them separate, but I’d like to create a macro to organize the different sets of data by column B, then by column D. I started with this macro:

Sub Sort_Twice()
' Sort_Twice Macro

    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("B2:B12") _
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    ActiveWorkbook.Worksheets("Sheet1").Sort.SortFields.Add Key:=Range("D2:D12") _
        , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
    With ActiveWorkbook.Worksheets("Sheet1").Sort
        .SetRange Range("A1:G12")
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
    End With
End Sub

So this will sort everything between A1 and G12 because that’s what I had highlighted when I started recording. Any suggestion on how to get to allow me to highlight a new block and run the macro only on those fields? The only things I can find say to change the the cells listed in the rangers here, but that seems very counterintuitive to what I’m trying to do.

How to&Answers:

If you can name the ranges of each data set you can do something like this:

Sub SortRanges()
    Dim TargetSheet As Worksheet
    Dim RangeName As Variant
    Dim CurrentRange As Range
    Set TargetSheet = ThisWorkbook.Worksheets(1)
    For Each RangeName In Array("Range1", "Range2", "Range3")
        Set CurrentRange = TargetSheet.Range(RangeName)
        CurrentRange.Sort key1:=CurrentRange.Columns(2), key2:=CurrentRange.Columns(4)
End Sub

It will take the list of range names and sort them one by one on column 2 and 4. If you can’t name the ranges, make an array of ranges in your code instead.


You can sort the entire column.
I don’t know if you have to clear the sort fields, I just left it in there.

Sub CDER()
    Dim sh As Worksheet
    Set sh = Sheets("Sheet1")

    With sh
        .Range("B:B").Sort key1:=.Range("B:B"), order1:=xlAscending, Header:=xlYes
        .Range("G:G").Sort key1:=.Range("G:G"), order1:=xlAscending, Header:=xlYes
    End With

End Sub