Getting Started Guide

13

Chapter
Getting Started with
MacrosUsing the Macro RecorderThis PDF is designed to be read onscreen, two pages at atime. If you want to print a copy, your PDF viewer shouldhave an option for printing two pages on one sheet ofpaper, but you may need to start with page 2 to get it toprint facing pages correctly. (Print this cover page
separately.)CopyrightThis document is Copyright © 2007–2010 by its contributors as listed
in the section titled Authors. You may distribute it and/or modify it
under the terms of either the GNU General Public License, version 3 orlater, or the Creative Commons Attribution License, version 3.0 or
later.
All trademarks within this guide belong to their legitimate owners.

Authors
Andrew Pitonyak
Jean Hollis Weber

Feedback
Maintainer: Andrew Pitonyak
Please direct any comments or suggestions about this document to:authors@user-faq.openoffice.org

Publication date and software version
Published 5 January 2010. Based on OpenOffice.org 3.2.

You can download
an editable version of this document fromhttp://oooauthors.org/english/userguide3/published/

Contents
Your first macro.....................................................................................4
Creating a simple macro.....................................................................4
Running the macro.............................................................................5
Viewing and editing the macro...........................................................6
Comments start with REM...............................................................7
Defining subroutines with SUB........................................................7
Defining variables using DIM..........................................................8
Pulling the macro together..............................................................8
Creating a macro...................................................................................9
A complicated example.......................................................................9
Running the macro quickly...............................................................13
Sometimes the macro recorder fails....................................................13
The dispatch framework...................................................................13
How the macro recorder uses the dispatch framework....................14
Other options.................................................................................... 14
Macro organization.............................................................................. 15
Where are macros stored?................................................................17
Importing macros.............................................................................. 18
Downloading macros to import.........................................................20
How to run a macro.............................................................................20
Toolbar.............................................................................................. 23
Menu item......................................................................................... 23
Keyboard shortcuts...........................................................................23
Event................................................................................................. 23
Extensions............................................................................................ 25
Writing macros without the recorder...................................................26
Finding more information....................................................................27
Included material.............................................................................. 27
Online resources............................................................................... 27
Printed and eBook materials.............................................................28

Getting Started with Macros3

Your first macro
A macro is a saved sequence of commands or keystrokes that are
stored for later use. An example of a simple macro is one that “types”
your address. The OpenOffice.org macro language is very flexible,
allowing automation of both simple and complex tasks. Macros areespecially useful to repeat a task the same way over and over again.
OpenOffice.org macros are usually written in a language called
StarBasic, or just abbreviated Basic. Although you can learn Basic andwrite macros, there is a steep learning curve to writing macros fromscratch. The usual method for a beginner is to use the built-in macro
recorder, which records your keystrokes and saves them for use.
Most tasks in OpenOffice.org are accomplished by “dispatching acommand” (sending a command), which is intercepted and used. The
macro recorder works by recording the commands that are dispatched(see “The dispatch framework” on page 13).

Creating a simple macro
Imagine repeatedly entering simple information. Although you canstore the information in the clipboard, if you use the clipboard forsomething else, the contents are changed. Storing the contents as a
macro is a simple solution. (In some simple cases, including theexample used here, a better solution is to use AutoText.)
1) Use Tools > Macros > Record Macro to start recording amacro.
A small window is displayed so you know that
OpenOffice.org is recording.
2) Type the desired information or perform an appropriate series ofoperations. In this case, I typed my name, Andrew Pitonyak.
3) Click the Stop Recording button to stop recording, save themacro, and display the OpenOffice.org Basic Macros dialog (seeFigure 1).
4) Be certain to open the library container named My Macros. Find
the library named Standard under My Macros. Be warned, every
library container has a library named Standard. Select theStandard library and click New Module to create a new module
to contain the macro.

4

Getting Started with Macros

Figure 1: OOo Macro Organizer dialog, DBInspection library selected
5) The default module name is Module1; choose a better name.
Although it is still not descriptive, I used Recorded. Type adescriptive name and click OK to create the module. The
OpenOffice.org Basic Macros dialog is displayed again, showing
the new module.

Figure 2: Give your module a meaningful name
6) Highlight the newly created module. In the upper left corner, typethe macro name to use, such as “EnterMyname”, and then click
Save to save the macro.
If you followed all of the steps, the Standard library now contains amodule named Recorded, which contains the EnterMyName macro, asshown in Figure 3. When OOo creates a new module, it automaticallyadds the macro named Main; as seen in Figure 3.

Running the macro
Use Tools > Macros > Run Macro to open the Macro Selector dialog(see Figure 3). Select the newly created macro and click Run.

Your first macro

5

Figure 3: Select your macro and click Run
There are other methods to run a macro. For example, use Tools >Macros > Organize Macros > OpenOffice.org Basic to open themacro organizer, which contains a Run button as well. The author, anavid macro writer, prefers the macro organizer because the dialog
usually opens faster, but the selection process may be slightly slower.

Viewing and editing the macro
You can view and edit the macro that was just created. Use Tools >Macros > Organize Macros > OpenOffice.org Basic to open the
OpenOffice.org Basic Macros dialog (see Figure 3). Select the newmacro and click Edit to open the macro in the Basic IDE (Integrated
Development Environment).
Listing 1: Generated “EnterMyname” macro.
REM *****Sub Main

BASIC

*****

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
6

Getting Started with Macrosdispatcher = createUnoService("com.sun.star.frame.DispatchHelper")rem ------------------------------------------------------------dim args1(0) as new com.sun.star.beans.PropertyValueargs1(0).Name = "Text"
args1(0).Value = "Andrew Pitonyak"
dispatcher.executeDispatch(document, ".uno:InsertText", "", 0, args1())
end sub

The macro in Listing 1 is not as complicated as it first appears.
Learning a few things helps significantly in understanding thegenerated macros. The discussion starts with features near the top of
the macro listing and describes them. If you like to avoid details, thensimply change the text “Andrew Pitonyak” to what you want to insert at
the current cursor position.

Comments start with REM
The keyword REM, short for remark, starts a macro comment. All text
after REM (on the same line) is ignored. As a short cut, the single
quote character can also be used to start a comment.

Tip

StarBasic is not case-sensitive for keywords, so REM, Rem,and rem all start a comment. If you use symbolic constants
defined by the API, it is safer to assume that the names arecase-sensitive—symbolic constants are an advanced topic not
usually needed by people that use the macro recorder.

Defining subroutines with SUB
Individual macros are stored in subroutines defined 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. The next subroutine, EnterMyName, contains thegenerated code.
Tip

OpenOffice.org creates an empty subroutine named Main
when it creates a module.

There are advanced topics that are beyond the scope of this document,
but knowing about them might be of interest:• You can write a macro so that values can be passed to thesubroutine. The values are called arguments. Recorded macros do
not accept arguments.

Your first macro

7• Another kind of subroutine is called a function. A function is asubroutine that returns a value. The keyword FUNCTION is usedrather than SUB to define a function. Generated macros arealways of type SUB.

Defining variables using DIM
You can write information on a piece of paper so that you can look at itlater. A variable, like a piece of paper, contains information that can bechanged and read. The DIM statement is similar to setting aside apiece of paper to be used to store a message or note.
The EnterMyName macro defines the variables document anddispatcher as type object. Other common variable types include string,
integer, and date. A third variable, named args1, is an array ofproperty values. A variable of type array allows a single variable tocontain 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 toaccess a storage location. In this example, there is only one value, and
it is numbered zero.

Pulling the macro together
The following details are very complete; it is not important tounderstand all of the details. The first line defines the start of themacro.
sub EnterMyName

Declare two variables:
dim document
as object
dim dispatcher as object

ThisComponent refers to the current document.
The CurrentController property of a document refers to a service that“controls” the document. For example, when you type, it is the current
controller that notices. The current controller then dispatches thechanges to the document’s frame.
The Frame property of a controller returns a main frame for a
document. Therefore, the variable named document refers to a
document’s frame, which receives dispatched commands.
document = ThisComponent.CurrentController.Frame

Most tasks in OpenOffice.org are accomplished by dispatching acommand. OOo version 2.0 introduced the dispatch helper service,
which does most of the work to use dispatches in macros. The method
8

Getting Started with Macros

CreateUnoService accepts the name of a service and it tries to create
an instance of that service. On completion, the dispatcher variable
contains a reference to a DispatchHelper.
dispatcher = createUnoService("com.sun.star.frame.DispatchHelper")Declare an 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.
dim args1(0) as new com.sun.star.beans.PropertyValue

Give the property the name “Text” and the value “Andrew Pitonyak”,
which is the text that is inserted when the macro is run.
args1(0).Name = "Text"
args1(0).Value = "Andrew Pitonyak"

This is where the magic happens. The dispatch helper sends a dispatch
to the document’s frame (stored in the variable named document) withthe command .uno:InsertText. The next two arguments, frame nameand search flags, are beyond the scope of this document. The lastargument is the array of property values to be used while executing
the command InsertText.
dispatcher.executeDispatch(document, ".uno:InsertText", "", 0, args1())

Finally, the end of the subroutine.
end sub

Creating a macro
I usually ask two questions before recording a macro:
1) Can the task be written as a simple set of commands?
2) Can the steps be arranged such that the last command leaves the
cursor ready for the next command?

A complicated example
I frequently copy rows and columns of data from a web site and format
them as a table in a text document. First, I copy the table from the website to the clipboard. To avoid strange formatting and fonts, I paste thetext into a Writer document as unformatted text. I reformat the text
with tabs between columns so that I can use Table > Convert > Text
to Table to convert to a table.
I inspect the text to see if I can record a macro to format the text
(remember the two questions that I ask). As an example, I copied the
FontWeight constants group from the OpenOffice.org web site. The
Creating a macro9first column indicates the constant name. Each name is followed by aspace and a tab.
DONTKNOW

The font weight is not specified/known.

THIN

specifies a 50% font weight.

ULTRALIGHT specifies a 60% font weight.
LIGHT

specifies a 75% font weight.

SEMILIGHT

specifies a 90% font weight.

NORMAL

specifies a normal font weight.

SEMIBOLD

specifies a 110% font weight.

BOLD

specifies a 150% font weight.

ULTRABOLD

specifies a 175% font weight.

BLACK

specifies a 200% font weight.

I want the first column to contain the numeric value, the second
column the name, and the third column the description. The desired
work is easily accomplished for every row except for DONTKNOW andNORMAL, which do not contain a numeric value—but I know that thevalues are 0 and 100, so I will enter those manually.
The data can be cleaned in multiple ways—all of them easy. The firstexample uses keystrokes that assume the cursor is at the start of theline with the text THIN.
1) Use Tools > Macros > Record Macro to start recording.
2) Press Ctrl+Right Arrow to move the cursor to the start of“specifies”.
3) Press Backspace twice to remove the tab and the space.
4) Press Tab to add the tab without the space after the constantname.
5) Press Delete to delete the lower case s and then press S to add anupper case S.
6) Press Ctrl+Right Arrow twice to move the cursor to the start of
the number.
7) Press Ctrl+Shift+Right Arrow to select and move the cursor
before the % sign.
8) Press Ctrl+C to copy the selected text to the clipboard.
9) Press End to move the cursor to the end of the line.
10

Getting Started with Macros10) Press Backspace twice to remove the two trailing spaces.
11) Press Home to move the cursor to the start of the line.
12) Press Ctrl+V to paste the selected number to the start of the line.
13) Pasting the value also pasted an extra space, so press Backspace
to remove the extra space.
14) Press Tab to insert a tab between the number and the name.
15) Press Home to move to the start of the line.
16) Press down arrow to move to the next line.
17) Stop recording the macro and save the macro.
It takes much longer to read and write the steps than to record themacro. Work slowly and think about the steps as you do them. With
practice this becomes second nature.
The generated macro has been modified to contain the step number inthe comments to match the code to the step above.
Listing 2: Copy the numeric value to the start of the column.
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 (2) Press Ctrl+Right Arrow to move the cursor to the start of “specifies”.
dispatcher.executeDispatch(document, ".uno:GoToNextWord", "", 0, Array())
rem (3) 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 (4) Press Tab to add the tab without the space after the constant name.
dim args4(0) as new com.sun.star.beans.PropertyValueargs4(0).Name = "Text"
args4(0).Value = CHR$(9)dispatcher.executeDispatch(document, ".uno:InsertText", "", 0, args4())
rem (5) Press Delete to delete the lower case s ....
dispatcher.executeDispatch(document, ".uno:Delete", "", 0, Array())
rem (5) ... and then press S to add an upper case S.
dim args6(0) as new com.sun.star.beans.PropertyValueargs6(0).Name = "Text"
args6(0).Value = "S"

Creating a macro

11

dispatcher.executeDispatch(document, ".uno:InsertText", "", 0, args6())
rem (6) 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 (7) Press Ctrl+Shift+Right Arrow to select the number.
dispatcher.executeDispatch(document, ".uno:WordRightSel", "", 0, Array())
rem (8) Press Ctrl+C to copy the selected text to the clipboard.
dispatcher.executeDispatch(document, ".uno:Copy", "", 0, Array())
rem (9) Press End to move the cursor to the end of the line.
dispatcher.executeDispatch(document, ".uno:GoToEndOfLine", "", 0, Array())
rem (10) 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 (11) Press Home to move the cursor to the start of the line.
dispatcher.executeDispatch(document, ".uno:GoToStartOfLine", "", 0, Array())
rem (12) Press Ctrl+V to paste the selected number to the start of the line.
dispatcher.executeDispatch(document, ".uno:Paste", "", 0, Array())
rem (13) Press Backspace to remove the extra space.
dispatcher.executeDispatch(document, ".uno:SwBackspace", "", 0, Array())
rem (14) Press Tab to insert a tab between the number and the name.
dim args17(0) as new com.sun.star.beans.PropertyValueargs17(0).Name = "Text"
args17(0).Value = CHR$(9)dispatcher.executeDispatch(document, ".uno:InsertText", "", 0, args17())
rem (15) Press Home to move to the start of the line.
dispatcher.executeDispatch(document, ".uno:GoToStartOfLine", "", 0, Array())
rem (16) Press down arrow to move to the next line.
dim args19(1) as new com.sun.star.beans.PropertyValueargs19(0).Name = "Count"args19(0).Value = 1
args19(1).Name = "Select"args19(1).Value = false
dispatcher.executeDispatch(document, ".uno:GoDown", "", 0, args19())
end sub

12

Getting Started with Macros

Cursor movements are used for all operations (as opposed tosearching). If run on the DONTKNOW line, the word weight is moved
to the front of the line, and the first “The” is changed to “She”. This is
not perfect, but I should not have run the macro on the lines that did
not have the proper format; I need to do these manually.

Running the macro quickly
It is tedious to repeatedly run the macro using Tools > Macros > Run
Macro (see Figure 3). The macro can be run from the IDE. Use Tools> Macros > Organize Macros > OpenOffice.org Basic to open the
Basic Macro dialog. Select your macro and click Edit to open themacro in the IDE.
The IDE has a Run Basic icon in the toolbar that runs the first macroin the IDE. Unless you change the first macro, it is the empty macro
named Main. Modify Main so that it reads as shown in Listing 3.
Listing 3: Modify Main to call CopyNumToCol1.
Sub Main
CopyNumToCol1
End Sub

Now, you can run CopyNumToCol1 by repeatedly clicking the Run
Basic icon in the toolbar of the IDE. This is very fast and easy,
especially for temporary macros that will be used a few times and thendiscarded.

Sometimes the macro recorder fails
Understanding the OpenOffice.org internals helps to understand how
and why the macro recorder frequently fails. The primary offender isrelated to the dispatch framework and its relationship to the macro
recorder.

The dispatch framework
The purpose of the dispatch framework is to provide a uniform accessto components (documents) for commands that usually correspond tomenu items. I can use File > Save from the menu, the shortcut keys
Ctrl+S, or click on the Save toolbar icon. All of these commands aretranslated into the same “dispatch command”, which is sent to thecurrent document.

Sometimes the macro recorder fails

13

The dispatch framework can also be used to send “commands” back to
the UI (User Interface). For example, after saving the document, theFile Save command is disabled. As soon as the document has beenchanged, the File Save command is enabled.
If we see a dispatch command, it is text such as .uno:InsertObject or.uno:GoToStartOfLine. The command is sent to the document’s frame,
and the frame passes on the command until an object is found that canhandle the command.

How the macro recorder uses the dispatch
framework
The macro recorder records the generated dispatches. The recorder isrelatively simple to implement and the same commands that are issued
are recorded for later use. The problem is that not all dispatchedcommands are complete. For example, inserting an object generates
the following code:
dispatcher.executeDispatch(document, ".uno:InsertObject", "", 0, Array())

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.
I recorded a macro and used 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.
rem dispatcher.executeDispatch(document,".uno:OptionsTreeDialog", "", 0, Array())

If a dialog is opened, the command to open the dialog is likely to begenerated. Any work done inside the dialog is not usually recorded.
Examples 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, settinguser data, setting filters in Calc, actions in database forms, andexporting a document to an encrypted PDF file. You never know for
certain what will work unless you try it, however. The actions from thesearch dialog are properly captured, for example.

Other options
When the macro recorder is not able to solve a specific problem, theusual solution is to write code using the OpenOffice.org objects.
Unfortunately, there is a steep learning curve for the OOo objects. It is
usually best to start with simple examples and then branch out slowly
14

Getting Started with 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 amacro, there is an add-in created by Paolo Mantovani, which converts
Calc macros when they are recorded. The final code manipulates
OpenOffice.org objects rather than generating dispatches. This can bevery useful for learning the object model.
You can download the macro recorder from Paolo’s web site directly orfrom the OOo Macros web site. You should check both places to see
which contains the latest version.
http://www.paolo-mantovani.org/downloads/ DispatchToApiRecorder/
http://www.ooomacros.org/user.php

Macro organization
In OpenOffice.org, macros are grouped in modules, modules aregrouped 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 4: Macro Library hierarchy
A computer scientist would use Figure 5 to precisely describe thesituation. The text “1..*” means one or more, and “0..*” means zero or
more. The black triangle means composed of or contains.

Macro organization15

• A library container contains one or more libraries, and eachlibrary is contained in one library container.
• A library contains zero or more modules, and each module iscontained in one library.
• A module contains zero or more macros, and each macro iscontained in one module.

Figure 5: Macro Library hierarchy
Use Tools > Macros > Organize Macros > OpenOffice.org Basic
to open the OpenOffice.org Basic Macros dialog (see Figure 6). Allavailable 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 OpenOffice.org called
OpenOffice.org Macros, and one container for personal macros called
My Macros. As shown in Figure 6, only two documents are currently
open.

Figure 6: Library containers are shown on the left
The OpenOffice.org Macros are stored with the application runtime
code, which may not be editable to you unless you are an
administrator. This is just as well since these macros should not bechanged and you should not store your own macros in the OOocontainer.
Unless your macros are applicable to a single document, and only to asingle document, your macros will probably be stored in the My
16

Getting Started with Macros

Macros container. The My Macros container is stored in your user areaor home directory.
If a macro is contained in a document, then a recorded macro willattempt to work on that document; primarily because it uses
“ThisComponent” for its actions.
Every library container contains a library named Standard. It is betterto create your own libraries with meaningful names than to use theStandard library. Not only are meaningful names easier to manage, butthey can also be imported into other library containers whereas theStandard library cannot.
CautionOpenOffice.org 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 theStandard library, you cannot import them into anotherlibrary 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,
OpenOffice.org uses names such as Module1. Feel free to use your own
meaningful name.
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. Macrosstored 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 automaticallyloaded. A loaded library is displayed differently from a library that is
not loaded. To load the library and the modules it contains, doubleclick on the library.

Where are macros stored?
OpenOffice.org stores user-specific data in a directory under the user’s
home directory. For example, on Windows, this is C:\Documents andSettings\<name>\Application Data. User macros are stored in
OpenOffice.org2\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 casualuse. If you know where they are stored, however, you can create abackup, share your macros, or inspect them if there is an error. For
Macro organization17

example, on one or more of my OpenOffice.org upgrades, all of mymacros disappeared. Although the macros were still on disk, themacros were not copied to the new directories. The solution was toimport the macros into the new installation.
Use Tools > Macros > Organize Dialogs to open the OpenOffice.org
Macros organizer dialog. Another common way to open this dialog is touse Tools > Macros > Organize Macros > OpenOffice.org Basic
to open the OpenOffice.org Macros dialog and then click theOrganizer button (see Figure 7).

Figure 7: The macro organizer dialog

Importing macros
The OpenOffice.org Macro Organizer dialog provides functionality tocreate, delete, and rename libraries, modules, and dialogs. Select thelibrary container to use and then click the Import button to importmacro libraries (see Figure 8).

18

Tip

You cannot import the library named Standard.

Tip

On Linux, the OpenOffice.org-specific files are stored in a
directory whose name begins with a period. Directories andfiles with names beginning with a period are not shown in anormal selection dialog. To open the directory, I navigated tothe parent directory, entered the name .openoffice.org2.0, andthen clicked Open. This opened the directory, which was notinitially shown.

Getting Started with Macros

Figure 8: Select a macro library to import
Navigate to the directory containing the library to import. There areusually 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.
Select a file and click Open to continue (see Figure 9).

Figure 9: Choose library import options
If the library already exists, it will not be replaced unless Replace
existing libraries is checked. If Insert as reference is checked, thelibrary is referenced in its current location, but you cannot edit thelibrary. If Insert as reference is not checked, however, the library is
copied to the user’s macro directory.
Macros can be stored in libraries inside OpenOffice.org documents.
Select a document rather than a directory on disk (as shown in Figure8) to import libraries contained in a document.

Macro organization

19

Downloading macros to import
Macros are available for download. Some macros are contained in
documents, some as regular files that you must select and import, andsome as macro text that should be copied and pasted into the Basic
IDE; use Tools > Macros > Organize Macros > OpenOffice.org
Basic to open the OpenOffice.org Macros dialog, choose the macro toedit, and then click Edit to open the macro in the Basic IDE.
Some macros are available as free downloads on the Internet (seeTable 1).
Table 1. Places to find macro examples
Location

Description

http://www.ooomacros.org/

Excellent collection of packaged
macros.

http://www.pitonyak.org/oo.php

Reference materials regarding macros.

http://www.pitonyak.org/database/

Reference materials regarding
database macros.

http://development.openoffice.org/

Lots of links to everything.

http://www.oooforum.org/

Many examples and help.

How to run a macro
A typical method to run a macro is as follows:
1) Use Tools > Macros > Run Macro to open the Macro Selector
dialog (see Figure 10).
2) Select the library and module in the Library list (left hand side).
3) Select the macro in the Macro name list (right hand side).
4) Click Run to run the macro.

20

Getting Started with Macros

Figure 10: Use the Macro Selector dialog to run macros
Although you can use Tools > Macros > Run Macro to run all
macros, this is not efficient for frequently run macros. A more common
technique is to assign a macro to a toolbar button, menu item,
keyboard shortcut, or a button embedded in a document. Whilechoosing a method, it is also good to ask questions such as:• Should the macro be available for only one document, or globallyfor all documents?
• Does the macro pertain to 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 makeit available. For example, you will probably not add a rarely used
macro to a toolbar. To help determine your choices, see Table 2.
Table 2. Methods for starting a macro
Type

OpenOffice.org

Document Type

Document

Toolbar

No

Yes

Yes

Menu

No

Yes

Yes

Shortcut

Yes

Yes

No

Event

Yes

No

Yes

How to run a macro21

To add a menu item, keyboard shortcut, or toolbar icon that calls amacro, use the Customize dialog (see Figure 12). Open this dialog ineither of these ways:• Choose Tools > Customize from the main menu bar.
• Each toolbar has an iconthat opens a menu; choose theCustomize Toolbar option.

Tip

Complete coverage of the Customize dialog is beyond thescope of this document. Click the Help button to access thehelp pages included with OpenOffice.org.

The Customize dialog contains tabs to configure menus, keyboard
bindings, toolbars, and events.

Figure 11: OpenOffice.org Customize dialog

22

Getting Started with Macros

Toolbar
Macros can be added to toolbars. For more about modifying toolbars,
see Chapter 14 (Customizing OpenOffice.org).

Menu item
Use Tools > Customize to open the Customize dialog, and select the
Menus tab. You can modify an existing menu, or create new menus thatcall macros. For more about modifying menus, see Chapter 14.

Keyboard shortcuts
Use Tools > Customize to open the Customize dialog, and select the
Keyboard tab. Assigning keyboard shortcuts is discussed in Chapter 14.

Event
In OpenOffice.org, when something happens, we say that an event
occurred. For example, a document was opened, a key was pressed, or
the mouse moved. OpenOffice.org allows events to cause a macro to becalled; 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.

CautionBe careful when you configure an event handler. For
example, assume that you write an event handler that iscalled 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 OpenOffice.org.

Use Tools > Customize to open the Customize dialog, and select the
Events tab (see Figure 12). The events in the Customize dialog are
related to the entire application and specific documents. Use the Save
In box to choose OpenOffice.org, or a specific document.

How to run a macro

23

Figure 12: Assign macro to an application level event
A common use is to assign the Open Document event to call a specificmacro. The macro then performs certain setup tasks for the document.
Select the desired event and click the Macro button to open the Macro
Selector dialog (see Figure 13).
Select the desired macro and click OK to assign the macro to theevent. The Events tab shows that the event has been assigned to a
macro (see Figure 14). When the document opens, the PrintHellomacro is run.
Many objects in a document can be set to call macros when eventsoccur. The most common usage is to add a control, such as a button,
into a document. Even double-clicking on a graphic opens a dialog witha Macros tab that allows you to assign a macro to an event.

24

Getting Started with Macros

Figure 13: Assign macro to the document open event

Figure 14: PrintHello is assigned to the Open Document event

Extensions
An extension is a package that can be installed into OpenOffice.org 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 somelevel of UI integration such as new menus or toolbars
Data pilots that are used directly in Calc
Chart Add-Ins with new chart types
Linguistic components such as spell checkers
Document templates and images

Extensions

25

Although individual extensions can be found in different places, there
is an extension repository at: http://extensions.services.openoffice.org/.
For more about obtaining and installing extensions, see Chapter 14(Customizing OpenOffice.org).

Writing macros without the recorder
The examples covered in this chapter are created using the macro
recorder and the dispatcher. You can also write macros that directly
access the objects that comprise OpenOffice.org. In other words, you
can directly manipulate a document.
Directly manipulating OOo’s internal objects is an advanced topic thatis beyond the scope of this chapter. A simple example, however,demonstrates how this works.
Listing 4: Append the text “Hello” to the current document.
Sub AppendHelloDim oDocDim sTextService$
Dim oCurs
REM ThisComponent refers to the currently active document.
oDoc = ThisComponent
REM Verify that this is a text document
sTextService = "com.sun.star.text.TextDocument"
If NOT oDoc.supportsService(sTextService) Then
MsgBox "This macro only works with a text document"
Exit SubEnd If
REM Get the view cursor from the current controller.
oCurs = oDoc.currentController.getViewCursor()
REM Move the cursor to the end of the document
oCurs.gotoEnd(False)
REM Insert text "Hello" at the end of the document
oCurs.Text.insertString(oCurs, "Hello", False)
End Sub

26

Getting Started with Macros

Finding more information
Numerous resources are available that provide help with writing
macros. Use Help > OpenOffice.org Help to open the OOo help
pages. The upper left corner of the OOo help system contains a dropdown list that determines which help set is displayed. To view the help
for Basic, choose OpenOffice.org Basic from this list.

Included material
Many excellent macros are included with OOo. Use Tools > Macros >Organize Macros > OpenOffice.org Basic to open the Macro dialog.
Expand the Tools library in the OpenOffice.org 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://user.services.openoffice.org/ (OOo forums, well supported)
http://api.openoffice.org/docs/common/ref/com/sun/star/module-ix.html(official IDL reference; here you'll find almost every command with adescription)
http://wiki.services.openoffice.org/wiki/Documentation/BASIC_Guide(official OpenOffice.org BASIC Programming Guide)
http://wiki.services.openoffice.org/wiki/Documentation/DevGuide/Open
Office.org_Developers_Guide (official OpenOffice.org Developers
Guide; contains a detailed explanation)
http://www.pitonyak.org/oo.php (Andrew Pitonyak’s macro page)
http://www.pitonyak.org/AndrewMacro.odt (numerous examples ofworking macros)
http://www.pitonyak.org/book/ (Andrew Pitonyak’s book on macros)
http://www.pitonyak.org/database/ (numerous macro examples using
Base)
http://docs.sun.com/app/docs/doc/819-0439 (Sun’s book on macro
programming—very well written and laid out; the OOo BASIC
Programming Guide and the OOo Developers Guide are derived fromthis book)Finding more information27

Printed and eBook materials
The following books are available for purchase in both printed andeBook form from their publishers.
Andrew Pitonyak’s OpenOffice.org Macros Explained. See
http://www.hentzenwerke.com/catalog/oome.htm.
Dr. Mark Alexander Bain’s Learn OpenOffice.org Spreadsheet Macro
Programming. See http://www.packtpub.com/openoffice-ooobasic-calcautomation/book.

28

Getting Started with Macros