0

Scenario: I have a sheet and am trying to sort a part of it. Inside the sheet I have a dropdown list, which allows me to select the values (aaa, bbb, ccc). Each of those values represent a column and when selected, the code should sort the range by that column.

Problem: The process works for one of the values in the dropdown list, but not for the others (it runs, but nothing happens).

Code:

Sub ratecolumnssort()

    Dim LastRow As Integer
    Dim sortColumn As String, sortAgent As String

    shtMonitoring.Activate
    LastRow = shtMonitoring.Cells(shtMonitoring.rows.count, "B").End(xlUp).row

    sortAgent = shtMonitoring.Cells(8, 9) ' this is where the dropdown with values aaa, bbb and ccc is

    If sortAgent = "aaa" Then
        sortColumn = "F"
    ElseIf sortAgent = "bbb" Then
        sortColumn = "H"
    ElseIf sortAgent = "ccc" Then
        sortColumn = "J"
    End If

    With ActiveSheet.sort
        .SortFields.Add key:=Range(sortColumn & "11"), Order:=xlAscending
        .SetRange Range("B11", "N" & LastRow )
        .Header = xlYes
        .Apply
    End With

End Sub

Question: What am I doing wrong here?

1
  • 3
    Not tested, but I think that every sorting needs a previous clearing. Try something lke ActiveSheet..AutoFilter.Sort.SortFields.Clear before each sorting? Commented Nov 8, 2019 at 11:36

1 Answer 1

2

You need to clear the sort settings first.

 With ActiveSheet.Sort
        .SortFields.Clear 'add this line
        'as before
Sign up to request clarification or add additional context in comments.

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.