Download as pdf or txt
Download as pdf or txt
You are on page 1of 22

Getting Started Guide

Chapter 13
Getting Started with Macros
Using the Macro Recorder and Beyond
Copyright
This document is Copyright 20102013 by its contributors as listed below. You may distribute it
andor modi!y it under the terms o! either the G"# General $ublic %icense
&http'www.gnu.orglicensesgpl.html() *ersion 3 or later) or the Creati*e Commons +ttribution
%icense &http'creati*ecommons.orglicensesby3.0() *ersion 3.0 or later.
+ll trademar,s within this guide belong to their legitimate owners.
Contributors
-on .aile /r. 0artin .o1 +ndrew $itonya,
$eter Scho!ield
Feedback
$lease direct any comments or suggestions about this document to'
documentation2global.libreo!!ice.org
Acknowledgments
This chapter is based on Chapter 13 o! Getting Started with OpenOffice.org 3.3. The contributors
to that chapter are'
+ndrew $itonya, /ean 3ollis 4eber
Publication date and software version
$ublished 10 .ebruary 2013. 5ased on %ibre6!!ice 7.0.
Note for Mac users
Some ,eystro,es and menu items are di!!erent on a 0ac !rom those used in 4indows and %inu1.
The table below gi*es some common substitutions !or the instructions in this chapter. .or a more
detailed list) see the application 3elp.
Windows or Linux Mac equivalent Effect
Tools > ptions
menu selection
!ibreffice > Preferences +ccess setup options
Right-clic Control!clic andor right-clic
depending on computer setup
6pens a conte1t menu
Ctrl "Control# z "Co$$and# #sed with other ,eys
%& Shift8z8%& 6pens the "a*igator
%11 z8' 6pens the Styles and .ormatting window
(oc)$entation for *i+reOffice is a,aila+le at http-..www.li+reoffice.org.get-help.doc)$entation
Contents
Copyright"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" #
Contributors................................................................................................................................. 2
.eedbac,..................................................................................................................................... 2
+c,nowledgments........................................................................................................................ 2
$ublication date and so!tware *ersion......................................................................................... 2
Note for Mac users"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""#
$ntroduction"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" %
&our first macros""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""%
+dding a macro............................................................................................................................ 7
-ecording a macro...................................................................................................................... 9
-unning a macro......................................................................................................................... :
;iewing and editing macros......................................................................................................... :
-<0 comments....................................................................................................................... =
>e!ining subroutines with S#5................................................................................................ =
>e!ining *ariables using >im................................................................................................... ?
<1plaining macro code............................................................................................................ ?
Creating a macro""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""'(
+ more complicated e1ample o! a macro................................................................................... 10
-unning a macro @uic,ly............................................................................................................ 13
Macro recorder failures""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" ')
>ispatch !ramewor,................................................................................................................... 13
3ow the macro recorder uses the dispatch !ramewor,.............................................................. 17
6ther options............................................................................................................................. 17
Macro organi*ation"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" '%
4here are macros storedA........................................................................................................ 1B
Cmporting macros....................................................................................................................... 19
>ownloading macros to import................................................................................................... 1:
+ow to run a macro""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""',
Toolbars) menu items and ,eyboard shortcuts........................................................................... 1=
<*ents........................................................................................................................................ 1?
-.tensions"""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" #(
/riting macros without the recorder""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" #'
Finding more information""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""""" #'
Cncluded material....................................................................................................................... 21
6nline resources........................................................................................................................ 22
$rinted and e5oo, materials...................................................................................................... 22
Getting Started with Macros 3
$ntroduction
+ macro is a sa*ed se@uence o! commands or ,eystro,es that are stored !or later use. +n e1ample
o! a simple macro is one that DtypesE your address. The %ibre6!!ice macro language is *ery
!le1ible) allowing automation o! both simple and comple1 tas,s. 0acros are *ery use!ul when you
ha*e to repeat the same tas, in the same way o*er and o*er again.
%ibre6!!ice macros are usually written in a language called %ibre6!!ice 5asic) sometimes
abbre*iated to 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 use macros that
someone else has written or use the builtFin macro recorder) which records ,eystro,es and sa*es
them !or use.
0ost tas,s in %ibre6!!ice are accomplished by Ddispatching a commandE &sending a command()
which is intercepted and used. The macro recorder wor,s by recording the commands that are
dispatched &see D>ispatch !ramewor,E on page 13(.
&our first macros
Adding a macro
The !irst step in learning macro programming is to !ind and use e1isting macros. This section
assumes that you ha*e a macro that you want to use) which may be in an email) on a web page) or
e*en in a boo,. .or this e1ample) the macro in %isting 1 is used. You must create a library and
module to contain your macroG see D0acro organiHationE on page 17 !or more in!ormation.
*isting 1- Si$ple $acro that says hello
Sub HelloMacro
Print "Hello"
End Sub
%ig)re 1- *i+reOffice Basic Macros dialog
/ Getting Started with Macros
%ig)re 0- *i+reOffice Basic Macro Organi1er dialog
%ig)re 3- 2ntegrated (e+)gging 3n,iron$ent dialog
#se the !ollowing steps to create a library to contain your macro'
1( #se Tools > Macros > rgani*e Macros > !ibreffice 0asic to open the %ibre6!!ice
5asic 0acro dialog &.igure 1(.
2( Clic, rgani*er to open the 5asic 0acro 6rganiHer dialog &.igure 2( and select the
*i+raries tab.
3( Set the *ocation to My Macros 4 (ialogs) which is the de!ault location.
7( Clic, New to open the "ew %ibrary dialog.
B( <nter a library name) !or e1ample Test%ibrary) and clic, 1.
9( Select the Mod)les tab.
:( Cn the Mod)le list) e1pand My Macros and select) !or e1ample Test%ibrary. + module named
0odule1 already e1ists and can contain your macro. C! you wish) you can clic, New to
create another module in the library.
5o)r first $acros &
=( Select 0odule1) or the new module that you created) and clic, -dit to open the Cntegrated
>ebugging <n*ironment &C><( &.igure 3(. The C>< is a te1t editor included with %ibre6!!ice
that allows you to create and edit macros.
?( 4hen a new module is created) it contains a comment and an empty macro named 0ain)
which does nothing.
10( +dd the new macro either be!ore Sub 0ain or a!ter <nd Sub. %isting 2 shows the new
macro has been added be!ore Sub 0ain.
11( Clic, the Compile icon on the 0acro toolbar to compile the macro.
12( Clic, the 2un 0A3$C icon on the 0acro toolbar) or press the %& ,ey) to run the
3ello0acro in the module. + small dialog will open with the word D3elloE displayed.
13( Clic, 1 to close this small dialog.
17( To select and run any macro in the module) clic, the 3elect Macro icon on the
Standard toolbar or go to Tools > Macros > rgani*e Macros > !ibreffice 0asic"
1B( Select a macro and then clic, 2un.
*isting 0- Mod)le1 after adding the new $acro.
REM ***** BASIC *****
Sub HelloMacro
Print "Hello"
End Sub
Sub Main
End Sub
2ecording a macro
C! you ha*e to repeatedly enter the same in!ormation) you can copy this in!ormation a!ter it has
been entered into your document !or the !irst time) then paste the in!ormation into your document
each time you want to use it. 3owe*er) i! something else is copied to the clipboard) the contents on
the clipboard are changed. This means that you ha*e reFcopy your repeated in!ormation. To
o*ercome this problem) you can create a macro that enters your repeated in!ormation.
Note
.or some types o! in!ormation that you want to repeatedly enter into a document) it
maybe more con*enient to create an +utoTe1t !ile. See the 6riter G)ide Chapter 3
6oring with 'e7t !or more in!ormation.
1( 0a,e sure macro recording is enabled by going to Tools > ptions > !ibreffice >
Advanced on the main menu bar and selecting the option -nable macro recording. 5y
de!ault) this !eature is turned o!! when %ibre6!!ice was installed on your computer.
2( Go to Tools > Macros > 2ecord Macro on the main menu bar to start recording a macro.
+ small dialog is displayed indicating that %ibre6!!ice is recording a macro.
3( Type the desired in!ormation or per!orm an appropriate series o! operations. +s an
e1ample) type your name.
7( Clic, 3top 2ecording on the small -ecording dialog to stop recording and the %ibre6!!ice
5asic 0acros dialog opens &.igure 1 on page 7(.
B( 6pen the library container My Macros.
9( .ind the library named Standard in 0y 0acros. "ote that e*ery library container has a
library named Standard.
8 Getting Started with Macros
:( Select the Standard library and clic, New Module to create a new module to contain the
macro. This opens the "ew 0odule dialog &.igure 7(.
%ig)re /- 9ew Mod)le dialog
=( Type a descripti*e name !or the new module) !or e1ample Recorded and clic, 1 to create
the module. The %ibre6!!ice 5asic 0acros dialog now displays the name o! the new module
in the Standard library.
?( Cn the Macro name te1t bo1) type a name !or the macro you ha*e Iust recorded) !or
e1ample 3nterMy9a$e.
10( Clic, 3ave to sa*e the macro and close the %ibre6!!ice 5asic 0acros dialog.
11( C! you !ollowed all o! the abo*e steps) the Standard library now contains a module named
-ecorded and this module contains the <nter0y"ame macro.
Note
4hen %ibre6!!ice creates a new module) it automatically adds the macro named
0ain.
2unning a macro
1( Go to Tools > Macros > 2un Macro on the main menu bar to open the 0acro Selector
dialog &.igure B(.
2( .or e1ample) select your newly created macro <nter0y"ame and clic, 2un.
3( +lternati*ely) go to Tools > Macros > rgani*e Macros > !ibreffice 0asic on the main
menu bar to open the %ibre6!!ice 5asic 0acros dialog) select your macro and clic, 2un.
%ig)re &- Macro Selector dialog
4iewing and editing macros
To *iew andor edit the macro that you created'
1( Go to Tools > Macros > rgani*e Macros > !ibreffice 0asic to open the %ibre6!!ice
5asic 0acros dialog.
5o)r first $acros :
2( Select your new macro <nter0y"ame and clic, -dit to open the macro in the 5asic C><.
The macro <nter0y"ame is shown in %isting 3.
The <nter0y"ame macro is not as complicated as it !irst appears. %earning a !ew things helps
signi!icantly in understanding macros. The discussion starts with !eatures near the top o! the macro
listing and describes them.
*isting 3- Generated ;3nterMyna$e< $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(+
rem -------------------------------------------------------------
dim ar!s,'-+ as ne. com$sun$star$beans$/roperty0alue
ar!s,'-+$Name " (#e1t(
ar!s,'-+$0alue " (2our name(
dispatcer$e1ecute)ispatc'document3 ($uno4Insert#e1t(3 ((3 -3 ar!s,'++
end sub
REM comments
+ll comments in macro coding begin with -<0) which stands !or remar,. +ll te1t a!ter -<0 and on
the same line is ignored. +s a short cut) the single @uote character &J( can also be used to start a
comment.
%ibre6!!ice 5asic is not caseFsensiti*e !or ,eywords) so -<0) -em) and rem can all start a
comment. C! you use symbolic constants de!ined by the +pplication $rogramming Cnter!ace &+$C() it
is sa!er to assume that the names are caseFsensiti*e. Symbolic constants are an ad*anced topic
not co*ered by this user guide and are not re@uired when using the macro recorder in %ibre6!!ice.
Defining subroutines with SUB
Cndi*idual macros are stored in subroutines and these subroutines begin with the ,eyword S#5.
The end o! a subroutine is indicated by the words <"> S#5. The code starts by de!ining the
subroutine named 0ain) which is empty and does nothing. The ne1t subroutine) <nter0y"ame)
contains the generated code !or your macro.
Note
%ibre6!!ice always creates an empty subroutine named 0ain when it creates a
macro.
There are ad*anced topics that are beyond the scope o! this user guide) but ,nowing about them
might be o! interest'
You can write a macro so that *alues can be passed to the subroutine. The *alues are
called arguments. 3owe*er) recorded macros in %ibre6!!ice do not accept arguments.
= Getting Started with Macros
+nother ,ind o! subroutine is called a !unction which is a subroutine that returns a *alue.
.unctions are de!ined by the ,eyword .#"CTC6" at the beginning. 3owe*er) recorded
macros in %ibre6!!ice do not accept !unctions.
Defining variables using Dim
You can write in!ormation on a piece o! paper so that you can loo, at it later. + *ariable) li,e a piece
o! paper) contains in!ormation that can be changed and read. >im originally in 5+SCC stood !or
>imension and was used to de!ine the dimensions o! an array. The dim statement used in the
<nter0y"ame macro is similar to setting aside a piece o! paper to be used to store a message or
note.
Cn the <nter0y"ame macro) the *ariables document and dispatcer are de!ined as the type
o+>ect. 6ther common *ariable types include string) integer) and date. + third *ariable) named
args1? 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,. ;alues in an array are usually
numbered starting !rom Hero. The number in the parentheses indicates the highest usable number
to access a storage location. Cn this e1ample) there is only one *alue) and it is numbered Hero.
Exlaining macro code
The !ollowing is an e1planation o! the coding used in the <nter0y"ame macro. You may not
understand all the details) but the e1planation o! each line o! code may gi*e you some idea o! how
a macro wor,s.
sub EnterMyName
>e!ines the start o! the macro
dim document as object
>e!ined as a *ariable
dim dispatcer as objects.
>e!ined as a *ariable
document " #isComponent$CurrentController$%rame
ThisComponent re!ers to the current document.
CurrentController is a property re!erring to a ser*ice that controls the document. .or e1ample)
when you type) it is the current controller that ta,es note o! what you type. CurrentController
then dispatches the changes to the document !rame.
.rame is a controller property that returns a main !rame !or a document. There!ore) the *ariable
named document re!ers to a documentKs !rame) which recei*es dispatched commands.
dispatcer " create&noService'(com$sun$star$frame$)ispatc*elper(+
0ost tas,s in %ibre6!!ice are accomplished by dispatching a command. %ibre6!!ice includes a
dispatch helper ser*ice) which does most o! the wor, when using 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 re!erence to a >ispatch3elper.
dim ar!s,'-+ as ne. com$sun$star$beans$/roperty0alue
>eclares an array o! properties. <ach property has a name and a *alue. Cn other words) it is a
name*alue pair. The created array has one property at inde1 Hero.
ar!s,'-+$Name " (#e1t(
ar!s,'-+$0alue " (2our name(
Gi*es the property the name DTe1tE and the *alue DYour nameE) which is the te1t that is inserted
when the macro is run.
dispatcer$e1ecute)ispatc'document3 ($uno4Insert#e1t(3 ((3 -3 ar!s,'++
5o)r first $acros @
This is where the magic happens. The dispatch helper sends a dispatch to the document !rame
&stored in the *ariable named document( with the command .uno'CnsertTe1t. The ne1t two
arguments) !rame name and search !lags) are beyond the scope o! this document. The last
argument is the array o! property *alues to be used while e1ecuting the command CnsertTe1t.
end sub
The last line o! the code ends o! the subroutine.
Creating a macro
4hen creating a macro) it is important to as, two @uestions be!ore recording'
1( Can the tas, be written as a simple set o! commandsA
2( Can the steps be arranged so that the last command lea*es the cursor ready !or the ne1t
command or entering te1t or data into the documentA
A more complicated e.ample of a macro
+ common tas, is to copy rows and columns o! data !rom a web site and !ormat them as a table in
a te1t document as !ollows'
1( Copy the data !rom the web site to the clipboard.
2( To a*oid strange !ormatting and !onts) paste the te1t into a 4riter document as un!ormatted
te1t.
3( -e!ormat the te1t with tabs between columns so that it can be con*erted into a table using
Table > Convert > Te.t to Table on the main menu bar.
>6"TL"64 The !ont weight is not speci!ied,nown.
T3C" speci!ies a B0M !ont weight.
#%T-+%CG3T speci!ies a 90M !ont weight.
%CG3T speci!ies a :BM !ont weight.
S<0C%CG3T speci!ies a ?0M !ont weight.
"6-0+% speci!ies a normal !ont weight.
S<0C56%> speci!ies a 110M !ont weight.
56%> speci!ies a 1B0M !ont weight.
#%T-+56%> speci!ies a 1:BM !ont weight.
5%+CL speci!ies a 200M !ont weight.
%ig)re 8- 37a$ple of copied data
4ith the two @uestions gi*en abo*e in mind) inspect the te1t to see i! a macro can be recorded to
!ormat the te1t. +n e1ample o! copied data showing the .ont4eight constants group !rom the +$C
web site &.igure 9(. The !irst column in this e1ample indicates a constant name and each name is
!ollowed by a space and a tab.
The !irst column in the table should contain a numeric *alue) the second column the name) and the
third column the description. This con*ersion is easily accomplished !or e*ery row e1cept !or
>6"TL"64 and "6-0+%) which do not contain a numeric *alue) but the *alues are between 0
and 100 and can be entered manually.
1A Getting Started with Macros
The data can be cleaned up in se*eral ways) all o! them easy to accomplish. The e1ample gi*en
below uses ,eystro,es that assume the cursor is at the start o! the line with the te1t T3C".
1( 0a,e sure macro recording is enabled by going to Tools > ptions > !ibreffice >
Advanced on the main menu bar and selecting the option -nable macro recording. 5y
de!ault) this !eature is turned o!! when %ibre6!!ice was installed on your computer.
2( Go to Tools > Macros > 2ecord Macro on the main menu bar to start recording.
3( $ress Ctrl!Right Brrow to mo*e the cursor to the start o! Dspeci!iesE.
7( $ress Bacspace twice to remo*e the tab and the space.
B( $ress 'a+ to add the tab without the space a!ter the constant name.
9( $ress (elete to delete the lower case s and then press Shift!S to add an upper case S.
:( $ress Ctrl!Right Brrow twice to mo*e the cursor to the start o! the number.
=( $ress Ctrl!Shift!Right Brrow to select and mo*e the cursor be!ore the M sign.
?( $ress Ctrl!C to copy the selected te1t to the clipboard.
10( $ress 3nd to mo*e the cursor to the end o! the line.
11( $ress Bacspace twice to remo*e the two trailing spaces.
12( $ress Co$e to mo*e the cursor to the start o! the line.
13( $ress Ctrl!D to paste the selected number to the start o! the line.
17( $asting the *alue also pasted an e1tra space) so press Bacspace to remo*e the e1tra
space.
1B( $ress 'a+ to insert a tab between the number and the name.
19( $ress Co$e to mo*e to the start o! the line.
1:( $ress down arrow to mo*e to the ne1t line.
1=( Stop recording the macro and sa*e the macro) see D-ecording a macroE on page 9.
Ct ta,es much longer to read and write the steps than to record the macro. 4or, slowly and thin,
about the steps as you do them. 4ith practice this becomes second nature.
The generated macro code in %isting 7 has been modi!ied to contain the step number in the
comments to match the code to the step abo*e.
*isting /- Copying n)$eric ,al)e to start of the col)$n.
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.Bac;space(3 ((3 -3 Array'++
rem -------------------------------------------------------------
dispatcer$e1ecute)ispatc'document3 ($uno4S.Bac;space(3 ((3 -3 Array'++
rem '<+ /ress Tab to add te tab .itout te space after te constant name$
Creating a $acro 11
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 Shift+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 'A+ /ress Ctrl+Shift+Right Arrow to select te number$
dispatcer$e1ecute)ispatc'document3 ($uno49ordRi!tSel(3 ((3 -3 Array'++
rem '>+ /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.Bac;space(3 ((3 -3 Array'++
rem -------------------------------------------------------------
dispatcer$e1ecute)ispatc'document3 ($uno4S.Bac;space(3 ((3 -3 Array'++
rem ',D+ /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.Bac;space(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$
10 Getting Started with Macros
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(. C! run on the
>6"TL"64 line) the word weight is mo*ed to the !ront o! the line) and the !irst DTheE is changed
to DSheE. This is not per!ect) but you should not run the macro on the lines that did not ha*e the
proper !ormat. You need to do these manually.
2unning a macro 5uickly
Ct is tedious to repeatedly run the macro using Tools > Macros > 2un Macro on the main menu
bar when the macro can be run !rom the C>< &.igure 3 on page B(.
1( Go to Tools > Macros > rgani*e Macros > !ibreffice 0asic on the main menu bar to
open the 5asic 0acro dialog &.igure 1 on page 7(.
2( Select your macro and clic, -dit to open the macro in the C><.
3( Clic, the 2un 0A3$C icon on the 0acro toolbar) or press the %& ,ey) to run the macro.
7( #nless you change the !irst macro) it is the empty macro named 0ain. 0odi!y 0ain so that
it reads as shown in %isting B.
B( "ow) you can run Copy"umToCol1 by repeatedly clic,ing the 2un 0asic icon in the toolbar
o! the C><. This is *ery !ast and easy) especially !or temporary macros that will be used a
!ew times and then discarded.
*isting &- Modify Main to call Copy9)$'oCol1.
Sub Main
CopyNum#oCol,
End Sub
Macro recorder failures
Sometimes the macro recorder has a !ailure and understanding %ibre6!!ice internal wor,ings helps
to understand how and why the macro recorder sometimes !ails. The primary o!!ender is related to
the dispatch !ramewor, and its relationship to the macro recorder.
6ispatch framework
The purpose o! the dispatch !ramewor, is to pro*ide uni!orm access to components &documents(
!or commands that usually correspond to menu items. #sing File > 3ave !rom the main menu bar)
the shortcut ,eys Ctrl!S) or clic,ing the 3ave icon are all o! commands that are translated into the
same Ddispatch commandE.
The dispatch !ramewor, can also be used to send DcommandsE bac, to the #ser Cnter!ace &#C(. .or
e1ample) a!ter 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.
+ dispatch command is te1t) !or e1ample .uno'Cnsert6bIect or .uno'GoToStart6!%ine. The
command is sent to the document !rame and this passes on the command until an obIect is !ound
that can handle the command.
Macro recorder fail)res 13
+ow the macro recorder uses the dispatch framework
The macro recorder records the generated dispatches. The recorder is relati*ely simple tool to use
and the same commands that are issued are recorded !or later use. The problem is that not all
dispatched commands are complete. .or e1ample) inserting an obIect generates the !ollowing
code'
dispatcer$e1ecute)ispatc'document3 ($uno4InsertBbject(3 ((3 -3 Array'++
Ct is not possible to speci!y what ,ind o! obIect to create or insert. C! an obIect is inserted !rom a !ile)
you cannot speci!y which !ile to insert.
-ecording a macro and using Tools > ptions on the main menu bar to open and modi!y
con!iguration items) the generated macro does not record any con!iguration changes. Cn !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'++
C! a dialog is opened) a command to open the dialog is li,ely to be generated. +ny wor, done inside
the dialog is not usually recorded. <1amples o! this include macro organiHation 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 e1porting a document to an encrypted $>. !ile. You ne*er ,now !or certain
what will wor, unless you try it. .or e1ample) the actions !rom the search dialog are properly
captured.
ther options
4hen the macro recorder is not able to sol*e a speci!ic problem) the usual solution is to write code
using the %ibre6!!ice obIects. #n!ortunately) there is a steep learning cur*e !or these %ibre6!!ice
obIects. Ct is usually best to start with simple e1amples and then increase the scope o! macros as
you learn more. %earning to read generated macros is a good place to start.
C! you record Calc macros) and the recorder can correctly generate a macro) there is an addFin
a*ailable which con*erts Calc macros when they are recorded. The !inal code manipulates
%ibre6!!ice obIects rather than generating dispatches. This can be *ery use!ul !or learning the
obIect model and can be downloaded directly !rom the web site'
http'www.paoloFmanto*ani.orgdownloads>ispatchTo+pi-ecorder
Macro organi*ation
Cn %ibre6!!ice) macros are grouped in modules) modules are grouped in libraries) and libraries are
grouped in library containers. + library is usually used as a maIor grouping !or either an entire
category o! macros) or !or an entire application. 0odules usually split !unctionality) such as user
interaction and calculations. Cndi*idual macros are subroutines and !unctions. .igure : shows an
e1ample o! the hierarchical structure o! macro libraries in %ibre6!!ice.
Go to Tools > Macros > rgani*e Macros > !ibreffice 0asic on the main menu bar to open the
%ibre6!!ice 5asic 0acros dialog &.igure 1 on page 7(. +ll a*ailable library containers are shown in
the Macro fro$ list. <*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
%ibre6!!ice called %ibre6!!ice 0acros) and one container !or personal macros called 0y 0acros.
The %ibre6!!ice 0acros 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 %ibre6!!ice container.
1/ Getting Started with Macros
#nless your macros are applicable to a single document) and only to a single document) your
macros will probably be stored in the 0y 0acros container. The 0y 0acros container is stored in
your user area or home directory.
%ig)re :- Macro *i+rary hierarchy
C! a macro is contained in a document) then a recorded macro will attempt to wor, on that
documentG because it primarily uses DThisComponentE !or its actions.
<*ery library container contains a library named Standard. Ct is better to create your own libraries
with meaning!ul names than to use the Standard library. "ot only are meaning!ul names easier to
manage) but they can also be imported into other library containers whereas the Standard library
cannot.
Caution %ibre6!!ice allows you to import libraries into a library container) but it will not allow
you to o*erwrite the library named Standard. There!ore) 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 meaning!ul names) it is prudent to use
meaning!ul names !or your modules. 5y de!ault) %ibre6!!ice uses names such as 0odule1)
0odule2 and so on.
+s you create your macros) you must decide where to store them. Storing a macro in a document
is use!ul i! the document will be shared and you want the macro to be included with the document.
0acros stored in the application library container named 0y 0acros) howe*er) are globally
a*ailable to all documents.
0acros 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 di!!erently !rom a
library that is not loaded. To load the library and the modules it contains) doubleFclic, on the library.
/here are macros stored7
%ibre6!!ice stores userFspeci!ic data in a directory in the home directory !or each user. The location
is operating system speci!ic. Go to Tools > ptions > !ibreffice > Paths on the main menu bar
to *iew where other con!iguration data are stored. .or e1ample) on computer running 4indows N$)
this is C4E)ocuments and Settin!sEFuser nameGEApplication )ata. #ser macros are
Macro organi1ation 1&
stored in CibreBfficeE:EuserEbasic. <ach library is stored in its own directory o!! the basic
directory.
Ct is not important to understand where macros are stored !or casual use. C! 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.
Go to Tools > Macros > rgani*e 6ialogs on the main menu bar to open the %ibre6!!ice 0acro
6rganiHer dialog &.igure 2 on page B(. +lternati*ely) go to Tools > Macros > rgani*e Macros >
!ibreffice 0asic on the main menu bar to open the %ibre6!!ice 0acros dialog &.igure 1 on page
7( and then clic, the rgani*er button.
$mporting macros
The %ibre6!!ice 0acro 6rganiHer 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 clic, $mport to import macro libraries &.igure 2
on page B(.
2( "a*igate to the directory containing the library to import &.igure =(. There are usually two
!iles !rom which to choose) dialog.1lb and script.1lb. Ct does not matter which o! these two
!iles you selectG both will be imported. 0acros can be stored in libraries inside %ibre6!!ice
documents. Select a document rather than a directory on dis, to import libraries contained
in a document.
Note
You cannot import the library named Standard.
%ig)re =- 9a,igating to a $acro li+rary
Tip
6n a computer operating %inu1) the %ibre6!!ice speci!ic !iles are stored in the home
directory o! a user in a directory whose name begins with a period. >irectories and
!iles with names beginning with a period are normally hidden and not shown in a
normal selection dialog. To open hidden !olders and !iles) press Ctrl-C to show
hidden !olders and !iles not normally shown and na*igate as usual.
18 Getting Started with Macros
3( Select a !ile and clic, pen to continue and open the Cmport %ibraries dialog &.igure ?(.
%ig)re @- Choose li+rary i$port options
7( Select the !ollowing options !or importing libraries'
a( C! no options are selected) the library is copied to your user macro directory. 3owe*er) i!
the library you are importing has the same name and you are importing into the same
location) it will not be copied.
b( Select 2eplace e.isting libraries i! the library you want to import has the same name
and you want to replace the e1isting library.
c( Select $nsert as reference i! you want to use the library as re!erence) but not import the
library into your document. 4hen a library is used as a re!erence) it remains in its
current location and is read only.
B( Clic, 1 to import the macro library you selected.
6ownloading macros to import
0acros 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 te1t that should be copied and pasted
into the 5asic C><. See D+dding a macroD on page 7 on how to add macros to your macro library
and D;iewing and editing macrosE on page : on how to edit macros using the 5asic C><..
Some macros are a*ailable as !ree downloads on the Cnternet &see Table 1(.
'a+le 1. Macro e7a$ples
Location Descrition
http'www.ooomacros.org Collection o! pac,aged macros now somewhat dated.
http'www.pitonya,.orgoo.php -e!erence materials regarding macros.
http'www.pitonya,.orgdatabase -e!erence materials regarding database macros.
http'de*elopment.openo!!ice.org %ots o! lin,s to e*erything.
http'www.ooo!orum.org + !orum) with many e1amples and help.
http'user.ser*ices.openo!!ice.org +nother !orum) with many e1amples and help.
Macro organi1ation 1:
+ow to run a macro
+lthough you can use Tools > Macros > 2un Macro to run all macros) this is not e!!icient !or
!re@uently run macros. See D-unning a macroE on page : !or more in!ormation.
+ more common techni@ue !or !re@uently used macros is to assign the macro a toolbar icon) menu
item) ,eyboard shortcut) or a button embedded in a document. 4hile choosing a method) it is also
good to as, @uestions such as'
Should the macro be a*ailable !or only one document) or globally !or all documentsA
Cs the macro !or a speci!ic document type) such as a Calc documentA
3ow !re@uently will the macro be usedA
The answers will determine where to store the macro and how to ma,e it a*ailable. .or e1ample)
you will probably not add a rarely used macro to a toolbar. To help determine your choices) see
Table 2.
'a+le 0. Methods for starting a $acro
!"e Libre#ffice Document !"e Document
Toolbar "o Yes Yes
0enu "o Yes Yes
Shortcut Yes Yes "o
<*ent Yes "o Yes
Toolbars8 menu items and keyboard shortcuts
To add a menu item) ,eyboard shortcut) or toolbar icon that calls a macro) use the CustomiHe
dialog &.igure 10(. The CustomiHe dialog contains pages to con!igure menus) ,eyboard shortcuts)
toolbars) and e*ents. To open this dialog) go to Tools > Customi*e on the main menu bar or rightF
clic, in an empty space on a toolbar and select Customi*e Toolbar !rom the conte1t menu.
Complete co*erage o! the CustomiHe dialog is beyond the scope o! this chapter. Clic, the +elp
button to access the help pages included with %ibre6!!ice or see Chapter 1/ C)sto$i1ing
*i+reOffice.
1= Getting Started with Macros
%ig)re 1A- Men)s page in C)sto$i1e dialog
-vents
Cn %ibre6!!ice) when something happens it is that has an e*ent occurred. .or e1ample) opening a
document) pressing a ,ey) or mo*ing the mouse cursor. %ibre6!!ice allows e*ents to cause a
macro to be calledG 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 care!ul when you con!igure an e*ent handler. .or e1ample) 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 %ibre6!!ice.
1( Go to Tools > Customi*e on the main menu bar to open the CustomiHe dialog and select
the <*ents tab &.igure 11(. The e*ents in the CustomiHe dialog are related to the entire
application and speci!ic documents.
2( Cn 3ave $n) select %ibre6!!ice) or a speci!ic document !rom the drop down menu to sa*e
your e*ent.
3( + common use is to assign the 6pen >ocument e*ent to call a speci!ic macro. The macro
then per!orms certain setup tas,s !or the document. Select the desired e*ent and clic,
Macro to open the 0acro Selector dialog &.igure B on page :(.
7( Select the desired macro and clic, 1 to assign the macro to the e*ent. The <*ents page
shows that the e*ent has been assigned to a macro.
Cow to r)n a $acro 1@
%ig)re 11- 3,ents page in C)sto$i1e dialog
0any obIects in a document can be set to call macros when e*ents occur. The most common use
is to add a control) such as a button) into a document. <*en doubleFclic,ing on a graphic opens a
dialog with a 0acros tab that allows you to assign a macro to an e*ent.
-.tensions
+n e1tension is a pac,age that can be installed into %ibre6!!ice to add new !unctionality.
<1tensions can be written in almost any programming language and may be simple or
sophisticated. <1tensions can be grouped into types'
Calc +ddFCns) which pro*ide new !unctionality !or Calc) including new !unctions that act li,e
normal builtFin !unctions
"ew components and !unctionality) which normally include some le*el o! #ser Cnter!ace &#C(
integration such as new menus or toolbars
$i*ot Tables that are used directly in Calc
Chart +ddFCns with new chart types
%inguistic components such as spell chec,ers
>ocument templates and images
+lthough indi*idual e1tensions can be !ound in se*eral places) there is currently an e1tension
repository at' http'e1tensions.libreo!!ice.org and some documentation at
http'libreplanet.orgwi,iGroup'6pen6!!ice<1tensions%ist
.or more about obtaining and installing e1tensions) see Chapter 1/ C)sto$i1ing *i+reOffice.
0A Getting Started with Macros
/riting macros without the recorder
The e1amples co*ered in this chapter are created using the macro recorder and the dispatcher.
You can also write macros that directly access the obIects that comprise %ibre6!!ice i! you are
con!ident in writing computer code. Cn other words) you can create a macro that directly
manipulates a document.
>irectly manipulating %ibre6!!ice internal obIects is an ad*anced topic that is beyond the scope o!
this chapter. + simple e1ample) howe*er) demonstrates how this wor,s.
*isting 8- Bppend the te7t ;Cello< to the c)rrent doc)$ent.
Sub Append*ello
)im o)oc
)im s#e1tService=
)im oCurs

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 .or;s .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 > !ibreffice
+elp to open the %ibre6!!ice help pages. The upper le!t corner o! the %ibre6!!ice help system
contains a dropFdown list that determines which help set is displayed. To *iew the help !or 5asic)
choose *i+reOffice Basic !rom this list.
$ncluded material
0any e1cellent macros are included with %ibre6!!ice. #se Tools > Macros > rgani*e Macros >
!ibreffice 0asic to open the 0acro dialog. <1pand the Tools library in the %ibre6!!ice library
container. Cnspect the >ebug moduleOsome good e1amples include 4ritedbgCn!o&document( and
printdbgCn!o&sheet(.
nline resources
The !ollowing lin,s and re!erences contain in!ormation regarding macro programming'
http'as,.libreo!!ice.org &a P Q + site where *olunteers answer @uestions related to %ibre6!!ice(
%inding $ore infor$ation 01
http'!orum.openo!!ice.orgen!orum &+pache 6pen6!!ice community !orumG *olunteers answer
@uestions about %ibre6!!ice as well(
http'api.openoffice.orgdocscommonre!comsunstarmoduleFi1.html &o!!icial C>% re!erenceG here
you will !ind almost e*ery command with a description(
https'wi,i.document!oundation.org>ocumentation6therR>ocumentationRandR-esources &loo,
in $rogrammers section !or BBS2C Erogra$$ersF G)ide and (e,elopersF G)ideG the latter contains
a detailed e1planation(
http'www.pitonya,.orgoo.php &macro page !or +ndrew $itonya,(
http'www.pitonya,.org+ndrew0acro.odt &numerous e1amples o! wor,ing macros(
http'www.pitonya,.org660<R3R0.odt &+ndrew $itonya,Ks boo, on macros(
http'www.pitonya,.orgdatabase &numerous macro e1amples using 5ase(
Printed and e0ook materials
There are currently no boo,s speci!ic to %ibre6!!ice macros that are a*ailable !or download.
Cn!ormation in the !ollowing boo,s is mostly applicable to %ibre6!!iceG the boo,s are a*ailable !or
purchase in both printed and e5oo, !orm !rom their publishers'
>r. 0ar, +le1ander 5ainKs *earn OpenOffice.org Spreadsheet Macro Erogra$$ing.
See http'www.pac,tpub.comopeno!!iceFooobasicFcalcFautomationboo,.
-oberto 5eniteHJs (ata+ase Erogra$$ing with OpenOffice.org Base 4 Basic.
See http'www.lulu.comproductpaperbac,databaseFprogrammingFwithFopeno!!iceorgFbaseF
basic3B9=:2=
00 Getting Started with Macros

You might also like