Unable to Apply Sort using VBA

b bb 6 Reputation points
2022-03-03T16:19:21.827+00:00

Thank you for taking the time to read my question.

I have a sheet that I have some merged cells on, but I need to sort it. So I'm unmerging all cells, then trying to sort. When I get to the .Apply, my code fails with the error:

1004, Application-defined or object-defined error

I do not know what I'm doing wrong as I recorded a macro of me sorting my page and that worked. Then I edited the range to be more dynamic as I only want to sort specific rows based on Column A and now it's not working.

Any help is greatly appreciated

Thanks!

Code:
Public Sub CommandButton6_Click() 'Sort
Dim x As Long
SetConst
SkipChange = True
On Error GoTo CommandButton6_Err
Application.ScreenUpdating = False

    ActiveSheet.Unprotect
    'Need to Unmerge otherwise can't sort
    ActiveSheet.Cells.UnMerge

    ActiveWorkbook.Worksheets("Project").Sort.SortFields.Clear
    ActiveWorkbook.Worksheets("Project").Sort.SortFields.Add _
        Key:=Range("A6:AAC" & Cells(6, WBSCol).End(xlDown).Row), _
        SortOn:=xlSortOnValues, _
        Order:=xlAscending, _
        DataOption:=xlSortTextAsNumbers
    With ActiveWorkbook.Worksheets("Project").Sort
        .SetRange Range("A6:AAC" & Cells(6, WBSCol).End(xlDown).Row)
        .Header = xlGuess
        .MatchCase = False
        .Orientation = xlTopToBottom
        .SortMethod = xlPinYin
        .Apply
    End With

    CommandButton6_Exit:
    Exit Sub

    CommandButton6_Err:
    MsgBox Err.Number & ", " & Err.Description
    Resume CommandButton6_Exit
End Sub
Developer technologies | Visual Basic for Applications
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. b bb 6 Reputation points
    2022-03-03T17:41:31.877+00:00

    I sorted it out.

    The key:= should only be the column the sort is happening on, I was providing the entire range I wanted to sort.

    Key:=Range(Cells(6, 1), Cells(Cells(6, WBSCol).End(xlDown).Row, 1))
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.