excelvbasorting

Sort rows based on multiple criteria


I need to sort rows based on order number and whether or not the last 4 columns contain "Y".
If H-K all contain Y, then they need to be brought to the top and sorted by order number.
Then, if only H-J contain Y, they should be below and also sorted by order number and so on.
Rows that do not contain Y in any of the cells H-K should be at the bottom and still sorted by order number.

To my knowledge, the spreadsheet did this sorting for years, but now it does not.

Example data: enter image description here


Solution

  • Option Explicit
    
    Sub mysort()
    
        Dim ws As Worksheet, rng As Range, lastrow As Long
        
        Set ws = ThisWorkbook.Sheets("Sheet1")
        With ws
            lastrow = .Cells(.Rows.Count, "B").End(xlUp).Row
           
            ' add helper column L
            Set rng = .Range("L2:L" & lastrow)
            rng.FormulaR1C1 = "=COUNTIF(RC[-4]:RC[-1],""Y"")"
           
            ' sort
            .Sort.SortFields.Clear
            .Sort.SortFields.Add2 Key:=rng _
            , SortOn:=xlSortOnValues, Order:=xlDescending, DataOption:=xlSortNormal
            .Sort.SortFields.Add2 Key:=Range("B2:B" & lastrow) _
            , SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
            With .Sort
                .SetRange ws.Range("A1:L" & lastrow)
                .Header = xlYes
                .MatchCase = False
                .Orientation = xlTopToBottom
                .SortMethod = xlPinYin
                .Apply
            End With
        End With
          
        ' clear helper
        rng.Clear
    
    End Sub