19
Calc Guide Chapter 12  Calc Macros  Automating repetitive tasks This PDF is designed to be read onscreen, two pages a t a time. I !ou want to print a cop! , !our PDF viewer should have an option or printing two pages on one sheet o paper , but !ou ma! need to start with page " to get it to print acing pag es correctl! . #Print this cover page separatel!.$

Macros en Calc de Open Oxygen

  • Upload
    solo

  • View
    226

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 1/18

Calc Guide

Chapter 12 Calc Macros Automating repetitive tasks

This PDF is designed to be read onscreen, two pages at atime. I !ou want to print a cop!, !our PDF viewer shouldhave an option or printing two pages on one sheet opaper, but !ou ma! need to start with page " to get it toprint acing pages correctl!. #Print this cover pageseparatel!.$

Page 2: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 2/18

CopyrightThis document is Cop!right © "%%&'"%%( b! its contributors as listedin the section titled Authors . )ou ma! distribute it and*or modi ! itunder the terms o either the G+ General Public -icense , version orlater, or the Creative Commons Attribution -icense , version .% orlater.

All trademarks within this guide belong to their legitimate owners.

Authors Andrew Piton!ak Gar! /chnabl

0ean 1ollis 2eber

Feedback 3aintainer4 Andrew Piton!ak 5 andrew6piton!ak.org 7Please direct an! comments or suggestions about this document to4authors6user8 a9.openo ice.org

Publication date and software versionPublished "" 3a! "%%(. :ased on ;pen; ice.org .<.

)ou can download an editable version o this document rom

http4**oooauthors.org*en*authors*userguide *published*

Page 3: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 3/18

ContentsCop!right..............................................................................................."Introduction...........................................................................................=

sing the macro recorder......................................................................=2rite !our own unctions.......................................................................>

sing a macro as a unction..............................................................<%Passing arguments to a macro..........................................................<

Arguments are passed as values.......................................................<=2riting macros that act like built8in unctions..................................<=

Accessing cells directl!........................................................................<&

/orting.................................................................................................<>Conclusion...........................................................................................<?

Calc 3acros

Page 4: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 4/18

Introduction A macro is a saved se9uence o commands or ke!strokes that arestored or later use. An e@ample o a simple macro is one that t!pesB

!our address. The ;pen; ice.org #;;o$ macro language is ver!le@ible, allowing automation o both simple and comple@ tasks. 3acros

are especiall! use ul to repeat a task the same wa! over and overagain. This chapter brie l! discusses common problems related tomacro programming using Calc.

Using the macro recorderChapter < o the Getting /tarted guide #Getting /tarted with 3acros$provides a basis or understanding the general macro capabilities in;pen; ice.org using the macro recorder. An e@ample is shown herewithout the e@planations in the Getting /tarted guide. The ollowingsteps create a macro that per orms paste special with multipl!.

<$ ;pen a new spreadsheet."$ nter numbers into a sheet.

Figure <4 nter numbers.$ /elect cell A , which contains the number , and cop! the value

to the clipboard.=$ /elect the range A<4C .&$ se Tools > Macros > Record Macro to start the macro

recorder. The ecord 3acro dialog is displa!ed with a stoprecording button #see Figure " $.

Figure "4 /top recording button.

= Calc 3acros

Page 5: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 5/18

Page 6: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 6/18

Page 7: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 7/18

-isting <. Paste special with multipl!.sub PasteMultiply

rem --------------------------------------------------------------rem define variablesdim document as objectdim dispatcher as objectrem --------------------------------------------------------------rem get access to the documentdocument = ThisComponent . CurrentController . Framedispatcher = createUno ervice ! "com.sun.star.frame.#ispatch$elper" %

rem --------------------------------------------------------------dim args& ! ' % as ne( com. sun . star . beans . Property)alueargs& ! *%.+ame = "Flags"args& ! *%. )alue = ","args& ! &%.+ame = "FormulaCommand"args& ! &%.)alue = args& ! %.+ame = " /ip0mptyCells"args& ! %. )alue = falseargs& ! %.+ame = "Transpose"args& ! %. )alue = falseargs& ! 1%.+ame = ",s2in/"args& ! 1%. )alue = falseargs& ! ' %.+ame = "MoveMode"args& ! ' %. )alue = 1

dispatcher . e3ecute#ispatch ! document 4 ".uno56nsertContents" 4 "" 4 *4 args& !%%end sub

3ore detail on recording macros is provided in Chapter < #Getting/tarted with 3acros$ in the Getting /tarted guide we recommend !ouread it i !ou have not alread! done so. 3ore detail is also provided inthe ollowing sections, but not as related to recording macros.

Write your own functionsCalc can call macros as Calc unctions. se the ollowing steps tocreate a simple macro4

<$ Create a new Calc document named CalcTestMacros.ods ."$ se Tools > Macros > Organi"e Macros > OpenO##ice$org

%asic to open the ;pen; ice.org :asic 3acros dialog #seeFigure > $. The 3acro rom bo@ lists available macro librar!containers. 3! 3acros contains macros that !ou write or add to;;o. ;pen; ice.org 3acros contains macros included with ;;oand should not be changed. All other librar! containers arecurrentl! open ;;o documents.

2rite !our own unctions >

Page 8: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 8/18

Figure >. ;pen; ice.org :asic 3acros dialog.

$ Click Organi"er to open the ;pen; ice.org :asic 3acro

;rganiHer dialog #see Figure ? $.

Figure ?. ;pen; ice.org :asic 3acro ;rganiHer.

=$ Click the &i'raries tab.&$ /elect the document to contain the macro.E$ Click Ne to open the +ew -ibrar! dialog #see Figure ( $.

Figure (. +ew -ibrar! dialog.>$ nter a descriptive librar! name #such as AuthorsCalc3acros$

and click OK to create the librar! #see Figure <% $. The newlibrar! name is shown the librar! list, but the dialog ma! showonl! a portion o the name.

? Calc 3acros

Page 9: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 9/18

Page 10: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 10/18

Page 11: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 11/18

Figure <=. The unction is gone.;o documents can contain macros. 2hen the document is created

and saved, it automaticall! contains a librar! named /tandard. The/tandard librar! is special in that it is automaticall! loaded when thedocument is opened. +o other librar! is automaticall! opened.Calc does not contain a unction named +umberFive#$, so it checks allopened and visible macro libraries or the unction. -ibraries inpen; ice.org 3acros , 3! 3acros , and the Calc document are

checked or an appropriatel! named unction #see Figure > $. The+umberFive#$ unction is stored in the AuthorsCalc3acros librar!,which is not automaticall! loaded when the document is opened.

se Tools > Macros > Organi"e Macros > OpenO##ice$org %asicto open the ;pen; ice.org :asic 3acros dialog #see Figure > $. @pandCalcTest3acros and ind AuthorsCalc3acros. The icon or a loadedlibrar! is di erent than the icon or a librar! that is not loaded #seeFigure <& $.

Figure <&. ,nloaded macro librar!.

Click the plus # $ ne@t to AuthorsCalc3acros to load the librar!. Theicon changes to indicate that the librar! is now loaded #see Figure <E $.Click Close to close the dialog.

Figure <E4 -oaded macro librar! uses adi erent icon.

n ortunatel!, the cells containing J+umberFive#$ are in error. Calcdoes not recalculate cells in error unless !ou edit them or somehowchange them. The usual solution is to store macros used as unctions in

the /tandard librar!. I the macro is large or i there are man! macros,a stub with the desired name is stored in the /tandard librar!. The stub

2rite !our own unctions <<

Page 12: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 12/18

macro loads the librar! containing the implementation and then callsthe implementation.

<$ se Tools > Macros > Organi"e Macros > OpenO##ice$org%asic to open the ;pen; ice.org :asic 3acros dialog #seeFigure <> $. /elect the +umberFive macro and click Edit to openthe macro or editing.

Figure <>. /elect a macro and click dit.

"$ Change the name o +umberFive to +umberFiveKImplementation#see -isting $.

-isting . Change the name o +umberFive to

+umberFiveKImplementation Function +umberFive;6mplementation !% +umberFive;6mplementation !% = '0nd Function

$ In the :asic ID #see Figure << $, hover the mouse cursor over thetoolbar buttons to displa! the tool tips. Click the Select Macrobutton to open the ;pen; ice.org :asic 3acros dialog #seeFigure <> $.

=$ /elect the /tandard librar! in the CalcTest3acros document andclick Ne to create a new module. nter a meaning ul name suchas CalcFunctions and click OK . ;;o automaticall! creates amacro named 3ain and opens the module or editing.

&$ Create a macro in the /tandard librar! that calls theimplementation unction #see -isting = $. The new macro loads the

AuthorsCalc3acros librar! i it is not alread! loaded, and thencalls the implementation unction.

<" Calc 3acros

Page 13: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 13/18

-isting =. Change the name o +umberFive to+umberFiveKImplementation.Function +umberFive !% 6f +:T 9asic2ibraries . is2ibrary2oaded ! ",uthorsCalcMacros" % Then 9asic2ibraries . 2oad2ibrary ! ",uthorsCalcMacros" %

0nd 6f +umberFive = +umberFive;6mplementation !%0nd Function

E$ /ave, close, and reopen the Calc document. This time, the+umberFive#$ unction works.

Passing arguments to a macroTo illustrate a unction that accepts arguments, we will write a macro

that calculates the sum o its arguments that are positive —

it willignore arguments that are less than Hero #see -isting & $.-isting &. Positive/um calculates the sum o the positive arguments.

Function Positive um !:ptional 3% #im The um ,s #ouble #im i7o( ,s 6nteger #im iCol ,s 6nteger

The um = *.* 6f +:T 6sMissing ! 3% Then 6f +:T 6s,rray ! 3% Then 6f 3 < * Then The um = 3 0lse For i7o( = 29ound ! 34 &% To U9ound ! 34 &% For iCol = 29ound ! 34 % To U9ound ! 34 % 6f 3! i7o( 4 iCol % < * Then The um = The um 3! i7o( 4 iCol % +e3t +e3t 0nd 6f 0nd 6f

Positive um = The um0nd Function

The macro in -isting & demonstrates a couple o important techni9ues.<$ The argument @ is optional. I the argument is not optional and it

is called without an argument, ;;o prints a warning messageever! time the macro is called. I Calc calls the unction man!times, then the error is displa!ed man! times.

"$ Is3issing checks that an argument was passed be ore theargument is used.

2rite !our own unctions <

Page 14: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 14/18

$ IsArra! checks to see i the argument is a single value, or anarra!. For e@ample, JPositive/um#>$ or JPositive/um#A=$. In the

irst case, the number > is passed as an argument, and in thesecond case, the value o cell A= is passed to the unction.

=$ I a range is passed to the unction, it is passed as a two8dimensional arra! o values or e@ample, JPositive/um#A"4:&$.-:ound and :ound are used to determine the arra! bounds thatare used. Although the lower bound is one, it is considered sa erto use -:ound in case it changes in the uture.

Tip

The macro in -isting & is care ul and checks to see i theargument is an arra! or a single argument. The macro does not

veri ! that each value is numeric. )ou ma! be as care ul as !oudesire. The more things !ou check, the more robust the macro is,

and the slower it runs.

Passing one argument is as eas! as passing two4 add another argumentto the unction de inition #see -isting E $. 2hen calling a unction withtwo arguments, separate the arguments with a semicolon or e@ample,JTest3a@# 8=$.-isting E. Test3a@ accepts two arguments and returns the larger othe two.

Function TestMa3 ! 34 y% 6f 3 <= y Then TestMa3 = 3 0lse TestMa3 = y 0nd 6f0nd Function

Arguments are passed as values

Arguments passed to a macro rom Calc are alwa!s values. It is notpossible to know what cells, i an!, are used. For e@ample,JPositive/um#A $ passes the value o cell A , and Positive/um has nowa! o knowing that cell A was used. I !ou must know which cells arere erenced rather than the values in the cells, pass the range as astring, parse the string, and obtain the values in the re erenced cells.

Writing macros that act like built in functions

Although Calc inds and calls macros as normal unctions, the! do notreall! behave as built8in unctions. For e@ample, macros do not appear

<= Calc 3acros

Page 15: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 15/18

in the unction lists. It is possible to write unctions that behave asregular unctions b! writing an Add8In. 1owever, this is an advancedtopic that is not covered heresee http4**wiki.services.openo ice.org*wiki*/impleCalcAddIn .

Accessing cells directly)ou can access the ;;o internal obLects directl! to manipulate a Calcdocument. For e@ample, the macro in -isting > adds the values in cellA" rom ever! sheet in the current document. ThisComponent is set b!/tar:asic when the macro starts to re erence the current document. ACalc document contains sheets4 ThisComponent.get/heets#$. segetCell:!Position#col, row$ to return a cell at a speci ic row andcolumn.-isting >. Add cell A" in ever! sheet.

Function umCells,ll heets !% #im The um ,s #ouble #im i ,s integer #im o heets #im o heet #im oCell

o heets = ThisComponent . get heets !%

For i = * To o heets . getCount !% - & o heet = o heets . get9y6nde3 ! i % oCell = o heet . getCell9yPosition ! *4 &% > ?etCell , The um = The um oCell . get)alue !% +e3t umCells,ll heets = The um0nd Function

Tip

A cell obLect supports the methods get alue#$, get/tring#$, andgetFormula#$ to get the numerical value, the string value, or the

ormula used in a cell. se the corresponding set unctions to setappropriate values.

se o/heet.getCell ange:!+ame#MA"M$ to return a range o cells b!name. I a single cell is re erenced, then a cell obLect is returned. I acell range is given, then an entire range o cells is returned #see -isting? $. +otice that a cell range returns data as an arra! o arra!s, which ismore cumbersome than treating it as an arra! with two dimensions asis done in -isting & .

Accessing cells directl! <&

Page 16: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 16/18

-isting ?. Add cell A"4C& in ever! sheet Function umCells,ll heets !% #im The um ,s #ouble #im i7o( ,s 6nteger4 iCol ,s 6nteger4 i ,s 6nteger #im o heets 4 o heet 4 oCells

#im o7o( !%4 o7o(s !% o heets = ThisComponent . get heets !%

For i = * To o heets . getCount !% - & o heet = o heets . get9y6nde3 ! i % oCells = o heet . getCell7ange9y+ame ! ", 5C'" % 70M get#ata,rray!% returns the data as variant so strings 70M are also returned. 70M get#ata!% returns data data as type #ouble4 so only

70M numbers are returned. o7o(s !% = oCells . get#ata !%

For i7o( = 29ound ! o7o(s !%% To U9ound ! o7o(s !%% o7o( !% = o7o(s ! i7o( % For iCol = 29ound ! o7o( !%% To U9ound ! o7o( !%% The um = The um o7o( ! iCol % +e3t +e3t +e3t umCells,ll heets = The um0nd Function

Tip 2hen a macro is called as a Calc unction, the macro cannotmodi ! an! value in the sheet rom which the macro was called.

!ortingConsider sorting the data in Figure <? . First, sort on column :descending and then column A ascending.

Figure <?4 /ort column : descending andcolumn A ascending.

<E Calc 3acros

Page 17: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 17/18

The e@ample in -isting ( , however, demonstrates how to sort on twocolumns.-isting (. /ort cells A<4C& on /heet <.

ub ort7ange #im o heet > Calc sheet containing data to sort. #im oCell7ange > #ata range to sort.

70M ,n array of sort fields determines the columns that are 70M sorted. This is an array (ith t(o elements4 * and &. 70M To sort on only one column4 use5 70M #im o ortFields!*% ,s +e( com.sun.star.util. ortField #im o ortFields ! &% ,s +e( com. sun . star . util . ortField

70M The sort descriptor is an array of properties. 70M The primary property contains the sort fields.

#im o ort#esc ! *% ,s +e( com. sun . star . beans . Property)alue 70M ?et the sheet named " heet&" o heet = ThisComponent . heets . get9y+ame ! " heet&" %

70M ?et the cell range to sort oCell7ange = o heet . getCell7ange9y+ame ! ",&5C'" %

70M elect the range to sort. 70M The only purpose (ould be to emphasi@e the sorted data. >ThisComponent.getCurrentController.select!oCell7ange%

70M The columns are numbered starting (ith *4 so 70M column , is *4 column 9 is &4 etc. 70M ort column 9 !column &% descending. o ortFields ! *%.Field = & o ortFields ! *%. ort,scending = F,2 0

70M 6f column 9 has t(o cells (ith the same value4 70M then use column , ascending to decide the order. o ortFields ! &%.Field = * o ortFields ! &%. ort,scending = True

70M etup the sort descriptor. o ort#esc ! *%.+ame = " ortFields" o ort#esc ! *%.)alue = o ortFields !%

70M ort the range. oCell7ange . ort ! o ort#esc !%%0nd ub

/orting <>

Page 18: Macros en Calc de Open Oxygen

8/20/2019 Macros en Calc de Open Oxygen

http://slidepdf.com/reader/full/macros-en-calc-de-open-oxygen 18/18

ConclusionThis chapter provides a brie overview on how to create libraries andmodules, using the macro recorder, using macros as Calc unctions,and writing !our own macros without the macro recorder. ach topicdeserves at least one chapter, and writing !our own macros or Calccould easil! ill an entire book. In other words, this is Lust thebeginning o what !ou can learnN

<? Calc 3acros