QP School

Full Version: Sort data in a range with VBA
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.