Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading