GS4013 GettingStartedWithMacros PDF
GS4013 GettingStartedWithMacros PDF
Chapter 13
Getting Started with Macros
Using the Macro Recorder … and Beyond
Copyright
This document is Copyright © 2010–2013 by its contributors as listed below. You may distribute it
and/or modify it under the terms of either the GNU General Public License
(http://www.gnu.org/licenses/gpl.html), version 3 or later, or the Creative Commons Attribution
License (http://creativecommons.org/licenses/by/3.0/), version 3.0 or later.
All trademarks within this guide belong to their legitimate owners.
Contributors
Ron Faile Jr. Martin Fox Andrew Pitonyak
Peter Schofield
Feedback
Please direct any comments or suggestions about this document to:
[email protected]
Acknowledgments
This chapter is based on Chapter 13 of Getting Started with OpenOffice.org 3.3. The contributors
to that chapter are:
Andrew Pitonyak Jean Hollis Weber
Adding a macro
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 may be in an email, on a web page, or
even in a book. For this example, the macro in Listing 1 is used. You must create a library and
module to contain your macro; see “Macro organization” on page 14 for more information.
11) Click the Compile icon on the Macro toolbar to compile the macro.
12) Click the Run BASIC icon on the Macro toolbar, or press the F5 key, to run the
HelloMacro in the module. A small dialog will open with the word “Hello” displayed.
13) Click OK to close this small dialog.
14) 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 > LibreOffice Basic.
15) Select a macro and then click Run.
Sub HelloMacro
Print "Hello"
End Sub
Sub Main
End Sub
Recording a macro
If you have to repeatedly enter the same information, you can copy this information after it has
been entered into your document for the first time, then paste the information into your document
each time you want to use it. However, if something else is copied to the clipboard, the contents on
the clipboard are changed. This means that you have re-copy your repeated information. To
overcome this problem, you can create a macro that enters your repeated information.
For some types of information that you want to repeatedly enter into a document, it
Note maybe more convenient to create an AutoText file. See the Writer Guide Chapter 3
Working with Text for more information.
1) Make sure macro recording is enabled by going to Tools > Options > LibreOffice >
Advanced on the main menu bar and selecting the option Enable macro recording. By
default, this feature is turned off when LibreOffice was installed on your computer.
2) Go to Tools > Macros > Record Macro on the main menu bar to start recording a macro.
A small dialog is displayed indicating that LibreOffice is recording a macro.
3) Type the desired information or perform an appropriate series of operations. As an
example, type your name.
4) Click Stop Recording on the small Recording dialog to stop recording and the LibreOffice
Basic Macros dialog opens (Figure 1 on page 4).
5) Open the library container My Macros.
6) Find the library named Standard in My Macros. Note that every library container has a
library named Standard.
When LibreOffice creates a new module, it automatically adds the macro named
Note Main.
Running a macro
1) Go to Tools > Macros > Run Macro on the main menu bar to open the Macro Selector
dialog (Figure 5).
2) For example, select your newly created macro EnterMyName and click Run.
3) Alternatively, go to Tools > Macros > Organize Macros > LibreOffice Basic on the main
menu bar to open the LibreOffice Basic Macros dialog, select your macro and click Run.
End Sub
sub EnterMyName
rem -------------------------------------------------------------
rem define variables
dim document as object
dim dispatcher as object
rem -------------------------------------------------------------
rem get access to the document
document = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
rem -------------------------------------------------------------
dim args1(0) as new com.sun.star.beans.PropertyValue
args1(0).Name = "Text"
args1(0).Value = "Your name"
REM comments
All comments in macro coding begin with REM, which stands for remark. All text after REM and on
the same line is ignored. As a short cut, the single quote character (') can also be used 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.
There are advanced topics that are beyond the scope of this user guide, but knowing about them
might be of interest:
• You can write a macro so that values can be passed to the subroutine. The values are
called arguments. However, recorded macros in LibreOffice do not accept arguments.
Creating a macro
When creating a macro, it is important to ask two questions before recording:
1) Can the task be written as a simple set of commands?
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?
sub CopyNumToCol1
rem -------------------------------------------------------------
rem define variables
dim document as object
dim dispatcher as object
rem -------------------------------------------------------------
rem get access to the document
document = ThisComponent.CurrentController.Frame
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")
rem (3) Press Ctrl+Right Arrow to move the cursor to the start of “specifies”.
dispatcher.executeDispatch(document, ".uno:GoToNextWord", "", 0, Array())
rem (4) Press Backspace twice to remove the tab and the space.
dispatcher.executeDispatch(document, ".uno:SwBackspace", "", 0, Array())
rem -------------------------------------------------------------
dispatcher.executeDispatch(document, ".uno:SwBackspace", "", 0, Array())
rem (5) Press Tab to add the tab without the space after the constant name.
Creating a macro 11
dim args4(0) as new com.sun.star.beans.PropertyValue
args4(0).Name = "Text"
args4(0).Value = CHR$(9)
rem (6) ... and then press Shift+S to add an upper case S.
dim args6(0) as new com.sun.star.beans.PropertyValue
args6(0).Name = "Text"
args6(0).Value = "S"
rem (7) Press Ctrl+Right Arrow twice to move the cursor to the number.
dispatcher.executeDispatch(document, ".uno:GoToNextWord", "", 0, Array())
rem -------------------------------------------------------------
dispatcher.executeDispatch(document, ".uno:GoToNextWord", "", 0, Array())
rem (9) Press Ctrl+C to copy the selected text to the clipboard.
dispatcher.executeDispatch(document, ".uno:Copy", "", 0, Array())
rem (10) Press End to move the cursor to the end of the line.
dispatcher.executeDispatch(document, ".uno:GoToEndOfLine", "", 0, Array())
rem (11) Press Backspace twice to remove the two trailing spaces.
dispatcher.executeDispatch(document, ".uno:SwBackspace", "", 0, Array())
rem -------------------------------------------------------------
dispatcher.executeDispatch(document, ".uno:SwBackspace", "", 0, Array())
rem (12) Press Home to move the cursor to the start of the line.
dispatcher.executeDispatch(document, ".uno:GoToStartOfLine", "", 0, Array())
rem (13) Press Ctrl+V to paste the selected number to the start of the line.
dispatcher.executeDispatch(document, ".uno:Paste", "", 0, Array())
rem (15) Press Tab to insert a tab between the number and the name.
dim args17(0) as new com.sun.star.beans.PropertyValue
args17(0).Name = "Text"
args17(0).Value = CHR$(9)
Dispatch framework
The purpose of the dispatch framework is to provide uniform access to components (documents)
for commands that usually correspond to menu items. Using File > Save from the main menu bar,
the shortcut keys Ctrl+S, or clicking the Save icon are all of commands that are translated into the
same “dispatch command”.
The dispatch framework can also be used to send “commands” back to the User Interface (UI). For
example, after saving the document, the File Save command is disabled. As soon as the document
has been changed, the File Save command is enabled.
A dispatch command is text, for example .uno:InsertObject or .uno:GoToStartOfLine. The
command is sent to the document frame and this passes on the command until an object is found
that can handle the command.
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.
If you record Calc macros, and the recorder can correctly generate a macro, there is an add-in
available which converts Calc macros when they are recorded. The final code manipulates
LibreOffice objects rather than generating dispatches. This can be very useful for learning the
object model and can be downloaded directly from the web site:
http://www.paolo-mantovani.org/downloads/DispatchToApiRecorder/
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 7 shows an
example of the hierarchical structure of macro libraries in LibreOffice.
Go to Tools > Macros > Organize Macros > LibreOffice Basic on the main menu bar to open the
LibreOffice Basic Macros dialog (Figure 1 on page 4). All available library containers are shown in
the Macro from list. Every document is a library container, capable of containing multiple libraries.
The application itself acts as two library containers, one container for macros distributed with
LibreOffice called LibreOffice Macros, and one container for personal macros called My Macros.
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 container.
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. The Standard library and
Template library, however, 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.
Macro organization 15
stored in LibreOffice\4\user\basic. Each library is stored in its own directory off the basic
directory.
It is not important to understand where macros are stored for casual use. If you know where they
are stored, however, you can create a backup, share your macros, or inspect them if there is an
error.
Go to Tools > Macros > Organize Dialogs on the main menu bar to open the LibreOffice Macro
Organizer dialog (Figure 2 on page 5). Alternatively, go to Tools > Macros > Organize Macros >
LibreOffice Basic on the main menu bar to open the LibreOffice Macros dialog (Figure 1 on page
4) and then click the Organizer button.
Importing macros
The LibreOffice Macro Organizer dialog allows you to import macro libraries into your document as
well as creating, deleting, and renaming libraries, modules, and dialogs.
1) Select the library container to use and then click Import to import macro libraries (Figure 2
on page 5).
2) Navigate to the directory containing the library to import (Figure 8). There are usually two
files from which to choose, dialog.xlb and script.xlb. It does not matter which of these two
files you select; both will be imported. Macros can be stored in libraries inside LibreOffice
documents. Select a document rather than a directory on disk to import libraries contained
in a document.
On a computer operating Linux, the LibreOffice specific files are stored in the home
directory of a user in a directory whose name begins with a period. Directories and
Tip files with names beginning with a period are normally hidden and not shown in a
normal selection dialog. To open hidden folders and files, press Ctrl-H to show
hidden folders and files not normally shown and navigate as usual.
Macro organization 17
How to run a macro
Although you can use Tools > Macros > Run Macro to run all macros, this is not efficient for
frequently run macros. See “Running a macro” on page 7 for more information.
A more common technique for frequently used macros is to assign the macro a toolbar icon, menu
item, keyboard shortcut, or a button embedded in a document. While choosing a method, it is also
good to ask questions such as:
• Should the macro be available for only one document, or globally for all documents?
• Is the macro for a specific document type, such as a Calc document?
• How frequently will the macro be used?
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.
Events
In LibreOffice, when something happens it is that has an event occurred. For example, opening a
document, pressing a key, or moving the mouse cursor. LibreOffice allows events to cause a
macro to be called; the macro is then called an event handler. Full coverage of event handlers is
well beyond the scope of this document, but a little knowledge can accomplish much.
Be careful when you configure an event handler. For example, assume that you
Caution
write an event handler that is called every time that a key is pressed, but you make a
mistake so the event is not properly handled. One possible result is that your event
handler will consume all key presses, forcing you to forcibly terminate LibreOffice.
1) Go to Tools > Customize on the main menu bar to open the Customize dialog and select
the Events tab (Figure 11). The events in the Customize dialog are related to the entire
application and specific documents.
2) In Save In, select LibreOffice, or a specific document from the drop down 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 (Figure 5 on page 7).
4) Select the desired macro and click OK to assign the macro to the event. The Events page
shows that the event has been assigned to a macro.
Extensions
An extension is a package that can be installed into LibreOffice to add new functionality.
Extensions can be written in almost any programming language and may be simple or
sophisticated. Extensions can be grouped into types:
• Calc Add-Ins, which provide new functionality for Calc, including new functions that act like
normal built-in functions
• New components and functionality, which normally include some level of User Interface (UI)
integration such as new menus or toolbars
• Pivot Tables that are used directly in Calc
• Chart Add-Ins with new chart types
• Linguistic components such as spell checkers
• Document templates and images
Although individual extensions can be found in several places, there is currently an extension
repository at: http://extensions.libreoffice.org/ and some documentation at
http://libreplanet.org/wiki/Group:OpenOfficeExtensions/List
For more about obtaining and installing extensions, see Chapter 14 Customizing LibreOffice.
Sub AppendHello
Dim oDoc
Dim sTextService$
Dim oCurs
Included material
Many excellent macros are included with LibreOffice. Use Tools > Macros > Organize Macros >
LibreOffice Basic to open the Macro dialog. Expand the Tools library in the LibreOffice library
container. Inspect the Debug module—some good examples include WritedbgInfo(document) and
printdbgInfo(sheet).
Online resources
The following links and references contain information regarding macro programming:
http://ask.libreoffice.org/ (a Q & A site where volunteers answer questions related to LibreOffice)