You are on page 1of 24

Getting Started Guide

Chapter 13
Getting Started with Macros
Using the Macro Recorder and beyond
Copyright
This document is Copyright 20102011 by its contributors as listed below. You may distribute it
and/or modiy it under the terms o either the G!" General #ublic $icense
%http://www.gnu.org/licenses/gpl.htl&' (ersion ) or later' or the Creati(e Commons *ttribution
$icense %http://creati!ecoons.org/licenses/by/3."/&' (ersion ).0 or later.
*ll trademar+s within this guide belong to their legitimate owners.
Contributors
,on -aile .r.
/artin -o0
*ndrew #itonya+
Feedback
#lease direct any comments or suggestions about this document to1
docuentation#global.libreo$$ice.org
Acknowledgments
This chapter is based on Chapter 1) o Getting Started with %pen%$$ice.org 3.3. The contributors
to that chapter are1
*ndrew #itonya+
.ean 2ollis 3eber
Publication date and software version
#ublished 14 *ugust 2011. 5ased on $ibre6ice ).).).
Note for Mac users
Some +eystro+es and menu items are dierent on a /ac rom those used in 3indows and $inu0.
The table below gi(es some common substitutions or the instructions in this chapter. -or a more
detailed list' see the application 2elp.
Windows/Linux Mac equivalent Effect
Tools Options
menu selection
ibreoffice ! Preferences *ccess setup options
Right&clic' Control(clic' 6pens a conte0t menu
Ctrl )Control* z )Coand* "sed with other +eys
+, Shi$t(z7+, 6pens the !a(igator
+11 z7- 6pens the Styles and -ormatting window
.ocuentation $or /ibre%$$ice is a!ailable at www.libreo$$ice.org
Contents
0ote $or Mac users........................................................................................................................... 1
2our $irst acros.............................................................................................................................. 3
4dding an e5isting acro............................................................................................................ 3
Creating a siple acro.............................................................................................................. ,
Running the acro...................................................................................................................... 6
7iewing and editing the acro..................................................................................................... 6
Coents start with R8M...................................................................................................... 9
.e$ining subroutines with SU:................................................................................................ 9
.e$ining !ariables using .;M.................................................................................................. 9
<ulling the acro together...................................................................................................... =
Creating a acro............................................................................................................................. =
4 coplicated e5aple................................................................................................................ =
Running the acro >uic'ly........................................................................................................ 11
Soeties the acro recorder $ails...............................................................................................13
-he dispatch $raewor'............................................................................................................ 13
?ow the acro recorder uses the dispatch $raewor'..............................................................13
%ther options............................................................................................................................. 13
Macro organi@ation........................................................................................................................ 13
Ahere are acros storedB........................................................................................................ 1C
;porting acros....................................................................................................................... 1C
.ownloading acros to iport.................................................................................................. 19
?ow to run a acro........................................................................................................................ 19
-oolbar...................................................................................................................................... 1=
Menu ite.................................................................................................................................. 1=
Deyboard shortcuts.................................................................................................................... 1=
8!ent......................................................................................................................................... 1"
85tensions..................................................................................................................................... 11
Ariting acros without the recorder...............................................................................................11
+inding ore in$oration............................................................................................................... 13
;ncluded aterial....................................................................................................................... 13
%nline resources....................................................................................................................... 13
<rinted and e:oo' aterials...................................................................................................... 13
Getting Started with Macros 3
"our first macros
* macro is a sa(ed se8uence o commands or +eystro+es that are stored or later use. *n e0ample
o a simple macro is one that 9types: your address. The $ibre6ice macro language is (ery
le0ible' allowing automation o both simple and comple0 tas+s. /acros are especially useul to
repeat a tas+ the same way o(er and o(er again.
$ibre6ice macros are usually written in a language called $ibre6ice 5asic' or ;ust abbre(iated
5asic. *lthough you can learn 5asic and write macros' there is a steep learning cur(e to writing
macros rom scratch. The usual methods or a beginner are to add macros that someone else has
written and to use the built<in macro recorder' which records your +eystro+es and sa(es them or
use.
=n $ibre6ice recording o macros is currently classiied as an 9e0perimental %unstable&: eature. To
enable macro recording' use Tools ! Options ! ibreOffice ! #eneral and select the $nable
e%perimental &unstable' features option.
+igure 1: 8nable acros in the %ptions dialog.
/ost tas+s in $ibre6ice are accomplished by 9dispatching a command: %sending a command&'
which is intercepted and used. The macro recorder wor+s by recording the commands that are
dispatched %see 9The dispatch ramewor+: on page 1)&.
Adding an e%isting macro
The irst step in learning macro programming is to ind and use e0isting macros. This section
assumes that you ha(e a macro that you want to use> the macro may be in an email' on a web
page' or e(en in a boo+. -or this e0ample' use the macro in $isting 1.
/isting 1: Siple acro that says hello.
Sub HelloMacro
Print "Hello"
End Sub
3 Getting Started with Macros
You must create a library and module to contain your macro> this is co(ered in 9/acro
organi?ation: on page 14. "se these steps to create a library to contain your macro1
1& "se Tools Macros Organi(e Macros ibreOffice )asic to open the /acro dialog
%see -igure 2 and -igure @&.
2& Clic+ 6rgani?er to open the 5asic /acro 6rgani?er dialog %see -igure A&.
)& Select the /ibraries tab.
4& Set the /ocation to My Macros E .ialogs' which is the deault.
B& Clic+ New to open the !ew $ibrary dialog. Cnter a library name such as 9Test$ibrary: and
clic+ O*.
D& Select the Modules tab.
@& =n the Module list' e0pand My Macros and select Test$ibrary. * module named /odule1
already e0ists and can contain your macro. You can clic+ New to create another module in
Test$ibrary.
A& Select the /odule1' or the new module that you created' and clic+ $dit to open the
=ntegrated Eebugging Cn(ironment %=EC&.
F& The =EC is a te0t editor or macros that allows you to edit and create macros. Copy the
macro into the =EC.
3hen a new module is created' it contains a comment and an empty macro named /ain' that
does nothing.
/isting 1: Contents o$ Module1 a$ter it is created.
REM ***** BASIC *****
Sub Main
End Sub
*dd the new macro either beore Sub /ain or ater Cnd Sub. =n $isting )' the new macro has been
added beore Sub /ain.
/isting 3: Module1 a$ter adding the new acro.
REM ***** BASIC *****
Sub HelloMacro
Print "Hello"
End Sub
Sub Main
End Sub
Clic+ the ,un 5asic button in the toolbar' or press +,' to run the irst macro in the module. "se
the /acro dialog' opened using the Select macro button or Tools Macros Organi(e
Macros ibreOffice )asic' to select and run any macro in the module.
Creating a simple macro
=magine repeatedly entering simple inormation. *lthough you can store the inormation in the
clipboard' i you use the clipboard or something else' the contents are changed. Storing the
contents as a macro is a simple solution. %=n some simple cases' including the e0ample used here'
a better solution is to use *utoTe0t.&
2our $irst acros ,
1& "se Tools Macros +ecord Macro to start recording a macro.
* small window is displayed so you +now that $ibre6ice is recording.
2& Type the desired inormation or perorm an appropriate series o
operations. =n this case' = typed the name' 4ndrew <itonya'.
)& Clic+ the ,top +ecording button to stop recording' sa(e the macro' and display the
$ibre6ice 5asic /acros dialog.
+igure 1: /ibre%$$ice Macro %rgani@er dialogF Ariter odule selected
4& 5e certain to open the library container named My Macros. -ind the library named
Standard under /y /acros. 5e warned' e!ery library container has a library named
Standard. Select the Standard library and clic+ New Module to create a new module to
contain the macro.
B& The deault module name is /odule1. Type a descripti(e name and clic+ O* to create the
module. The $ibre6ice 5asic /acros dialog is displayed again' showing the new module.
+igure 3: Gi!e your odule a eaning$ul nae
D& 2ighlight the newly created module. =n the upper let corner' type the macro name to use'
such as 9Cnter/yname:' and then clic+ ,ave to sa(e the macro.
= you ollowed all o the steps' the Standard library now contains a module named ,ecorded'
which contains the Cnter/y!ame macro' as shown in -igure 4.
Note
3hen $ibre6ice creates a new module' it automatically adds the macro named
/ain.
C Getting Started with Macros
Library Containers
Macros
Libraries
Modules
+unning the macro
"se Tools Macros +un Macro to open the /acro Selector dialog. Select the newly created
macro and clic+ +un.
+igure 3: Select a acro and clic' Run
There are other methods to run a macro. -or e0ample' use Tools Macros Organi(e Macros
ibreOffice )asic to open the macro organi?er' which contains a +un button as well. *nother
method is to use the macro organi?er> the dialog usually opens aster' but the selection process
may be slightly slower.
-iewing and editing the macro
You can (iew and edit the macro that was ;ust created. "se Tools Macros Organi(e Macros
ibreOffice )asic to open the $ibre6ice 5asic /acros dialog %see -igure 4&. Select the new
macro and clic+ $dit to open the macro in the 5asic =EC %=ntegrated Ee(elopment Cn(ironment&.
/isting 3: Generated G8nterMynaeH acro.
REM ***** BASIC *****
Sub Main
End Sub
sub EnterMyName
rem -------------------------------------------------------------
rem define variables
dim document as object
dim dispatcer as object
rem -------------------------------------------------------------
rem !et access to te document
document " #isComponent$CurrentController$%rame
dispatcer " create&noService'(com$sun$star$frame$)ispatc*elper(+
2our $irst acros 6
rem -------------------------------------------------------------
dim ar!s,'-+ as ne. com$sun$star$beans$/roperty0alue
ar!s,'-+$Name " (#e1t(
ar!s,'-+$0alue " (Andre. /itonya2(
dispatcer$e1ecute)ispatc'document3 ($uno4Insert#e1t(3 ((3 -3 ar!s,'++
end sub
The macro in $isting 4 is not as complicated as it irst appears. $earning a ew things helps
signiicantly in understanding the generated macros. The discussion starts with eatures near the
top o the macro listing and describes them. = you li+e to a(oid details' then simply change the te0t
9*ndrew #itonya+: in the macro abo(e to what you want to insert at the current cursor position.
Comments start with REM
The +eyword ,C/' short or rear'' starts a macro comment. *ll te0t ater ,C/ %on the same line&
is ignored. *s a short cut' the single 8uote character can also be used to start a comment.
Tip
$ibre6ice 5asic is not case<sensiti(e or +eywords' so ,C/' ,em' and rem all start
a comment. = you use symbolic constants deined by the *#=' it is saer to assume
that the names are case<sensiti(eGsymbolic constants are an ad(anced topic not
usually needed by people that use the macro recorder.
Defining subroutines with S!
=ndi(idual macros are stored in subroutines deined with the +eyword S"5. The end o a subroutine
is indicated by the words C!E S"5. The code starts by deining the subroutine named /ain' which
is empty and does nothing. The ne0t subroutine' Cnter/y!ame' contains the generated code.
Tip
$ibre6ice always creates an empty subroutine named /ain when it creates a
module.
There are ad(anced topics that are beyond the scope o this document' but +nowing about them
might be o interest1
You can write a macro so that (alues can be passed to the subroutine. The (alues are
called arguments. ,ecorded macros do not accept arguments.
*nother +ind o subroutine is called a unction. * unction is a subroutine that returns a
(alue. The +eyword -"!CT=6! is used rather than S"5 to deine a unction. Generated
macros are always o type S"5.
Defining variables using D"M
You can write inormation on a piece o paper so that you can loo+ at it later. * (ariable' li+e a piece
o paper' contains inormation that can be changed and read. The E=/ statement is similar to
setting aside a piece o paper to be used to store a message or note.
The Cnter/y!ame macro deines the (ariables docuent and dispatcher as type obIect. 6ther
common (ariable types include string' integer' and date. * third (ariable' named args1F is an array
o property (alues. * (ariable o type array allows a single (ariable to contain multiple (alues'
similar to storing multiple pages in a single boo+. Halues in an array are usually numbered starting
rom ?ero. The number in the parentheses indicates the highest usable number to access a
storage location. =n this e0ample' there is only one (alue' and it is numbered ?ero.
9 Getting Started with Macros
#ulling the macro together
The ollowing details are (ery complete> it is not important to understand all o the details. The irst
line deines the start o the macro.
sub EnterMyName
Eeclare two (ariables1
dim document as object
dim dispatcer as object
ThisComponent reers to the current document.
The CurrentController property o a document reers to a ser(ice that 9controls: the document. -or
e0ample' when you type' it is the current controller that notices. The current controller then
dispatches the changes to the documentIs rame.
The -rame property o a controller returns a main rame or a document. Thereore' the (ariable
named docuent reers to a documentIs rame' which recei(es dispatched commands.
document " #isComponent$CurrentController$%rame
/ost tas+s in $ibre6ice are accomplished by dispatching a command. $ibre6ice includes a
dispatch helper ser(ice' which does most o the wor+ to use dispatches in macros. The method
Create"noSer(ice accepts the name o a ser(ice and it tries to create an instance o that ser(ice.
6n completion' the dispatcher (ariable contains a reerence to a Eispatch2elper.
dispatcer " create&noService'(com$sun$star$frame$)ispatc*elper(+
Eeclare an array o properties. Cach property has a name and a (alue. =n other words' it is a
name/(alue pair. The created array has one property at inde0 ?ero.
dim ar!s,'-+ as ne. com$sun$star$beans$/roperty0alue
Gi(e the property the name 9Te0t: and the (alue 9*ndrew #itonya+:' which is the te0t that is
inserted when the macro is run.
ar!s,'-+$Name " (#e1t(
ar!s,'-+$0alue " (Andre. /itonya2(
This is where the magic happens. The dispatch helper sends a dispatch to the documentIs rame
%stored in the (ariable named document& with the command .uno:InsertText. The ne0t two
arguments' $rae nae and search $lags' are beyond the scope o this document. The last
argument is the array o property (alues to be used while e0ecuting the command =nsertTe0t.
dispatcer$e1ecute)ispatc'document3 ($uno4Insert#e1t(3 ((3 -3 ar!s,'++
-inally' the end o the subroutine.
end sub
Creating a macro
3hen creating a macro' it is important to as+ two 8uestions beore recording1
1& Can the tas+ be written as a simple set o commandsJ
2& Can the steps be arranged such that the last command lea(es the cursor ready or the ne0t
commandJ
A complicated e%ample
= re8uently copy rows and columns o data rom a web site and ormat them as a table in a te0t
document. -irst' = copy the table rom the web site to the clipboard. To a(oid strange ormatting and
onts' = paste the te0t into a 3riter document as unormatted te0t. = reormat the te0t with tabs
between columns so that = can use Table Convert Te%t to Table to con(ert to a table.
Creating a acro =
= inspect the te0t to see i = can record a macro to ormat the te0t %remember the two 8uestions that
= as+&. *s an e0ample' = copied the -ont3eight constants group rom the *#= web site. The irst
column indicates the constant name. Cach name is ollowed by a space and a tab.
E6!TK!63 The ont weight is not speciied/+nown.
T2=! speciies a B0L ont weight.
"$T,*$=G2T speciies a D0L ont weight.
$=G2T speciies a @BL ont weight.
SC/=$=G2T speciies a F0L ont weight.
!6,/*$ speciies a normal ont weight.
SC/=56$E speciies a 110L ont weight.
56$E speciies a 1B0L ont weight.
"$T,*56$E speciies a 1@BL ont weight.
5$*CK speciies a 200L ont weight.
= want the irst column to contain the numeric (alue' the second column the name' and the third
column the description. The desired wor+ is easily accomplished or e(ery row e0cept or
E6!TK!63 and !6,/*$' which do not contain a numeric (alueGbut = +now that the (alues are
0 and 100' so = will enter those manually.
The data can be cleaned in multiple waysGall o them easy. The irst e0ample uses +eystro+es
that assume the cursor is at the start o the line with the te0t T2=!.
1& "se Tools Macros +ecord Macro to start recording.
2& #ress Ctrl(Right 4rrow to mo(e the cursor to the start o 9speciies:.
)& #ress :ac'space twice to remo(e the tab and the space.
4& #ress -ab to add the tab without the space ater the constant name.
B& #ress .elete to delete the lower case s and then press S to add an upper case S.
D& #ress Ctrl(Right 4rrow twice to mo(e the cursor to the start o the number.
@& #ress Ctrl(Shi$t(Right 4rrow to select and mo(e the cursor beore the L sign.
A& #ress Ctrl(C to copy the selected te0t to the clipboard.
F& #ress 8nd to mo(e the cursor to the end o the line.
10& #ress :ac'space twice to remo(e the two trailing spaces.
11& #ress ?oe to mo(e the cursor to the start o the line.
12& #ress Ctrl(7 to paste the selected number to the start o the line.
1)& #asting the (alue also pasted an e0tra space' so press :ac'space to remo(e the e0tra
space.
14& #ress -ab to insert a tab between the number and the name.
1B& #ress ?oe to mo(e to the start o the line.
1D& #ress down arrow to mo(e to the ne0t line.
1@& Stop recording the macro and sa(e the macro.
=t ta+es much longer to read and write the steps than to record the macro. 3or+ slowly and thin+
about the steps as you do them. 3ith practice this becomes second nature.
The generated macro has been modiied to contain the step number in the comments to match the
code to the step abo(e.
1" Getting Started with Macros
/isting ,: Copy the nueric !alue to the start o$ the colun.
sub CopyNum#oCol,
rem -------------------------------------------------------------
rem define variables
dim document as object
dim dispatcer as object
rem -------------------------------------------------------------
rem !et access to te document
document " #isComponent$CurrentController$%rame
dispatcer " create&noService'(com$sun$star$frame$)ispatc*elper(+
rem '5+ /ress Ctrl+Right Arrow to move te cursor to te start of 6specifies7$
dispatcer$e1ecute)ispatc'document3 ($uno48o#oNe1t9ord(3 ((3 -3 Array'++
rem ':+ /ress Backspace t.ice to remove te tab and te space$
dispatcer$e1ecute)ispatc'document3 ($uno4S.Bac2space(3 ((3 -3 Array'++
rem -------------------------------------------------------------
dispatcer$e1ecute)ispatc'document3 ($uno4S.Bac2space(3 ((3 -3 Array'++
rem ';+ /ress Tab to add te tab .itout te space after te constant name$
dim ar!s;'-+ as ne. com$sun$star$beans$/roperty0alue
ar!s;'-+$Name " (#e1t(
ar!s;'-+$0alue " C*R<'=+
dispatcer$e1ecute)ispatc'document3 ($uno4Insert#e1t(3 ((3 -3 ar!s;'++
rem '>+ /ress Delete to delete te lo.er case s $$$$
dispatcer$e1ecute)ispatc'document3 ($uno4)elete(3 ((3 -3 Array'++
rem '>+ $$$ and ten press S to add an upper case S$
dim ar!s?'-+ as ne. com$sun$star$beans$/roperty0alue
ar!s?'-+$Name " (#e1t(
ar!s?'-+$0alue " (S(
dispatcer$e1ecute)ispatc'document3 ($uno4Insert#e1t(3 ((3 -3 ar!s?'++
rem '?+ /ress Ctrl+Right Arrow t.ice to move te cursor to te number$
dispatcer$e1ecute)ispatc'document3 ($uno48o#oNe1t9ord(3 ((3 -3 Array'++
rem -------------------------------------------------------------
dispatcer$e1ecute)ispatc'document3 ($uno48o#oNe1t9ord(3 ((3 -3 Array'++
rem '@+ /ress Ctrl+Shift+Right Arrow to select te number$
dispatcer$e1ecute)ispatc'document3 ($uno49ordRi!tSel(3 ((3 -3 Array'++
rem 'A+ /ress Ctrl+C to copy te selected te1t to te clipboard$
dispatcer$e1ecute)ispatc'document3 ($uno4Copy(3 ((3 -3 Array'++
rem '=+ /ress End to move te cursor to te end of te line$
dispatcer$e1ecute)ispatc'document3 ($uno48o#oEndBfCine(3 ((3 -3 Array'++
rem ',-+ /ress Backspace t.ice to remove te t.o trailin! spaces$
dispatcer$e1ecute)ispatc'document3 ($uno4S.Bac2space(3 ((3 -3 Array'++
rem -------------------------------------------------------------
Creating a acro 11
dispatcer$e1ecute)ispatc'document3 ($uno4S.Bac2space(3 ((3 -3 Array'++
rem ',,+ /ress Home to move te cursor to te start of te line$
dispatcer$e1ecute)ispatc'document3 ($uno48o#oStartBfCine(3 ((3 -3 Array'++
rem ',5+ /ress Ctrl+V to paste te selected number to te start of te line$
dispatcer$e1ecute)ispatc'document3 ($uno4/aste(3 ((3 -3 Array'++
rem ',:+ /ress Backspace to remove te e1tra space$
dispatcer$e1ecute)ispatc'document3 ($uno4S.Bac2space(3 ((3 -3 Array'++
rem ',;+ /ress Tab to insert a tab bet.een te number and te name$
dim ar!s,@'-+ as ne. com$sun$star$beans$/roperty0alue
ar!s,@'-+$Name " (#e1t(
ar!s,@'-+$0alue " C*R<'=+
dispatcer$e1ecute)ispatc'document3 ($uno4Insert#e1t(3 ((3 -3 ar!s,@'++
rem ',>+ /ress Home to move to te start of te line$
dispatcer$e1ecute)ispatc'document3 ($uno48o#oStartBfCine(3 ((3 -3 Array'++
rem ',?+ /ress Down Arrow to move to te ne1t line$
dim ar!s,=',+ as ne. com$sun$star$beans$/roperty0alue
ar!s,='-+$Name " (Count(
ar!s,='-+$0alue " ,
ar!s,=',+$Name " (Select(
ar!s,=',+$0alue " false
dispatcer$e1ecute)ispatc'document3 ($uno48o)o.n(3 ((3 -3 ar!s,='++
end sub
Cursor mo(ements are used or all operations %as opposed to searching&. = run on the
E6!TK!63 line' the word weight is mo(ed to the ront o the line' and the irst 9The: is changed
to 9She:. This is not perect' but = should not ha(e run the macro on the lines that did not ha(e the
proper ormat> = need to do these manually.
+unning the macro .uickly
=t is tedious to repeatedly run the macro using Tools Macros +un Macro %see -igure 4&. The
macro can be run rom the =EC. "se Tools Macros Organi(e Macros ibreOffice )asic to
open the 5asic /acro dialog. Select your macro and clic+ $dit to open the macro in the =EC.
The =EC has a +un )asic icon in the toolbar that runs the irst macro in the =EC. "nless you
change the irst macro' it is the empty macro named /ain. /odiy /ain so that it reads as shown in
$isting D.
/isting C: Modi$y Main to call Copy0u-oCol1.
Sub Main
CopyNum#oCol,
End Sub
!ow' you can run Copy!umToCol1 by repeatedly clic+ing the +un )asic icon in the toolbar o the
=EC. This is (ery ast and easy' especially or temporary macros that will be used a ew times and
then discarded.
11 Getting Started with Macros
,ometimes the macro recorder fails
"nderstanding the $ibre6ice internals helps to understand how and why the macro recorder
re8uently ails. The primary oender is related to the dispatch ramewor+ and its relationship to the
macro recorder.
The dispatch framework
The purpose o the dispatch ramewor+ is to pro(ide uniorm access to components %documents&
or commands that usually correspond to menu items. = can use File ,ave rom the menu' the
shortcut +eys Ctrl(S' or clic+ on the ,ave toolbar icon. *ll o these commands are translated into
the same 9dispatch command:.
The dispatch ramewor+ can also be used to send 9commands: bac+ to the "= %"ser =nterace&. -or
e0ample' ater sa(ing the document' the -ile Sa(e command is disabled. *s soon as the document
has been changed' the -ile Sa(e command is enabled.
= we see a dispatch command' it is te0t such as .uno1=nsert6b;ect or .uno1GoToStart6$ine. The
command is sent to the documentIs rame' and the rame passes on the command until an ob;ect
is ound that can handle the command.
/ow the macro recorder uses the dispatch framework
The macro recorder records the generated dispatches. The recorder is relati(ely simple to
implement and the same commands that are issued are recorded or later use. The problem is that
not all dispatched commands are complete. -or e0ample' inserting an ob;ect generates the
ollowing code1
dispatcer$e1ecute)ispatc'document3 ($uno4InsertBbject(3 ((3 -3 Array'++
=t is not possible to speciy what +ind o ob;ect to create or insert. = an ob;ect is inserted rom a ile'
you cannot speciy which ile to insert.
= recorded a macro and used Tools Options to open and modiy coniguration items. The
generated macro does not record any coniguration changes> in act' the generated code is
commented so it will not e(en be run.
rem dispatcer$e1ecute)ispatc'document3
($uno4Bptions#ree)ialo!(3 ((3 -3 Array'++
= a dialog is opened' the command to open the dialog is li+ely to be generated. *ny wor+ done
inside the dialog is not usually recorded. C0amples include macro organi?ation dialogs' inserting
special characters' and similar types o dialogs. 6ther possible problems using the macro recorder
include things such as inserting a ormula' setting user data' setting ilters in Calc' actions in
database orms' and e0porting a document to an encrypted #E- ile. You ne(er +now or certain
what will wor+ unless you try it' howe(er. The actions rom the search dialog are properly captured'
or e0ample.
Other options
3hen the macro recorder is not able to sol(e a speciic problem' the usual solution is to write code
using the $ibre6ice ob;ects. "nortunately' there is a steep learning cur(e or the ob;ects. =t is
usually best to start with simple e0amples and then branch out slowly as you learn more. $earning
to read generated macros is a good place to start.
= you record Calc macros' and the recorder can correctly generate a macro' there is an add<in
created by #aolo /anto(ani' which con(erts Calc macros when they are recorded. The inal code
manipulates $ibre6ice ob;ects rather than generating dispatches. This can be (ery useul or
learning the ob;ect model.
Soeties the acro recorder $ails 13
You can download the macro recorder rom #aoloIs web site directly1
http://www.paolo&anto!ani.org/downloads/.ispatch-o4piRecorder/
Macro organi(ation
=n $ibre6ice' macros are grouped in modules' modules are grouped in libraries' and libraries are
grouped in library containers. * library is usually used as a ma;or grouping or either an entire
category o macros' or or an entire application. /odules usually split unctionality' such as user
interaction and calculations. =ndi(idual macros are subroutines and unctions.
+igure ,: Macro /ibrary hierarchy
* computer scientist would use -igure D to precisely describe the situation. The te0t 91..M: means
one or more' and 90..M: means ?ero or more. The blac+ triangle means composed o or contains.
* library container contains one or more libraries' and each library is contained in one
library container.
* library contains ?ero or more modules' and each module is contained in one library.
* module contains ?ero or more macros' and each macro is contained in one module.
+igure C: Macro /ibrary hierarchy
"se Tools Macros Organi(e Macros ibreOffice )asic to open the $ibre6ice 5asic
/acros dialog %see -igure @&. *ll a(ailable library containers are shown in the Macro $ro list.
C(ery document is a library container' capable o containing multiple libraries. The application itsel
acts as two library containers' one container or macros distributed with $ibre6ice called
$ibre6ice /acros' and one container or personal macros called /y /acros. *s shown in -igure
@' only two documents are currently open.
13 Getting Started with Macros
+igure 6: /ibrary containers are shown on the le$t
The $ibre6ice /acros are stored with the application runtime code' which may not be editable to
you unless you are an administrator. This is ;ust as well since these macros should not be changed
and you should not store your own macros in the $ibre6ice container.
"nless your macros are applicable to a single document' and only to a single document' your
macros will probably be stored in the /y /acros container. The /y /acros container is stored in
your user area or home directory.
= a macro is contained in a document' then a recorded macro will attempt to wor+ on that
document> primarily because it uses 9ThisComponent: or its actions.
C(ery library container contains a library named Standard. =t is better to create your own libraries
with meaningul names than to use the Standard library. !ot only are meaningul names easier to
manage' but they can also be imported into other library containers whereas the Standard library
cannot.
Caution $ibre6ice allows you to import libraries into a library container' but it will not allow
you to o(erwrite the library named Standard. Thereore' i you store your macros in
the Standard library' you cannot import them into another library container.
.ust as it ma+es good sense to gi(e your libraries meaningul names' it is prudent to use
meaningul names or your modules. 5y deault' $ibre6ice uses names such as /odule1. -eel
ree to use your own meaningul name.
*s you create your macros' you must decide where to store them. Storing a macro in a document
is useul i the document will be shared and you want the macro to be included with the document.
/acros stored in the application library container named /y /acros' howe(er' are globally
a(ailable to all documents.
/acros are not a(ailable until the library that contains them is loaded. The Standard library and
Template library' howe(er' are automatically loaded. * loaded library is displayed dierently rom a
library that is not loaded. To load the library and the modules it contains' double<clic+ on the library.
Macro organi@ation 1,
0here are macros stored1
$ibre6ice stores user<speciic data in a directory under the userIs home directory. The location is
operating system speciic. "se Tools Options ibreOffice Paths to (iew where other
coniguration data is stored. 6n 3indows N#' this is C:\Documents and Settings\<name>\
Application Data. "ser macros are stored in Libre!!ice\"\user\basic. Cach library is
stored in its own directory o the basic directory.
=t is not important to understand where macros are stored or casual use. = you +now where they
are stored' howe(er' you can create a bac+up' share your macros' or inspect them i there is an
error.
"se Tools Macros Organi(e 2ialogs to open the $ibre6ice /acro 6rgani?er dialog. *nother
common way to open this dialog is to use Tools Macros Organi(e Macros ibreOffice
)asic to open the $ibre6ice /acros dialog and then clic+ the Organi(er button.
+igure 9: -he acro organi@er dialog
3mporting macros
The $ibre6ice /acro 6rgani?er dialog pro(ides unctionality to create' delete' and rename
libraries' modules' and dialogs. Select the library container to use and then clic+ the 3mport button
to import macro libraries %see -igure F&.
Note
You cannot import the library named Standard.
Tip
6n $inu0' the $ibre6ice<speciic iles are stored under the userOs home directory in
a directory whose name begins with a period. Eirectories and iles with names
beginning with a period are not shown in a normal selection dialog. To open the
directory' either na(igate to the home directory' enter the name .libreoiceP)' and
then clic+ Open or press Ctrl&? to show hidden olders and iles and na(igate as
usual. This will open the directory' which is not initially shown.
1C Getting Started with Macros
+igure =: Select a acro library to iport
!a(igate to the directory containing the library to import. There are usually two iles rom which to
choose' dialog.0lb and script.0lb. =t does not matter which o these two iles you select> both will be
imported. Select a ile and clic+ Open to continue.
+igure 1": Choose library iport options
= the library already e0ists' it will not be replaced unless +eplace e%isting libraries is chec+ed. =
3nsert as reference is chec+ed' the library is reerenced in its current location' but you cannot edit
the library. = 3nsert as reference is not chec+ed' howe(er' the library is copied to the userIs macro
directory.
/acros can be stored in libraries inside $ibre6ice documents. Select a document rather than a
directory on dis+ %as shown in -igure F& to import libraries contained in a document.
Macro organi@ation 16
2ownloading macros to import
/acros are a(ailable or download. Some macros are contained in documents' some as regular
iles that you must select and import' and some as macro te0t that should be copied and pasted
into the 5asic =EC> use Tools Macros Organi(e Macros ibreOffice )asic to open the
$ibre6ice /acros dialog' choose the macro to edit' and then clic+ $dit to open the macro in the
5asic =EC.
Some macros are a(ailable as ree downloads on the =nternet %see Table 1&. 9*dding an e0isting
macro9 on page 4 describes how to add these macros to your macros library.
-able 1. <laces to $ind acro e5aples
Location Descri$tion
http://www.oooacros.org/ Collection o pac+aged macros now somewhat
dated.
http://www.pitonya'.org/oo.php ,eerence materials regarding macros.
http://www.pitonya'.org/database/ ,eerence materials regarding database macros.
http://de!elopent.openo$$ice.org/ $ots o lin+s to e(erything.
http://www.ooo$oru.org/ * orum' with many e0amples and help.
http://user.ser!ices.openo$$ice.org/ *nother orum' with many e0amples and help.
/ow to run a macro
* typical method to run a macro is as ollows1
1& "se Tools Macros +un Macro to open the /acro Selector dialog %see -igure 11&.
2& Select the library and module in the $ibrary list %let hand side&.
)& Select the macro in the /acro name list %right hand side&.
4& Clic+ +un to run the macro.
+igure 11: Use the Macro Selector dialog to run acros
19 Getting Started with Macros
*lthough you can use Tools Macros +un Macro to run all macros' this is not eicient or
re8uently run macros. * more common techni8ue is to assign a macro to a toolbar button' menu
item' +eyboard shortcut' or a button embedded in a document. 3hile choosing a method' it is also
good to as+ 8uestions such as1
Should the macro be a(ailable or only one document' or globally or all documentsJ
Eoes the macro pertain to a speciic document type' such as a Calc documentJ
2ow re8uently will the macro be usedJ
The answers will determine where to store the macro and how to ma+e it a(ailable. -or e0ample'
you will probably not add a rarely used macro to a toolbar. To help determine your choices' see
Table 2.
-able 1. Methods $or starting a acro
%&$e Libre'ffice Document %&$e Document
Toolbar !o Yes Yes
/enu !o Yes Yes
Shortcut Yes Yes !o
C(ent Yes !o Yes
To add a menu item' +eyboard shortcut' or toolbar icon that calls a macro' use the Customi?e
dialog %see -igure 1)&. 6pen this dialog in either o these ways1
Choose Tools Customi(e rom the main menu bar.
Cach toolbar has an icon that opens a menu> choose the Customi(e Toolbar option.
Tip
Complete co(erage o the Customi?e dialog is beyond the scope o this document.
Clic+ the /elp button to access the help pages included with $ibre6ice.
The Customi?e dialog contains tabs to conigure menus' +eyboard bindings' toolbars' and e(ents.
Toolbar
/acros can be added to toolbars. -or more about modiying toolbars' see Chapter 14' Customi?ing
$ibre6ice.
Menu item
"se Tools Customi(e to open the Customi?e dialog' and select the /enus tab. You can modiy
an e0isting menu' or create new menus that call macros. -or more about modiying menus' see
Chapter 14.
*eyboard shortcuts
"se Tools Customi(e to open the Customi?e dialog' and select the Keyboard tab. *ssigning
+eyboard shortcuts is discussed in Chapter 14.
?ow to run a acro 1=
+igure 11: /ibre%$$ice Custoi@e dialog
$vent
=n $ibre6ice' when something happens' we say that an e(ent occurred. -or e0ample' a document
was opened' a +ey was pressed' or the mouse mo(ed. $ibre6ice allows e(ents to cause a macro
to be called> the macro is then called an e(ent handler. -ull co(erage o e(ent handlers is well
beyond the scope o this document' but a little +nowledge can accomplish much.
Caution
5e careul when you conigure an e(ent handler. -or e0ample' assume that you
write an e(ent handler that is called e(ery time that a +ey is pressed' but you ma+e a
mista+e so the e(ent is not properly handled. 6ne possible result is that your e(ent
handler will consume all +ey presses' orcing you to orcibly terminate $ibre6ice.
"se Tools Customi(e to open the Customi?e dialog' and select the C(ents tab %see -igure 1)&.
The e(ents in the Customi?e dialog are related to the entire application and speciic documents.
"se the Sa(e =n bo0 to choose $ibre6ice' or a speciic document.
1" Getting Started with Macros
+igure 13: 4ssign acro to an application le!el e!ent
* common use is to assign the 6pen Eocument e(ent to call a speciic macro. The macro then
perorms certain setup tas+s or the document. Select the desired e(ent and clic+ the Macro button
to open the /acro Selector dialog %see -igure 14&.
+igure 13: 4ssign acro to the docuent open e!ent
?ow to run a acro 11
Select the desired macro and clic+ O* to assign the macro to the e(ent. The C(ents tab shows
that the e(ent has been assigned to a macro %see -igure 1B&. 3hen the document opens' the
#rint2ello macro is run.
/any ob;ects in a document can be set to call macros when e(ents occur. The most common
usage is to add a control' such as a button' into a document. C(en double<clic+ing on a graphic
opens a dialog with a /acros tab that allows you to assign a macro to an e(ent.
+igure 1,: ?elloMacro is assigned to the %pen .ocuent e!ent
$%tensions
*n e0tension is a pac+age that can be installed into $ibre6ice to add new unctionality.
C0tensions can be written in almost any programming language and may be simple or
sophisticated. C0tensions can be grouped into types1
Calc *dd<=ns' which pro(ide new unctionality or Calc' including new unctions that act li+e
normal built<in unctions
!ew components and unctionality' which normally include some le(el o "= integration
such as new menus or toolbars
Eata pilots that are used directly in Calc
Chart *dd<=ns with new chart types
$inguistic components such as spell chec+ers
Eocument templates and images
*lthough indi(idual e0tensions can be ound in dierent places' there is currently an e0tension
repository at1 htt$(//extensions)*libreoffice*org/ and some documentation at
htt$(//libre$lanet*org/wi+i/,rou$('$en'fficeExtensions/List
-or more about obtaining and installing e0tensions' see Chapter 14' Customi?ing $ibre6ice.
0riting macros without the recorder
The e0amples co(ered in this chapter are created using the macro recorder and the dispatcher.
You can also write macros that directly access the ob;ects that comprise $ibre6ice. =n other
words' you can directly manipulate a document.
Eirectly manipulating $ibre6iceOs internal ob;ects is an ad(anced topic that is beyond the scope o
this chapter. * simple e0ample' howe(er' demonstrates how this wor+s.
/isting 6: 4ppend the te5t G?elloH to the current docuent.
Sub Append*ello
)im o)oc
)im s#e1tService<
)im oCurs
11 Getting Started with Macros

REM #isComponent refers to te currently active document$
o)oc " #isComponent
REM 0erify tat tis is a te1t document
s#e1tService " (com$sun$star$te1t$#e1t)ocument(
If NB# o)oc$supportsService's#e1tService+ #en
Ms!Bo1 (#is macro only .or2s .it a te1t document(
E1it Sub
End If

REM 8et te vie. cursor from te current controller$
oCurs " o)oc$currentController$!et0ie.Cursor'+

REM Move te cursor to te end of te document
oCurs$!otoEnd'%alse+

REM Insert te1t (*ello( at te end of te document
oCurs$#e1t$insertStrin!'oCurs3 (*ello(3 %alse+
End Sub
Finding more information
!umerous resources are a(ailable that pro(ide help with writing macros. "se /elp ibreOffice
/elp to open the $ibre6ice help pages. The upper let corner o the $ibre6ice help system
contains a drop<down list that determines which help set is displayed. To (iew the help or 5asic'
choose /ibre%$$ice :asic rom this list.
3ncluded material
/any e0cellent macros are included with $ibre6ice. "se Tools Macros Organi(e Macros
ibreOffice )asic to open the /acro dialog. C0pand the Tools library in the $ibre6ice library
container. =nspect the Eebug moduleGsome good e0amples include 3ritedbg=no%document& and
printdbg=no%sheet&.
Online resources
The ollowing lin+s and reerences contain inormation regarding macro programming1
http://user.ser!ices.openo$$ice.org/ %66o orums' well supported> (olunteers answer 8uestions
about $ibre6ice as well&
http://api.openo$$ice.org/docs/coon/re$/co/sun/star/odule&i5.htl %oicial =E$ reerence> here
youOll ind almost e(ery command with a description&
http://wi'i.ser!ices.openo$$ice.org/wi'i/.ocuentation/:4S;CJGuide %oicial 6pen6ice.org
5*S=C #rogramming Guide&. *lso a(ailable in .6ET ormat rom
http://wi'i.docuent$oundation.org/.ocuentationK%therJ.ocuentationJandJResources
http://wi'i.ser!ices.openo$$ice.org/wi'i/.ocuentation/.e!Guide %oicial 6pen6ice.org
Ee(elopers Guide> contains a detailed e0planation&. *lso a(ailable in .6ET ormat rom
http://wi'i.docuent$oundation.org/.ocuentationK%therJ.ocuentationJandJResources
http://www.pitonya'.org/oo.php %*ndrew #itonya+Is macro page&
http://www.pitonya'.org/4ndrewMacro.odt %numerous e0amples o wor+ing macros&
http://www.pitonya'.org/%%M8J3J".odt %*ndrew #itonya+Is boo+ on macros&
http://www.pitonya'.org/database/ %numerous macro e0amples using 5ase&
+inding ore in$oration 13
http://docs.sun.co/app/docs/doc/91=&"33= %SunIs boo+ on macro programmingG(ery well written
and laid out> the 66o 5*S=C #rogramming Guide and the 66o Ee(elopers Guide are deri(ed
rom this boo+&
Printed and e)ook materials
There are currently no boo+s speciic to $ibre6ice macros which are a(ailable or download.
-or 6pen6ice.org the ollowing boo+s are a(ailable or purchase in both printed and e5oo+ orm
rom their publishers.
Er. /ar+ *le0ander 5ainIs /earn %pen%$$ice.org Spreadsheet Macro <rograing.
See http://www.pac'tpub.co/openo$$ice&ooobasic&calc&autoation/boo'.
,oberto 5enite?Os .atabase <rograing with %pen%$$ice.org :ase E :asic.
See http://www.lulu.co/product/paperbac'/database&prograing&with&openo$$iceorg&base&
basic/3,C9619
13 Getting Started with Macros

You might also like