0

In Microsoft Excel, sorting a column or multiple columns in ascending order (A-Z) sends empty cells to the bottom of each list in the column. Moreover, it provides no options for dealing with empty cells in its sorting functions.

How can one send them to the top when sorting a selection of columns? Would like to achieve a result similar to this; enter image description here

4
  • 3
    You can put a letter ‘A’ in blank cells, then sort multiple columns. After the sorting, replace’A’ with empty string. Commented Oct 13, 2024 at 9:14
  • 3
    ...Or do the same thing with Sortby Commented Oct 13, 2024 at 9:22
  • @TomSharpe - totally forgot about SORTBY in E365 Commented Oct 13, 2024 at 9:29
  • Related Q&A - stackoverflow.com/questions/77902838/… Commented Oct 13, 2024 at 9:47

3 Answers 3

2

Edit, if you have Excel 365 you can use SORTBY function.

You could do it manually using search and replace, replacing blanks with say 1s, which sort ahead of text and replacing 1s with blanks. You could do it in VBA as well.

    Sub SortTableWithBlanksOnTop()
        Dim ws As Worksheet
        Dim rng As Range
        Dim lastRow As Long
        
        Set ws = ThisWorkbook.Sheets("Sheet1")
       
        lastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
    
        Set rng = ws.Range("A1:C" & lastRow)
        
        rng.Replace What:="", Replacement:="1", _
            SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
            ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
    
        With ws.Sort
            .SortFields.Clear
            .SortFields.Add Key:=ws.Range("A1:A" & lastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
            .SortFields.Add Key:=ws.Range("B1:B" & lastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
            .SortFields.Add Key:=ws.Range("C1:C" & lastRow), SortOn:=xlSortOnValues, Order:=xlAscending, DataOption:=xlSortNormal
            .SetRange rng
            .Header = xlYes ' Assuming you have headers
            .MatchCase = False
            .Orientation = xlTopToBottom
            .SortMethod = xlPinYin
            .Apply
        End With
    
    
        rng.Replace What:="1", Replacement:="", _
            SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
            ReplaceFormat:=False, FormulaVersion:=xlReplaceFormula2
End Sub
Sign up to request clarification or add additional context in comments.

1 Comment

It's convenient to point the whole column as the sorting key, e. g. "A:A". The simplified syntax is also allowed: ws.[A:A].
2

Thank you so much everyone for taking the time to add your comments and answers. They helped point me in the right direction. Indeed @Michal's answer works for a fixed number of columns and many may find it useful. What was needed was specifically a VBA code for a selection of columns, whenever a user arbitrarily selects any range of cells spanning any number of columns and have them sorted correctly.

After some research, this crafted solution works and works for anyone.

Sub SortBlanksOnTop()
    On Error Resume Next
    
    ' Set up your variables and turn off screen updating.
      Dim w As Worksheet
      Dim r As Range ' Working range
      Dim v As Double ' Value for blank cells
      Application.ScreenUpdating = False
    
    ' Set title for the range selection user dialog box.
      t = "Selection Range"
    
    ' Get the sheet.
      Set w = ActiveSheet
    
    ' Request and store range from user.
      Set r = Application.InputBox("Range", t, Application.Selection.Address, Type:=8)
    
    ' Create a new least value by subtracting from the least value in the selection.
    ' Doubles are being used because Ms Excel sorting ranks them before alphabets in ascending order.
      v = Application.WorksheetFunction.Small(r, 1) - 1
    
    'Substitute all blank cells in the selection range with this new value.
      r.SpecialCells(xlCellTypeBlanks) = v
    
    ' Clear any existing sort fields.
      w.Sort.SortFields.Clear

    ' Add sort field for each column in the selection range.
      For Each Column In r.Columns
         w.Sort.SortFields.Add Key:=Column, Order:=xlAscending
      Next Column

    ' Apply the sort
      With w.Sort
        .SetRange r
        .Header = xlNo
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
      End With
            
    ' Revert to blank cells.
      r.Replace What:=v, Replacement:="", LookAt:=xlWhole
      
    ' Turn screen updating back on.
      Application.ScreenUpdating = True
End Sub

Feel free to add conditions in the For Each loop to exclude any kinds of cells, columns or rows.

Hope to save someone's time.

Comments

0

Non-formula solution (not my original idea):

  • Add conditional formatting to blank cells
  • In sort order, the specify these to be "On Top"
  • Remove the formatting

Result with conditional formatting


Or with SORTBY, assuming all input is text (or blanks), by adding an empty string first -

Enter in a cell with enough empty cells to hold the sorted table:

=LET(tbl, A2:C12 & "", 
SORTBY(tbl, INDEX(tbl, , 1), , INDEX(tbl, , 2), , INDEX(tbl, , 3), ))

Result of SORTY with empty string added

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.