QP School
Sort data in a range with VBA - Printable Version

+- QP School (https://qomplainerzschool.lima-city.de)
+-- Forum: Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=3)
+--- Forum: Excel VBA Tutorials (https://qomplainerzschool.lima-city.de/forumdisplay.php?fid=48)
+--- Thread: Sort data in a range with VBA (/showthread.php?tid=5254)



Sort data in a range with VBA - Qomplainerz - 07-27-2023

Example:

Sub SortData()
    Dim sortRange As Range

    'Set the range to be sorted (assuming data starts from A1)
    Set sortRange = Range("A1").CurrentRegion

    'Sort the range in ascending order based on values in column A
    sortRange.Sort Key1:=sortRange.Columns(1), Order1:=xlAscending, Header:=xlYes
End Sub

Explanation:

The code defines a subroutine named SortData.
It declares a variable sortRange, which represents the range to be sorted. In this example, the range is set to the data starting from cell A1 using the CurrentRegion property.
The sortRange.Sort method is used to sort the range in ascending order.
Key1:=sortRange.Columns(1) specifies that the sorting should be based on values in column A (the first column of sortRange).
Order1:=xlAscending sets the sorting order to ascending.
Header:=xlYes indicates that the range has a header row, and sorting should include the header.