Sort a Table Using One Column
TDF LibreOffice Document Liberation Project Community Blogs Weblate Nextcloud Redmine Ask LibreOffice Donate
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 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.