Sorting alphabetically two columns, first one contains a set of repeat values and the second are unique values

Viewed 56

How can I sort to columns in the following way

My two columns before sorting

C    Ciks
C    Bsdjnf
C    ACfff
A    Bhdh
A    Apdp
A    Cyay
B    Ayay
B    Cnan
B    Btag

After being sorted

A    Apdp
A    Bhdh
A    Cyay
B    Ayay
B    Btag
B    Cnan
C    ACfff
C    Bsdjnf
C    Ciks

I have been using the common command found for example the one found here sort multiple columns excel VBA but when sorted the second column, this modify the first one.

(This is my first question in stackoverflow, I have read the advices to ask properly, hope this is ok, happy to modify my question is needed)

2 Answers

Sort Multiple Columns

Option Explicit

Sub SortMultipleColumns()

    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    Dim rg As Range: Set rg = ws.Range("A1").CurrentRegion

    With ws.Sort
        .SortFields.Clear
        .SortFields.Add Key:=rg.Columns(1), Order:=xlAscending
        .SortFields.Add Key:=rg.Columns(2), Order:=xlAscending
        .SetRange rg
        .Header = xlNo ' usually you have headers, then use 'xlYes'
        .Apply
    End With

End Sub

Is it excel? Can't you use excel Data -> Sort? enter image description here

It will sort by priority, upper line, upper priority, then next line... will not modify prior sorted line(s).

Related