Macros/Calc/ba029

From The Document Foundation Wiki
< Macros‎ | Calc
Jump to navigation Jump to search

Template:TopMenu/en Template:Menu/en Template:Menu.Macros/en

Other languages:

Summary

This page provides a LibreOffice Basic macro procedure that creates an advanced filter. It is an example drawn from Chapter 13 ("Calc as a Database") of the 7.0 Calc Guide.

Description

Applying an advanced filter with a macro works similarly to setting up a standard filter. The key difference is that the cell range containing the filter criteria is used to create the filter descriptor. The macro procedure below demonstrates how this is done using the createFilterDescriptorByObject method. It uses a class grade sheet in cells $Sheet1.A1:H11 as the data range and cells $Sheet2.A1:H3 as the criteria range. The linked spreadsheet contains such a data range and criteria range.

Code

 1Sub AdvancedRangeFilter()
 2  Dim oSheet     'A sheet from the Calc document.
 3  Dim oRanges    'The NamedRanges property.
 4  Dim oCritRange 'Range that contains the filter criteria.
 5  Dim oDataRange 'Range that contains the data to filter.
 6  Dim oFiltDesc  'Filter descriptor.
 7
 8  REM Range that contains the filter criteria
 9  oSheet = ThisComponent.getSheets().getByIndex(1)
10  oCritRange = oSheet.getCellRangeByName("A1:H3")
11
12  REM You can also obtain the range containing the 
13  REM filter criteria from a named range.
14  REM oRanges = ThisComponent.NamedRanges
15  REM oRange = oRanges.getByName("AverageLess80")
16  REM oCritRange = oRange.getReferredCells()
17
18  REM The data that you want to filter
19  oSheet = ThisComponent.getSheets().getByIndex(0)
20  oDataRange = oSheet.getCellRangeByName("A1:H11")
21
22  oFiltDesc = oCritRange.createFilterDescriptorByObject(oDataRange)
23  oDataRange.filter(oFiltDesc)
24End Sub

This Calc spreadsheet contains the above LibreOffice Basic code.