Finance

Charts

Statistics

Macros

Search

Sorting List Data by Three Fields with Excel VBA

Let’s consider an example that demonstrates the use of the Sort method. Suppose a worksheet contains a list of data about cars and their owners. Place two CommandButton controls on the worksheet: one will perform ascending sorting by three arbitrary columns, and the other will perform descending sorting.

Change the Caption property values accordingly: for the first button (CommandButton1) set SORT ASCENDING, and for the second button (CommandButton2) set SORT DESCENDING.

Sorting by three fields in ascending and descending order. Standard module

Sub Sort_Up()
    Range("A1").Select
    x = InputBox("Enter the column address for sorting by the first field", _
                 "Enter range")
    y = InputBox("Enter the column address for sorting by the second field", _
                 "Enter range")
    z = InputBox("Enter the column address for sorting by the third field", _
                 "Enter range")
    Selection.Sort Key1:=Range(x), Order1:=xlAscending, _
                   Key2:=Range(y), Order2:=xlAscending, _
                   Key3:=Range(z), Order3:=xlAscending, Header:=xlYes
    Range("A1").Select
End Sub

Sub Sort_Down()
    Range("A1").Select
    x = InputBox("Enter the column address for sorting by the first field", _
                 "Enter range")
    y = InputBox("Enter the column address for sorting by the second field", _
                 "Enter range")
    z = InputBox("Enter the column address for sorting by the third field", _
                 "Enter range")
    Selection.Sort Key1:=Range(x), Order1:=xlDescending, _
                   Key2:=Range(y), Order2:=xlDescending, _
                   Key3:=Range(z), Order3:=xlDescending, Header:=xlYes
    Range("A1").Select
End Sub

Sorting by three fields in ascending and descending order. Sheet1 module

Private Sub CommandButton1_Click()
    Sort_Up
End Sub

Private Sub CommandButton2_Click()
    Sort_Down
End Sub
0 0 votes
Évaluation de l'article
S’abonner
Notification pour
guest
0 Commentaires
Le plus ancien
Le plus récent Le plus populaire
Online comments
Show all comments
Facebook
Twitter
LinkedIn
WhatsApp
Email
Print
0
We’d love to hear your thoughts — please leave a commentx