Macros/Calc/ba023/es
TDF LibreOffice en español Document Liberation Project Blogs comunitarios Weblate Nextcloud Redmine Preguntas y respuestas Donar
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. Attention: The Field index value of the SortField variable starts relatively from the selected range. For instance, if the selected range spans over C1:H11, the column C has the field index 0.
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 <span lang="en" dir="ltr" class="mw-content-ltr">Set the range on which to sort</span>
oRange = oSheet.getCellRangeByName("A1:H11")
REM <span lang="en" dir="ltr" class="mw-content-ltr">Sort by the Average grade field in the range in descending order</span>
oSortFields(0).Field = 7
oSortFields(0).SortAscending = FALSE
REM <span lang="en" dir="ltr" class="mw-content-ltr">Set the sort fields to use</span>
oSortDesc(0).Name = "SortFields"
oSortDesc(0).Value = oSortFields()
REM <span lang="en" dir="ltr" class="mw-content-ltr">Now sort the range!</span>
oRange.Sort(oSortDesc())
End Sub
This Calc spreadsheet contains the above LibreOffice Basic code.