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:


This page provides a LibreOffice Basic macro procedure that creates a new database range referencing $Sheet1.$A$1:$F$10. It is an example drawn from Chapter 13 ("Calc as a Database") of the 7.0 Calc Guide.


In a macro, a database range is created, accessed, and deleted using the DatabaseRanges service. This service has many of the same methods as the NamedRanges service, but lacks the addNewFromTitles method. DatabaseRanges also uses a reduced version of the addNewByName method that lacks arguments for a relative base address and range type:

addNewByName(Name, Range)
Adds a new database range to the current document.

As an example of creating a range using this method, the macro below creates a database range named MyName and automatically applies auto filters to each of the range’s columns:


 1Sub AddNewDatabaseRange()
 2  Dim oRange 'DatabaseRange object.
 3  Dim oAddr  'Cell address range for the database range.
 4  Dim oSheet 'First sheet, which will contain the range.
 5  Dim oDoc   'Reference ThisComponent with a shorter name.
 7  oDoc = ThisComponent
 8  If NOT oDoc.DatabaseRanges.hasByName("MyName") Then
 9    oSheet = ThisComponent.getSheets().getByIndex(0)
10    oRange = oSheet.getCellRangeByName("A1:F10")
11    oAddr = oRange.getRangeAddress()
12    oDoc.DatabaseRanges.addNewByName("MyName", oAddr)
13  End If
14  oRange = oDoc.DatabaseRanges.getByName("MyName")
15  oRange.AutoFilter = True
16End Sub

This Calc spreadsheet contains the above LibreOffice Basic code.