Search code examples
vbaexcelsortingsubtotal

sort and subtotal preselected data


I'm working with a worksheet and at some point within there is a list of costs. However this list changes so can have varying numbers of rows. My ultimate goal is to sort and then subtotal this list of costs. Because the number of rows I want to sort and subtotal are always different, I was thinking I could make a macro that would only work off of preselected data eg the user to select the cells range to apply to be sorted and subtotalled. I can't just work off of all active cells, as there are some rows I don't want to include in the sort and subtotal.

I've recorded the following simple macro to sort and subtotal data, however, you'll note it only works for the cells that were selected when I recorded the macro. Does anybody know how to modify the macro so that the user can firstly manually select the cells range with the mouse and then click a button that automatically sorts the preselected data and subtotals it? any help very appreciated, thank you.

Sub Sort_and_Subtotal_CheckBox()

    ActiveWorkbook.Worksheets("dummy").AutoFilter.Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("dummy").AutoFilter.Sort.SortFields.Add Key:=Range( _
        "B151:B159"), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:= _
        xlSortNormal
    With ActiveWorkbook.Worksheets("dummy").AutoFilter.Sort
        .Header = xlYes
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With
    Range("B151:K156").Select
    Selection.Subtotal GroupBy:=1, Function:=xlSum, TotalList:=Array(10), _
        Replace:=True, PageBreaks:=False, SummaryBelowData:=True
End Sub

Solution

  • Try this code. This will allow the user to select the range by using an Input box.

    Dim SortRng As Range
    
    Set SortRng = Application.InputBox("Select the range to sort", "Select Range", 0, , , , , 8)
    
    SortRng.Select
    Selection.Sort Key1:=SortRng, Order1:=xlAscending, Header:=xlGuess, _
    OrderCustom:=1, MatchCase:=False, Orientation:=xlTopToBottom, _
    DataOption1:=xlSortNormal
    Range("A1").Select