Using Macros in Spreadsheet
Using Macros in Spreadsheet
A macro is a set of commands or keystrokes that are stored for later use. An example of
a simple macro is one that enters your address into an open document. You can use
macros to automate both simple and complex tasks. Macros are very useful when you
have to repeat the same task in the same way.
The simplest way to create a macro is to record a series of actions through LibreOffice’s
user interface. LibreOffice saves recorded macros using the open source LibreOffice
Basic scripting language, which is an implementation of the well-known BASIC
programming language. Such macros can be edited and enhanced after recording using
the built-in LibreOffice Basic Integrated Development Environment (IDE).
The most powerful macros in LibreOffice are created by writing code using one of the
four supported scripting languages (LibreOffice Basic, BeanShell, JavaScript, and
Python). This chapter provides an overview of LibreOffice’s macro facilities, mostly
focused on its default macro scripting language, LibreOffice Basic. Some introductory
examples are included for the BeanShell, JavaScript, and Python scripting languages.
However, an in-depth discussion of how to use these languages for scripting is beyond
the scope of this chapter.
The first step in learning macro programming is to find and use existing macros. This
section assumes that you have a macro that you want to use, which you may have
found in a book or on the internet. For this example, the macro in Listing 1 is used. You
should create a library and module to contain your macro; see “Macro
organization” below for more information.
7. On the Basic Macro Organizer dialog, select the Modules tab (Figure 3).
8. In the Module list, expand My Macros and select your library (in the
example, TestLibrary). A module named Module1 already exists and can contain your
macro. If you wish, you can click New to create another module in the library.
9. Select Module1, or the new module that you created, and click Edit to open the
Integrated Development Environment (IDE) (Figure 4). The IDE is a text editor and
associated facilities that are built into LibreOffice and allow you to create, edit, run,
and debug macros.
Figure 1: Basic Macros dialog
1. Click the Compile icon on the Macro toolbar to compile the macro.
2. Select the HelloMacro subroutine in the Object Catalog window and click the Run icon
on the Macro toolbar, or press the F5 key, to run the HelloMacro subroutine in the
module. A small dialog will open with the word “Hello” displayed (see below).
1. To select and run any macro in the module, click the Select Macro icon on the
Standard toolbar or go to Tools > Macros > Organize Macros > Basic.
2. Select a macro and then click Run.
Recording a macro
When you record a macro in LibreOffice, you are actually recording the steps to perform
a certain task using programming language. For example, consider that you have to
repeatedly enter the same information into a document. You can copy this information
after it has been entered into the document for the first time, then paste the
information into the document each time you want to use it. However, if something else
is copied to the clipboard, the contents of the clipboard are changed. This means that
you have to re-copy this piece of information again to later paste it into the document.
To overcome this problem, you can create a macro that enters this piece of information
without having to copy it every time you need it.
Note
For some cases when you want to repeatedly enter information into a
document, it may be more convenient to create an AutoText. See Chapter 2,
Working with Text: Basics, in the Writer Guide for more information.
Make sure macro recording is enabled by going to Tools > Options > LibreOffice >
Advanced and selecting the option Enable macro recording under Optional Features.
By default, this feature is turned off in LibreOffice.
1. Go to Tools > Macros > Record Macro to start recording a macro. A small dialog
with a Stop Recording button is displayed indicating that LibreOffice is recording a
macro.
2. Type the desired text you want to be entered when this macro is run. As an example,
type your name.
3. Click Stop Recording on the small dialog. This will cause Basic Macros dialog to
open (similar to Figure 1, but with different action buttons).
4. Open the library container My Macros.
5. Find the library named Standard in My Macros. Note that every library container has a
library named Standard.
6. Select the Standard library and then choose an existing module in which to save the
macro. Alternatively you can click New Module to create a new module to contain the
newly recorded macro.
7. In the Macro Name text box at the top left section of the dialog, type a name for the
macro you have just recorded, for example EnterMyName.
8. Click Save to save the macro and close the Basic Macros dialog.
If you followed all of the above steps, a macro named EnterMyName will have been
created inside the selected module.
Note
Whenever you create a new module in LibreOffice, a subroutine
named Main is automatically added to the module.
Running a macro
1. Go to Tools > Macros > Run Macro to open the Macro Selector dialog (Figure 6).
2. For example, select your newly created macro EnterMyName and click Run.
3. Alternatively, go to Tools > Macros > Organize Macros > Basic to open the Basic
Macros dialog (Figure 1), select your macro and click Run.
Figure 6: Use the Macro Selector dialog to select and run an existing macro
Viewing and editing macros
To view and/or edit the macro that you created:
1. Go to Tools > Macros > Organize Macros > Basic to open the Basic Macros dialog.
2. Select your new macro EnterMyName and click Edit. The Basic IDE will open and the
macro EnterMyName will be shown as in Listing 3.
This first macro is not complicated. A little explanation will significantly help you in
understanding macros. The discussion starts with first line of the macro and describes
features through the whole listing.
All comments in Basic macro coding begin with REM, which stands for remark. All text
after REM on the same line is ignored by the Basic interpreter when the macro is run.
Tip
As a short cut, you can use the single quote character (') to start a comment.
LibreOffice Basic is not case-sensitive for keywords, so REM, Rem, and rem can all start a
comment. If you use symbolic constants defined by the Application Programming
Interface (API), it is safer to assume that the names are case-sensitive. Symbolic
constants are an advanced topic not covered by this user guide and are not required
when using the macro recorder in LibreOffice.
Individual macros are stored in subroutines and these subroutines begin with the
keyword SUB. The end of a subroutine is indicated by the words END SUB. The code starts
by defining the subroutine named Main, which is empty and does nothing. Note that the
code in Listing 3 for the EnterMyName macro starts with the keyword SUB and ends
with END SUB.
There are advanced topics that are beyond the scope of this user guide, but knowing
about them might be of interest:
You can write subroutines that accept input values to be used inside the macro. These
values are called arguments. This can only be done when you create subroutines
from scratch. Recorded macros in LibreOffice do not accept arguments.
Another kind of subroutine is called a function, which is a subroutine that can return a
value as a result of its work. Functions are defined by the keyword FUNCTION at the
beginning. Recorded macros in LibreOffice create subroutines only.
You can write information on a piece of paper so that you can look at it later. A variable,
like a piece of paper, contains information that can be changed and read.
The DIM keyword originally stood for Dimension and was used to define the dimensions
of an array. The DIM statement used in the EnterMyName macro is similar to setting aside
a piece of paper to be used to store a message or note.
In the EnterMyName macro, the variables document and dispatcher are defined as the
type object. Other common variable types include string, integer, and date. A third
variable, named args1, is an array of property values. A variable of type array allows a
single variable to contain multiple values, similar to storing multiple pages in a single
book. Values in an array are usually numbered starting from zero. The number in the
parentheses indicates the highest usable number to access a storage location. In this
example, there is only one value, and it is numbered zero.
The following is an explanation of the code used in the EnterMyName macro. You may
not understand all the details, but the explanation of each line of code may give you
some idea of how a macro works.
sub EnterMyName
Defines document as an object variable. Objects are a specific variable type with
multiple fields (sometimes they are called properties) and actions (also they are
called methods). The fields can be perceived like variables (including an object)
and actions like subroutines which allow us to operate with the object.
Note
Sometimes the word service is used. A service is supplied by a type of
object which are distinguished in order to point out how they are used.
Declares the args1 array of properties. Each property has a name and a value. In
other words, it is a name/value pair. The created array has one property at index
zero.
The com.sun.star.beans.PropertyValue expression is a Universal Network
Objects (UNO) structure. Structures are special variable types that contain other
variables united by logical basis. They can be convenient to operate with sets of
heterogeneous information that should be treated as a single whole. An
explanation of UNO and user structures goes far beyond the scope of this
book. For more information on creating and using structures, see the LibreOffice
Help system and other Basic guides.
args1(0).Name = "Text"
args1(0).Value = "Your name"
Gives the property the name “Text” and the value “Your name”, which is the text
that is inserted when the macro is run.
dispatcher.executeDispatch(document, ".uno:InsertText", "", 0, args1())
The dispatch helper sends a dispatch to the document frame (stored in the
variable document) with the command .uno:InsertText. The next two arguments,
frame name and search flags, are beyond the scope of this book. The last
argument is the array of property values to be used while executing the
command InsertText.
In other words, this line of code executes the UNO
command .uno:InsertText passing the value “Your Name” as the “Text”
parameter.
end sub
The last line of the code ends the subroutine.
Creating a macro
When creating a macro, it is important to ask two questions before recording:
2. Can the steps be arranged so that the last command leaves the cursor ready for the
next command or entering text or data into the document?
A common task is to copy rows and columns of data from a website and format them as
a table in a text document as follows:
2. To avoid strange formatting and fonts, paste the text into a Writer document as
unformatted text.
3. Reformat the text with tabs between columns so that it can be converted into a table
using Table > Convert > Text to Table.
With the two questions above in mind, inspect the text to see if a macro can be
recorded to format the text. As an example of copied data, consider the text copied
from the API website describing the FontWeight constants (Figure 7). The first column in
this example indicates a constant name and each name is followed by a space and a tab,
and each line has two trailing spaces.
Suppose you want the first column in the table to contain the numeric value of the font
weight, the second column the constant name, and the third column the text
description. This task can be accomplished easily for every row except for DONTKNOW
and NORMAL, which do not contain a numeric value.
Below are the steps to record this macro using keystrokes and assuming that the cursor
is at the beginning of the line with the text “THIN”.
1. Make sure macro recording is enabled by going to Tools > Options > LibreOffice >
Advanced and selecting the option Enable macro recording. By default, this feature
is turned off when LibreOffice is installed on your computer.
2. Go to Tools > Macros > Record Macro to start recording.
3. Press Ctrl+Right Arrow to move the cursor to the start of the word “specifies”.
5. Press Tab to add the tab without the space after the constant name.
6. Press Delete to delete the lower case “s” and then press Shift+S to add an upper case
“S”.
7. Press Ctrl+Right Arrow twice to move the cursor to the start of the number.
8. Press Ctrl+Shift+Right Arrow to select and move the cursor before the % sign.
10. Press End to move the cursor to the end of the line.
11. Press Backspace twice to remove the two trailing spaces.
12. Press Home to move the cursor to the start of the line.
13. Press Ctrl+V to paste the selected number to the start of the line.
14. Pasting the value also pasted an extra space, so press Backspace to remove the extra
space.
15. Press Tab to insert a tab between the number and the name.
18. Stop recording the macro and save the macro, see “Recording a macro” above.
It takes much longer to read and write the steps above than to actually record the
macro. Work slowly and think about the steps as you do them. With practice you will
learn how to organize the steps to create macros that can be used to automate
repetitive tasks.
The generated macro code in Listing 4 has been modified to contain the step numbers
in the comments to match the steps discussed above.
To run this macro, first place the cursor at the beginning of the line to which you want
to apply the recorded steps. Then go to Tools > Macros > Run Macro, select
the CopyNumToCol1 macro and click Run. Figure 8 shows the original line and the
resulting line after applying the macro.
It is not convenient to repeatedly run macros using Tools > Macros > Run Macro. If
you frequently need to use a certain macro, you can assign a keyboard shortcut to
quickly run it. Next are the steps to assign the shortcut Ctrl+K to
the CopyNumToCol1 macro.
2. Select the Keyboard tab. In the Shortcut Keys section, select the Ctrl+K shortcut.
3. In the Category section, select LibreOffice macros. Navigate this section and select
the CopyNumToCol1 macro.
4. Now click the Modify button to assign the Ctrl+K shortcut to the CopyNumToCol1
macro.
5. Click OK to close the Customize dialog.
Now you can run the CopyNumToCol1 macro using the Ctrl+K shortcut. This is very fast
and easy to configure after you get used to the macro workflow. Figure 10 illustrates the
steps described above.
Figure 10: Assigning a shortcut to a macro
Dispatch framework
The dispatch framework can also be used to send “commands” back to the user
interface (UI). For example, after saving a new document, the list of recent files is
updated.
It is not possible to specify what kind of object to create or insert. If an object is inserted
from a file, you cannot specify which file to insert.
If while recording a macro you use Tools > Options to open and modify configuration
items, the generated macro does not record any configuration changes. In fact, the
generated code is commented so it will not even be run.
If a dialog is opened, a command to open the dialog is likely to be generated. Any work
done inside the dialog is not usually recorded. Examples of this include macro
organization dialogs, inserting special characters, and similar types of dialogs. Other
possible problems using the macro recorder include things such as inserting a formula,
setting user data, setting filters in Calc, actions in database forms, and exporting a
document to an encrypted PDF file. You never know for certain what will work unless
you try it. For example, the actions from the search dialog are properly captured.
Other options
When the macro recorder is not able to solve a specific problem, the usual solution is to
write code using the LibreOffice objects. Unfortunately, there is a steep learning curve
for these LibreOffice objects. It is usually best to start with simple examples and then
increase the scope of macros as you learn more. Learning to read generated macros is a
good place to start.
Macro organization
In LibreOffice, macros are grouped in modules, modules are grouped in libraries, and
libraries are grouped in library containers. A library is usually used as a major grouping
for either an entire category of macros, or for an entire application. Modules usually
split functionality, such as user interaction and calculations.
Individual macros are subroutines and functions. Figure 11 shows an example of the
hierarchical structure of macro libraries in LibreOffice.
The LibreOffice Macros are stored with the application runtime code, which may not be
editable to you unless you are an administrator. This helps protect these macros
because they should not be changed and you should not store your own macros in
the LibreOffice Macros container.
Unless your macros are applicable to a single document, and only to a single document,
your macros will probably be stored in the My Macros container. The My
Macros container is stored in your user area or home directory.
Every library container contains a library named Standard. It is better to create your own
libraries with meaningful names than to use the Standard library. Not only are
meaningful names easier to manage, but they can also be imported into other library
containers whereas the Standard library cannot.
Caution
LibreOffice allows you to import libraries into a library container, but it will not
allow you to overwrite the library named Standard. Therefore, if you store
your macros in the Standard library, you cannot import them into another
library container.
Just as it makes good sense to give your libraries meaningful names, it is prudent to use
meaningful names for your modules. By default, LibreOffice uses names such
as Module1, Module2, and so on.
As you create your macros, you must decide where to store them. Storing a macro in a
document is useful if the document will be shared and you want the macro to be
included with the document. Macros stored in the application library container
named My Macros, however, are globally available to all documents.
Macros are not available until the library that contains them is loaded. However, in
contrast to other libraries, the Standard and Template libraries are automatically loaded.
A loaded library is displayed differently from a library that is not loaded. To load the
library and the modules it contains, double-click on the library.
LibreOffice stores user-specific data in a folder inside the user’s home directory. The
location is operating system specific. Go to Tools > Options > LibreOffice > Paths to
view where other configuration data are stored. User macros written in Basic are stored
in LibreOffice\4\user\basic. Each library is stored in its own directory inside
the basic directory.
For casual use, it is not necessary to understand where macros are stored. If you know
where they are stored, however, you can create a backup, share your macros, or inspect
them if there is an error.
Exporting macros
The LibreOffice Basic Macro Organizer dialog allows you to export macro libraries so
that they can be reused and shared with other people. To export a macro library:
1. Go to Tools > Macros > Organize Macros > Basic and the click
the Organizer button.
2. Click the Libraries tab and choose which library you want to export.
3. Click Export and then select Export as BASIC Library (note that you cannot export
the Standard library).
4. Choose where you want to save the library and click Save.
When a library is exported, LibreOffice creates a folder containing all files related to the
library. Figure 12 shows an example of how a library named TestLibrary with a single
module called Module1 would be exported.
1. Select a file and click Open to continue and open the Import Libraries dialog (Figure
14).
Figure 14: Choose library import options
1. Select the following options for importing libraries:
If no options are selected, the library is copied to your user macro directory.
However, if the library you are importing has the same name and you are
importing into the same location, it will not be copied.
Select Insert as reference (read-only) if you want to use the library as
reference, but not import it into the document. When a library is used as a
reference, it remains in its current location and is fully functional, but cannot be
modified in the Basic IDE.
Select Replace existing libraries if the library you want to import has the same
name and you want to replace the existing library.
1. Click OK to import the macro library you selected.
Note
You cannot export/import the library named Standard.
Tip
On Linux, LibreOffice-specific files are stored in the user’s home directory
inside the .config folder. Directories and files with names beginning with a
dot may be hidden and not shown in a normal file selection dialog. When
using LibreOffice dialogs, rather than the operating system’s specific
dialogs, type the name of the desired directory in the Name field.
You can find macros created by the community to download from the internet. Some
macros are contained in documents, some as regular files that you need to import, and
some are published as text and need to be copied and pasted into the Basic IDE. See
“Adding a macro” above on how to add macros to your macro library and “Viewing and
editing macros” above on how to edit macros using the Basic IDE.
Some macros are available as free downloads on the Internet (see Table 1).
The answers will determine where to store the macro and how to make it available. For
example, you will probably not add a rarely used macro to a toolbar. To help determine
your choices, see Table 2.
To add a menu item, keyboard shortcut, or toolbar icon that calls a macro,
use the Customize dialog, which contains pages to configure menus, keyboard
shortcuts, toolbars, and events. To open this dialog, go to Tools > Customize. Use of
the Menus, Toolbars, Context Menus, and Keyboard tabs are covered in Chapter 14,
Customizing LibreOffice.
Events
Caution
Be careful when you configure an event handler. For example, assume that
you write an event handler that is called every time that a document is
modified, but you make a mistake so the event is not properly handled. One
possible result is that your event handler will force you to kill LibreOffice.
1. Go to Tools > Customize to open the Customize dialog and select the Events tab
(Figure 15). The events in the Customize dialog are related to the entire application
and specific documents.
2. In the Save In drop-down, select LibreOffice, or a specific document from the menu
to save your event.
3. A common use is to assign the Open Document event to call a specific macro. The
macro then performs certain setup tasks for the document. Select the desired event
and click Macro to open the Macro Selector dialog (similar to Figure 6 but with
different action buttons).
4. Select the desired macro and click OK to assign the macro to the event.
The Events tab will show that the event has been assigned to a macro.
Many objects in a document can be set to call macros when events occur. The most
common use is to add a control, such as a button, into a document. Even double-
clicking on a graphic opens a dialog with a Macros tab that allows you to assign a
macro to an event.
For more about obtaining and installing extensions, see Chapter 14, Customizing
LibreOffice.
Writing macros without the recorder
The examples covered so far in this chapter were created using the macro recorder and
the dispatcher. You can also write macros that directly access the objects that comprise
LibreOffice if you are confident in writing computer code. In other words, you can create
a macro that directly manipulates a document using more advanced programming
logic.
Macros are organized in the same way for all four scripting languages. The LibreOffice
Macros container holds all the macros that are supplied in the LibreOffice installation.
The My Macros library container holds your macros that are available to any of your
LibreOffice documents. Each document can also contain your macros that are not
available to any other document.
When you use the recording facility, the macros are created in LibreOffice Basic. To use
the other available scripting languages, you must write the code yourself.
When you select to run a macro using Tools > Macros > Run Macro, LibreOffice
displays the Macro Selector dialog. This dialog enables selection and running of any
available macro, coded in any of the available languages (Figure 16).
When you edit a macro using Tools > Macros > Edit Macros, LibreOffice displays the
LibreOffice Basic IDE. This dialog enables selection and editing of any available
LibreOffice Basic macro, but not macros in other languages.
Tip
If you want to learn more about the LibreOffice API as well as UNO objects,
refer to the official API documentation at https://api.libreoffice.org/
BeanShell macros
Click the Edit button on the BeanShell Macros dialog to access the BeanShell Debug
Window (Figure 18).
controller = model.getCurrentController();
sheet = view.getActiveSheet();
textCursor = cellText.createTextCursor();
return 0;
JavaScript macros
When you select Tools > Macros > Organize Macros > JavaScript, LibreOffice
displays the JavaScript Macros dialog (Figure 19).
Click the Edit button on the JavaScript Macros dialog to access the Rhino JavaScript
Debugger (Figure 20). Detailed instructions for using this tool can be found on Mozilla’s
website at https://developer.mozilla.org/en-US/docs/Mozilla/Projects/Rhino/Debugger.
documentRef = XSCRIPTCONTEXT.getDocument();
spreadsheetInterface = UnoRuntime.queryInterface(XSpreadsheetDocument,
documentRef);
allSheets = UnoRuntime.queryInterface(XIndexAccess,
spreadsheetInterface.getSheets());
theSheet = allSheets.getByIndex(0);
Cells = UnoRuntime.queryInterface(XCellRange,theSheet);
cellA1 = Cells.getCellByPosition(0,0);
theCell = UnoRuntime.queryInterface(XCell,cellA1);
Python macros
When you select Tools > Macros > Organize Macros > Python, LibreOffice displays
the Python Macros dialog (Figure 21).
Facilities to edit and debug Python scripts are not currently integrated into the standard
LibreOffice user interface. However, you can use any Python editor to create scripts and
then copy these files into the Scripts folder in your home directory. For more
information, refer to “Where are macros stored?” above.
Listing 8 presents an example of a Python macro that writes the text “Hello World from
Python” into cell A1 of the first sheet in a Calc spreadsheet.
def HelloWorld():
doc = XSCRIPTCONTEXT.getDocument()
cell = doc.Sheets[0]['A1']
cell.setString('Hello World from Python')
return
Tip
The Alternative Python Script Organizer (APSO) extension makes it easier
to edit and organize Python scripts, in particular when embedded in a
document. Using APSO you can configure your preferred source code
editor, start the integrated Python shell and debug Python scripts.
Visit https://gitlab.com/jmzambon/apso to download APSO and learn more
about how to use it.
Tip
To learn more about Python scripting in LibreOffice, you can refer to the Wiki
“Macros/Python Basics”, where you will find in-depth explanations and
examples on how to get started with Python scripting. To learn more,
visit https://wiki.documentfoundation.org/Macros/Python_Basics.