Retrieve Sorting Information for Cell Range

From The Document Foundation Wiki
< Macros‎ | Calc
Jump to navigation Jump to search
Other languages:
English • ‎italiano


This page provides a LibreOffice Basic macro procedure that retrieves the sorting information for a given cell range. It is an example drawn from Chapter 13 ("Calc as a Database") of the 7.0 Calc Guide.


You can use the method createSortDescriptor() to retrieve the sorting information for a given cell range. If this method is called on a database range, it will create a sort descriptor using the sorting information stored with that range. On the other hand, if createSortDescriptor() is called on a standard named range or an unnamed range, it will generate a sort descriptor with default properties. In either case, the newly-generated sort descriptor can be modified and passed as an argument to a sort method called on a given range.

The macro procedure below demonstrates how to generate and display the sorting information associated with a range. The output of this macro is a dialog box displaying sort descriptor properties.


 1Sub DisplaySortDescriptor
 2  On Error Resume Next
 3  Dim oSheet
 4  Dim oRange       ' A range is needed to create the sort descriptor.
 5  Dim oSortDescript
 6  Dim i%
 7  Dim s$
 8  Dim oDoc         ' Reference newly created calc document.
10  oDoc = StarDesktop.loadComponentFromURL("private:factory/scalc", "_default", 0, Array())
11  oSheet = oDoc.Sheets(0)
12  oRange = oSheet.getCellRangeByName("B28:D33")
13  oSortDescript = oRange.createSortDescriptor()
14  For i = LBound(oSortDescript) To UBound(oSortDescript)
15    s = s & oSortDescript(i).Name & " = "
16    s = s & oSortDescript(i).Value
17    s = s & CHR$(10)
18  Next
19  MsgBox s, 0, "Sort Descriptor"
20End Sub

This Calc spreadsheet contains the above LibreOffice Basic code.