LibreOffice Calc Guide 17
LibreOffice Calc Guide 17
Although this document was initially created for macro programmers, the content
should be accessible to all users. If you do not use macros, then skip those portions
Note that deal with macros. On the other hand, if you want to learn more about macros, be
sure to check out Andrew Pitonyaks book OpenOffice.org Macros Explained.
In a database, a record is a group of related data items treated as a single unit of information. Each
item in the record is called a field. A table consists of records. Each record in a table has the same
structure. A table can be visualized as a series of rows and columns. Each row in the table
corresponds to a single record and each column corresponds to the fields. A spreadsheet in a Calc
document is similar in structure to a database table. Each cell corresponds to a single field in a
database record. For many people, Calc implements sufficient database functionality that no other
database program or functionality is required.
While teaching, a spreadsheet might be used as a grading program. Each row represents a single
student. The columns represent the grades received on homework, labs, and tests (see Table 9).
The strong calculation capability provided in a spreadsheet makes this an excellent choice.
Although the choice to associate a row with a record rather than a column is arbitrary,
Tip it is almost universal. In other words, you are not likely to hear someone refer to a
column of data as a single database record.
Named range
The most common usage of a named range is, as its name implies, to associate a range of cells
with a meaningful name. For example, create a range named Scores, and then use the following
equation: =SUM(Scores). To create a named range, select the range to define. Use Insert >
Names > Define to open the Define Names dialog. Use the Define Names dialog to add and
modify one named range at a time.
In a macro, a named range is accessed, created, and deleted using the NamedRanges property of
a Calc document. Use the methods hasByName(name) and getByName(name) to verify and
retrieve a named range. The method getElementNames() returns an array containing the names of
all named ranges. The NamedRanges object supports the method addNewByname, which accepts
four arguments; the name, content, position, and type. The macro in Listing 10 creates a named
range, if it does not exist, that references a range of cells.
sName$ = "MyNRange"
oRanges = ThisComponent.NamedRanges
If NOT oRanges.hasByName(sName$) Then
REM Obtain the cell address by obtaining the cell
REM and then extracting the address from the cell.
Dim oCellAddress As new com.sun.star.table.CellAddress
oCellAddress.Sheet = 0 'The first sheet.
oCellAddress.Column = 1 'Column B.
oCellAddress.Row = 2 'Row 3.
The method addNewByname() accepts four arguments; the name, content, position, and type. The
fourth argument to the method addNewByName() is a combination of flags that specify how the
named range will be used (see Table 10). The most common value is 0, which is not a defined
constant value.
The third argument, a cell address, acts as the base address for cells referenced in a relative way.
If the cell range is not specified as an absolute address, the referenced range will be different
based on where in the spreadsheet the range is used. The relative behavior is illustrated in Listing
11, which also illustrates another usage of a named rangedefining an equation. The macro in
Listing 11 creates the named range AddLeft, which refers to the equation A3+B3 with C3 as the
reference cell. The cells A3 and B3 are the two cells directly to the left of C3, so, the equation
=AddLeft() calculates the sum of the two cells directly to the left of the cell that contains the
equation. Changing the reference cell to C4, which is below A3 and B3, causes the AddLeft
equation to calculate the sum of the two cells that are to the left on the previous row.
Listing 11. Create the AddLeft named range.
Sub AddNamedFunction()
Dim oSheet 'Sheet that contains the named range.
Dim oCellAddress 'Address for relative references.
Dim oRanges 'The NamedRanges property.
Dim oRange 'Single cell range.
Dim sName As String 'Name of the equation to create.
sName = "AddLeft"
oRanges = ThisComponent.NamedRanges
If NOT oRanges.hasByName(sName) Then
oSheet = ThisComponent.getSheets().getByIndex(0)
oRange = oSheet.getCellRangeByName("C3")
oCellAddress = oRange.getCellAddress()
oRanges.addNewByName(sName, "A3+B3", oCellAddress, 0)
End If
End Sub
Listing 11 illustrates two capabilities that are not widely known. A named range can
Tip define a function. Also, the third argument acts as the base address for cells
referenced in a relative way.
Select the range containing the headers and the data and then use Insert > Names > Create to
open the Create Names dialog (see Figure 303), which allows you to simultaneously create
multiple named ranges based on the top row, bottom row, right column or left column. If you
choose to create ranges based on the top row, one named range is created for each column
headerthe header is not included in the named range. Although the header is not included in the
range, the text in the header is used to name the range.
The macro in Listing 12 creates three named ranges based on the top row of a named range.
Listing 12. Create many named ranges.
Sub AddManyNamedRanges()
Dim oSheet 'Sheet that contains the named range.
Dim oAddress 'Range address.
Dim oRanges 'The NamedRanges property.
Dim oRange 'Single cell range.
oRanges = ThisComponent.NamedRanges
oSheet = ThisComponent.getSheets().getByIndex(0)
oRange = oSheet.getCellRangeByName("A1:C20")
oAddress = oRange.getRangeAddress()
oRanges.addNewFromTitles(oAddress, _
com.sun.star.sheet.Border.TOP)
End Sub
The constants in Table 11 determine the location of the headers when multiple ranges are created
using the method addNewFromTitles().
Caution It is possible to create multiple named ranges with the same name. Creating
multiple ranges with a single command increases the likelihood that multiple
ranges will be created with the same nameavoid this if possible.
Database range
Although a database range can be used as a regular named range, a database range also defines
a range of cells in a spreadsheet to be used as a database. Each row in a range corresponds to a
record and each cell corresponds to a field. You can sort, group, search, and perform calculations
on the range as if it were a database.
In a macro, a database range is accessed, created, and deleted from the DatabaseRanges
property. The macro in Listing 13 creates a database range named MyName and sets the range to
be used as an auto filter.
Listing 13. Create a database range and an auto filter.
Sub AddNewDatabaseRange()
Dim oRange 'DatabaseRange object.
Dim oAddr 'Cell address range for the database range.
Dim oSheet 'First sheet, which will contain the range.
Dim oDoc 'Reference ThisComponent with a shorter name.
oDoc = ThisComponent
If NOT oDoc.DatabaseRanges.hasByName("MyName") Then
oSheet = ThisComponent.getSheets().getByIndex(0)
oRange = oSheet.getCellRangeByName("A1:F10")
oAddr = oRange.getRangeAddress()
oDoc.DatabaseRanges.addNewByName("MyName", oAddr)
Sorting
The sorting mechanism in a Calc document rearranges the data in the sheet. The first step in
sorting data is to select the data that you want to sort. To sort the data in Table 9, select the cells
from A1 to G16if you include the column headers, indicate this in the sort dialog (see Figure
306). Use Data > Sort to open the Sort dialog (see Figure 305). You can sort by up to three
columns or rows at a time.
Click on the Options tab (see Figure 306) to set the sort options. Check the Range contains
column labels checkbox to prevent column headers from being sorted with the rest of the data.
The Sort by list box in Figure 305 displays the columns using the column headers if the Range
contains column labels checkbox in Figure 306 is checked. If the Range contains column
labels checkbox is not checked, however, then the columns are identified by their column name;
Column A, for example.
Normally, sorting the data causes the existing data to be replaced by the newly sorted data. The
Copy sort results to checkbox, however, causes the selected data to be left unchanged and a
copy of the sorted data is copied to the specified location. You can either directly enter a target
address (Sheet3.A1, for example) or select a predefined range.
Check the Custom sort order checkbox to sort based on a predefined list of values. To set your
own predefined lists, use Tools > Options > LibreOffice Calc > Sort Lists and then enter your
own sort lists. Predefined sort lists are useful for sorting lists of data that should not be sorted
alphabetically or numerically. For example, sorting days based on their name.
Filters
Use filters to limit the visible rows in a spreadsheet. Generic filters, common to all sorts of data
manipulations, are automatically provided by the auto filter capability. You can also define your own
filters.
After applying a filter, some rows are visible and some rows are not. If you select
Caution multiple rows in one operation, you will also select the invisible rows contained
between the selected visible rows. Operations, such as delete, act on all of the
selected rows. To avoid this problem, you must individually select each of the
filtered rows using the control key.
Standard filters
Use Data > Filter > Standard Filter to open Standard Filter dialog (see Figure 308) and limit the
view based on 1 to 3 filter conditions. Use Data > Filter > Remove Filter to turn off the filter.
oSheet = ThisComponent.getSheets().getByIndex(0)
With oFields(0)
REM You could use the Connection property to indicate
REM how to connect to the previous field. This is
REM the first field, so this is not required.
'.Connection = com.sun.star.sheet.FilterConnection.AND
'.Connection = com.sun.star.sheet.FilterConnection.OR
When a filter is applied to a sheet, it replaces any existing filter for the sheet. Setting an empty filter
in a sheet will therefore remove all filters for that sheet (see Listing 15).
Listing 15. Remove the current sheet filter.
Sub RemoveSheetFilter()
Dim oSheet ' Sheet to filter.
Dim oFilterDesc ' Filter descriptor.
oSheet = ThisComponent.getSheets().getByIndex(0)
oFilterDesc = oSheet.createFilterDescriptor(True)
oSheet.filter(oFilterDesc)
End Sub
Listing 16 demonstrates a more advanced filter that filters two columns and uses regular
expressions. Some unexpected behavior occurred while working with Listing 16. Although you can
create a filter descriptor using any sheet cell range, the filter applies to the entire sheet.
Listing 16. A simple sheet filter using two columns.
Sub SimpleSheetFilter_2()
Dim oSheet ' Sheet to filter.
Dim oRange ' Range to be filtered.
Dim oFilterDesc ' Filter descriptor.
Dim oFields(1) As New com.sun.star.sheet.TableFilterField
oSheet = ThisComponent.getSheets().getByIndex(0)
oRange = oSheet.getCellRangeByName("E12:G19")
oFilterDesc.setFilterFields(oFields())
oFilterDesc.ContainsHeader = False
oFilterDesc.UseRegularExpressions = True
oSheet.filter(oFilterDesc)
End Sub
Advanced filters
An advanced filter supports up to eight filter conditions, as opposed to the three supported by the
simple filter. The criteria for an advanced filter is stored in a sheet. The first step in creating an
advanced filter is entering the filter criteria into the spreadsheet.
1) Select an empty space in the Calc document. The empty space may reside in any sheet in
any location in the Calc document.
2) Duplicate the column headings from the area to be filtered into the area that will contain the
filter criteria.
3) Enter the filter criteria underneath the column headings (see Table 12). The criterion in
each column of a row is connected with AND. The criteria from each row are connected
with OR.
Define named ranges to reference your advanced filter criteria and any destination
Tip ranges for filtered data (see Figure 302). Each appropriately configured named range
is available in drop down list boxes in the Advanced Filter dialog (see Figure 309).
Figure 309. Apply an advanced filter using a previously defined named range
oFiltDesc = oCritRange.createFilterDescriptorByObject(oDataRange)
oDataRange.filter(oFiltDesc)
End Sub
Change properties on the filter descriptor to change the behavior of the filter (see Table 13).
(Advanced material.) The OutputPosition property returns a copy of a struct. Because a copy is
returned, it is not possible to set the individual values directly. For example,
oFiltDesc.OutputPosition.Row = 2 does not work (because you set the Row on the copy to 2, but
do not change the original).
Most of the functions in Table 14 require no explanation, either because they are well understood
(SUM, for example) or because if you need to use them then you know what they are (STDEV, for
example). Unfortunately, some of the more useful functions are infrequently used because they are
not well understood.
Count and sum cells that match conditions: COUNTIF and SUMIF
The COUNTIF and SUMIF functions calculate their values based on search criteria. The search
criteria can be a number, expression, text string, or even a regular expression. The search criteria
can be contained in a referenced cell or it can be included directly in the function call.
The COUNTIF function counts the number of cells in a range that match specified criteria. The first
argument to COUNTIF specifies the range to search and second argument is the search criteria.
Table 15 illustrates different search criteria using the COUNTIF function referencing the data
shown in Table 9.
The first two arguments for SUMIF serve the same purpose as the arguments for COUNTIF; the
range that contains the cells to search and the search criteria. The third and final argument for
SUMIF specifies the range to sum. For each cell in the search range that matches the search
criteria, the corresponding cell in the sum range is added into the sum.
Table 15: Examples of search criteria for the COUNTIF and SUMIF functions.
Criteria Type Function Result Description
Number =COUNTIF(B1:C16; 95) 3 Finds numeric values of 95.
Text =COUNTIF(B1:C16; "95") 3 Finds numeric or text values
of 95.
Expression =COUNTIF(B1:C16; ">95") 6 Finds numeric values
greater than 95.
Expression =COUNTIF(B1:C16; 2*45+5) 3 Finds only numeric values
of 95.
Do not forget that the SUBTOTAL function ignores cells that use the SUBTOTAL
function. Say you have a spreadsheet that tracks investments. The retirement
Tip investments are grouped together with a subtotal. The same is true of regular
investments. You can use a single subtotal that includes the entire range without
worrying about the subtotal cells.
Examples
Consider the data in Table 9. Each students information is stored in a single row. Write a formula
to return the average grade for Fred. The problem can be restated as Search column A in the
range A1:G16 for Fred and return the value in column F (column F is the sixth column). The
obvious solution is =VLOOKUP("Fred"; A2:G16; 6). Equally obvious is
=LOOKUP("Fred"; A2:A16; F2:F16).
It is common for the first row in a range to contain column headers. All of the search functions
check the first row to see if there is a match and then ignore it if it does not contain a match, in
case the first row is a header.
What if the column heading Average is known, but not the column containing the average? Find
the column containing Average rather than hard coding the value 6. A slight modification using
MATCH to find the column yields
=VLOOKUP("Fred"; A2:G16; MATCH("Average"; A1:G1; 0)); notice that the heading is
not sorted. As an exercise, use HLOOKUP to find Average and then MATCH to find the row
containing Fred.
As a final example, write a formula to assign grades based on a students average score. Assume
that a score less than 51 is an F, less than 61 is an E, less than 71 is a D, less than 81 is a C, less
than 91 is a B, and 91 to 100 is an A. Assume that the values in Table 17 are in Sheet2.