Search code examples
excelsorting

Having issues with an Excel 2019 sort pulling in the row above the selected area to sort, can anyone help me fix this


I am trying to help out my golf league to automate their weekly schedule spreadsheet manipulation by writing some VBA code. The process involves recording macros to mimic their process. When trying to sort on a partial column selection, the sort pulls in the row above the selection (a header row in row 6) into the sort. I've tried everything and read many articles on this, makes no sense to me and I can't seem to fix it. Can someone out there help me? See the screenshots below for what's happening and what I've tried to fix it.

screenshots of issue


Solution

  • Sort Data

    Sub SortHandles()
    
        ' Define constants.
        Const SHEET_NAME As String = "Sheet1"
        Const HEADER_CELL_ADDRESS As String = "A6" ' row 5 is empty
        Const SORT_COLUMN As Long = 3  
         
        ' Reference the objects.
        Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
        Dim ws As Worksheet: Set ws = wb.Sheets(SHEET_NAME)
        Dim rg As Range:
        With ws.Range(HEADER_CELL_ADDRESS).CurrentRegion
            Set rg = .Resize(.Rows.Count - 1).Offset(1) ' exclude top row
        End With
        
        ' Sort.
        rg.Sort rg.Columns(SORT_COLUMN), xlAscending, , , , , , xlNo
    
    End Sub