# Macros/Calc/ba023/es

< Macros‎ | Calc
This page is a translated version of the page Macros/Calc/ba023 and the translation is 8% complete.
Other languages:
English • ‎español • ‎italiano

## Summary

This page provides a LibreOffice Basic macro procedure that sorts a table based on the values in one column. It is an example drawn from Chapter 13 ("Calc as a Database") of the 7.0 Calc Guide.

## Description

In a Calc macro, data within a range is sorted by calling the sort() method on the range object. When a sort operation is called on a range, an array of properties known as a sort descriptor is passed to the sort method. Contained within a descriptor’s properties are sort fields, which are structures that inform Calc how to sort a range according to the data contained within one of its rows or columns.

As an example, the macro below sorts a class grade sheet in cells \$Sheet1.A1:H11 according to average grade in descending order. The linked spreadsheet contains such a grade sheet.

## Code

``````Sub SortAverageGrade
Dim oSheet
Dim oRange
Dim oSortFields(0) as new com.sun.star.util.SortField
Dim oSortDesc(0) as new com.sun.star.beans.PropertyValue

oSheet = ThisComponent.Sheets(0)
REM Set the range on which to sort
oRange = oSheet.getCellRangeByName("A1:H11")

REM Sort by the Average grade field in the range in descending order
oSortFields(0).Field = 7
oSortFields(0).SortAscending = FALSE

REM Set the sort fields to use
oSortDesc(0).Name = "SortFields"
oSortDesc(0).Value = oSortFields()

REM Now sort the range!
oRange.Sort(oSortDesc())
End Sub``````

This Calc spreadsheet contains the above LibreOffice Basic code.