Calc Guide

Chapter Calc Macros
Automating repetitive tasks
This PDF is designed to be read onscreen, two pages at a time. If you want to print a copy, your PDF viewer should have an option for printing two pages on one sheet of paper, but you may need to start with page 2 to get it to print facing pages correctly. (Print this cover page separately.

12

Copyright This document is !opyright © 2""#$2"%" by its contributors as listed in the section titled Authors. version . &ou may distribute it and'or modify it under the terms of either the ()* (eneral Public +icense.org/english/userguide3/published/ .org7 Please direct any comments or suggestions about this document to4 authors6documentation. 9ased on :pen:ffice.. version .2..openoffice." or later. 5andrew6pitonya. or the !reative !ommons -ttribution +icense. -ll trademar.org Publication date and software version Published 8 0une 2"%". or later. You can download an editable version of this document from http://oooauthors. Authors -ndrew Pitonya. (ary /chnabl 0ean 1ollis 2eber !laire 2ood Feedback 3aintainer4 -ndrew Pitonya.s within this guide belong to their legitimate owners..org .

.............................%...............................%8 /orting...................................................................................................%8 -ccessing cells directly.................................................................................................. 2rite your own functions................................................................ .... 2 Introduction.................%? Calc Macros 3 .................................................................................................................................................................%# 2riting macros that act li.. *sing the macro recorder...................%% Passing arguments to a macro..< *sing a macro as a function....................................................................... -rguments are passed as values........................................................................................................Contents !opyright..........e built=in functions.............................. %> !onclusion............................................................

. and copy the value to the clipboard. The Eecord 3acro dialog is displayed with a stop recording button. The following steps create a macro that performs paste special with multiply.org using the macro recorder. 2 Dnter numbers into a sheet.Introduction . -n eAample is shown here without the eAplanations in the Getting tarted guide. The :pen:ffice. 3acros are especially useful to repeat a tas.eystro. !igure $: top recording button % Calc Macros ..es that are stored for later use. the same way over and over again. which contains the number . !igure ": #nter numbers . This chapter briefly discusses common problems related to macro programming using !alc.org (::o macro language is very fleAible.. /elect the range -%4!. # *se Tools > Macros > Record Macro to start the macro recorder. of the Getting tarted guide ((etting /tarted with 3acros provides a basis for understanding the general macro capabilities in :pen:ffice.macro is a saved se@uence of commands or . % :pen a new spreadsheet.. -n eAample of a simple macro is one that BtypesC your address. Using the macro recorder !hapter %. /elect cell -.s. allowing automation of both simple and compleA tas.

For this eAample. The cells are now multiplied by . Stop Recording to stop the macro recorder. !igure 3: &aste pecial dialog > /et the operation to Multiply and clic. but this is not necessary.8 *se Edit > Paste Special to open the Paste /pecial dialog. DAisting documents show a library named /tandard. the current !alc document is (ntitled ". &ou can create a new library to contain the macro. This library is not created until the document is saved or the library is needed. OK. ? /elect the current document (see Figure # . !igure %: Cells multiplied b' 3 < !lic. The :pen:ffice. so at this point your new document does not contain a library. (sing the macro recorder ) .org 9asic 3acros dialog opens..

Calc Macros . In the )ew 3odule dialog.1 My Macros OpenOffice. type a name for the new module or leave the name as 3odule%. If no libraries eAist. /elect the newly created 3odule%. . %% !lic.org Macros " Open documents $ Create new library 5 Create new module in library ! Macros in selected library # Current document % Expand/collapse list !igure ): &arts of the *pen*ffice. then the /tandard library is automatically created and used. and clic. New Module.org +asic Macros dialog %" !lic. (/ee Figure 8. type PasteMultiply in the Macro name boA at the upper left. Save. OK to create a new module named 3odule%.

Frame dispatcher = createUno ervice!"com.star.+ame = "Flags" args&!*%.uno56nsertContents"4 ""4 *4 args&!%% end sub (sing the macro recorder .)alue = 1 dispatcher. -isting ".)alue = false args&!'%.s2in/" args&!1%.%.!igure ." args&!&%.e3ecute#ispatch!document4 ".+ame = ".sun.CurrentController.: elect the module and name the macro The created macro is saved in 3odule% of the /tandard library in the (ntitled " document.star. sub PasteMultiply rem -------------------------------------------------------------rem define variables dim document as object dim dispatcher as object rem -------------------------------------------------------------rem get access to the document document = ThisComponent.+ame = "MoveMode" args&!'%. .+ame = " /ip0mptyCells" args&!.)alue = args&!.sun.)alue = false args&!-%.)alue = false args&!1%.beans.frame. +isting % shows the contents of the macro.+ame = "FormulaCommand" args&!&%. &aste special with multipl'.Property)alue args&!*%.)alue = ".#ispatch$elper"% rem -------------------------------------------------------------dim args&!'% as ne( com.+ame = "Transpose" args&!-%.%.

ods.org Macros contains macros included with ::o and should not be changed.: *pen*ffice. &rite your own functions !alc can call macros as !alc functions. *pen*ffice. :n the +ibraries tab.3ore detail on recording macros is provided in !hapter %. M' Macros contains macros that you write or add to ::o. 3ore detail is also provided in the following sections. !lic. but not as related to recording macros. The Macro from boA lists available macro library containers including currently open ::o documents.org 9asic 3acros dialog. Organizer to open the :pen:ffice. *se the following steps to create a simple macro4 % !reate a new !alc document named CalcTestMacros. / Calc Macros . select the document to contain the macro. !igure .org 9asic 3acro :rganiGer dialog. 2 *se Tools > Macros > Organize Macros > OpenO ice!org "asic to open the :pen:ffice.org +asic Macros dialog . ((etting /tarted with 3acros in the Getting tarted guideF we recommend you read it if you have not already done so.

but the dialog may show only a portion of the name. !igure 1: 2ew -ibrar' dialog # Dnter a descriptive library name (such as -uthors!alc3acros and clic. OK to create the library. The new library name is shown the library list.org +asic Macro *rgani0er . !lic. New to open the )ew +ibrary dialog.!igure /: *pen*ffice. !igure "3: 4he librar' is shown in the organi0er 5rite 'our own functions 1 .

which returns the number five. variables are automatically defined at first use as type Hariant. Edit to edit the library. The Option Explicit statement forces all variables to be declared before they are used. < /ave the modified 3odule%. !alc automatically creates a module named 3odule% and a macro named 3ain. -isting $. !igure "": +asic 6ntegrated 7evelopment #nvironment 867#9 > 3odify the code so that it is the same as that shown in +isting 2. 70M 88888 9. If :ption DAplicit is omitted.The important addition is the creation of the NumberFive function.8 /elect -uthors!alc3acros and clic. 6C :ption 03plicit ub Main 0nd ub 88888 Function +umberFive!% +umberFive = ' 0nd Function "3 Calc Macros . !unction that returns five.

or the one shown in Figure %. you can enter =NumberFive() and !alc clearly shows =N M!E"F#$E(). If you do not eApect a document to contain a macro. $isa#le Macros in case the macro is a virus. !igure "3: **o warns 'ou that a document contains macros 5rite 'our own functions "" . In Figure %2. it is safer to clic. close it.Using a macro as a function *sing the newly created !alc document CalcTestMacros. enter the formula =NumberFive() (see Figure %2 . Depending on your settings in Tools > Options > OpenO ice!org > Security > Macro Security. or !alc will not allow any macros to be run inside the document. !alc will dislay the warning shown in Figure %. !alc finds the macro and calls it.. !igure "$: (se the 2umber!ive89 Macro as a Calc function 'ip Function names are not case sensitive.ods. &ou will need to clic. Ena#le Macros. /ave the !alc document. and open it again.

*nfortunately. !alc can no longer find the function.org 9asic 3acros dialog (see Figure %8 . *se Tools > Macros > Organize Macros > OpenO ice!org "asic to open the :pen:ffice. +ibraries in *pen*ffice. the cells containing I)umberFive( are in error. DApand !alcTest3acros and find -uthors!alc3acros. The icon for a loaded library is a different color from the icon for a library that is not loaded.ed for an appropriately named function (see Figure > . %lose to close the dialog. the eApansion symbol (usually a plus or a triangle neAt to -uthors!alc3acros to load the library. !alc does not recalculate cells in error unless you edit them or somehow change them. then when the document loads. !lic. The icon changes color to indicate that the library is now loaded. The /tandard library is automatically loaded when the document is opened. !alc does not contain a function named )umberFive( . M' Macros. which is not automatically loaded when the document is opened. If the macro is large or if there are many macros. )o other library is automatically loaded.org Macros. !igure "): 4he function is gone 2hen a document is created and saved.s all opened and visible macro libraries for the function. The )umberFive( function is stored in the -uthors!alc3acros library. and the !alc document are chec. The usual solution is to store macros used as functions in the /tandard library.!igure "%: 5arning if macros are disabled If you choose to disable macros. "$ Calc Macros . so it chec. it automatically contains a library named /tandard. !lic.

The stub macro loads the library containing the implementation and then calls the implementation. # !reate a macro in the /tandard library that calls the implementation function (see +isting . Edit to open the macro for editing. The new macro loads the -uthors!alc3acros library if it is not already loaded.org 9asic 3acros dialog. % *se Tools > Macros > Organize Macros > OpenO ice!org "asic to open the :pen:ffice. OK. In the 9asic IDD (see Figure %% . Change the name of 2umber!ive to 2umber!ive:6mplementation Function NumberFive%#mplementation() NumberFive%#mplementation() = & End Function . the Select Macro button to open the :pen:ffice. !igure ". New to create a new module.a stub with the desired name is stored in the /tandard library.: elect a macro and click #dit 2 !hange the name of )umberFive to )umberFiveJImplementation (see +isting . and then calls the implementation function.org 9asic 3acros dialog (see Figure %8 . Dnter a meaningful name such as !alcFunctions and clic. /elect the )umberFive macro and clic. /elect the /tandard library in the !alcTest3acros document and clic. . . hover the mouse cursor over the toolbar buttons to display the tool tips. ::o automatically creates a macro named 3ain and opens the module for editing. !lic. . 5rite 'our own functions "3 . -isting 3.

% 6f 3!i7o(4 iCol% < * Then The um = The um = 3!i7o(4 iCol% +e3t +e3t 0nd 6f 0nd 6f Positive um = The um 0nd Function The macro in +isting # demonstrates a couple of important techni@ues4 % The argument x is optional.6mplementation!% 0nd Function Passing arguments to a macro To illustrate a function that accepts arguments.2oad2ibrary!". -isting %.s 6nteger #im iCol .s 6nteger The um = *. "% Calc Macros . Function +umberFive!% 6f +:T 9asic2ibraries.uthorsCalcMacros"% Then 9asic2ibraries.s that an argument was passed before the argument is used. 2 #sMissin' chec.s #ouble #im i7o( . and reopen the !alc document. -isting ). then the error is displayed many times.% To U9ound!34 . &ositive um calculates the sum of the positive arguments. the )umberFive( function wor. we will write a macro that calculates the sum of its arguments that are positive —it will ignore arguments that are less than Gero (see +isting # .rray!3% Then 6f 3 < * Then The um = 3 0lse For i7o( = 29ound!34 &% To U9ound!34 &% For iCol = 29ound!34 .8 /ave. This time.s. If !alc calls the function many times. ::o prints a warning message every time the macro is called. close. Function Positive um!:ptional 3% #im The um .uthorsCalcMacros"% 0nd 6f +umberFive = +umberFive.* 6f +:T 6sMissing!3% Then 6f +:T 6s.is2ibrary2oaded!". If the argument is not optional and it is called without an argument. Change the name of 2umber!ive to 2umber!ive:6mplementation.

'ip Passing one argument is as easy as passing two4 add another argument to the function definition (see +isting 8 .s to see if the argument is an array or a single argument. or an array.-!&). . =Positive)um((/) passes the value of cell -. the number > is passed as an argument. pass the range as a string.now what cells. 4estMa.e. and in the second case. it is considered safer to use .nowing that cell -. The more things you chec. For eAample. &ou may be as careful as you li.!ound in case it changes in the future. was used. and Positive/um has no way of .. -lthough the lower bound is one. are used. For eAample. In the first case. Function TestMa3!34 y% 6f 3 <= y Then TestMa3 = 3 0lse TestMa3 = y 0nd 6f 0nd Function Arguments are passed as values -rguments passed to a macro from !alc are always values. . =Positive)um((. 2hen calling a function with two arguments. separate the arguments with a semicolonF for eAample. The macro in +isting # is careful and chec. -isting . and the slower it runs. #s(rray chec. if any.!ound and !ound are used to determine the array bounds that are used. and obtain the values in the referenced cells. The macro does not verify that each value is numeric. accepts two arguments and returns the larger of the two.. It is not possible to .. =Positive)um(*) or =Positive)um((+). parse the string. is passed to the function. the value of cell -. If a range is passed to the function. 5rite 'our own functions ") . the more robust the macro is.now which cells are referenced rather than the values in the cells.s to see if the argument is a single value. it is passed as a two= dimensional array of valuesF for eAample. =TestMax(/& 0+).. If you must .

*se o)1eet. The um = The um = oCell. and 'etFormula() to get the numerical value.org'wi. the string value.s #ouble #im i .& o heet = o heets.i'/imple!alc-ddIn.s integer #im o heets #im o heet #im oCell o heets = ThisComponent. ". T1isComponent is set by /tar9asic when the macro starts to reference the current document. If a single cell is referenced.get9y6nde3!i% oCell = o heet. this is an advanced topic that is not covered hereF see http4''wi. )otice that a cell range returns data as an array of arrays.'et)1eets(). macros do not appear in the function lists. !alc document contains sheets4 T1isComponent.'etCell"an'e!yName(4(.openoffice. Function umCells.get heets!% For i = * To o heets.i. It is possible to write functions that behave as regular functions by writing an -dd=In. For eAample. 'et)trin'(). *se the corresponding set functions to set appropriate values. then a cell obKect is returned.getCount!% . Accessing cells directly &ou can access the ::o internal obKects directly to manipulate a !alc document.4) to return a range of cells by name. or the formula used in a cell. -isting . the macro in +isting > adds the values in cell -2 from every sheet in the current document. For eAample. then an entire range of cells is returned (see +isting < . *se 'etCell!yPosition(col2 ro3) to return a cell at a specific row and column. Calc Macros .ll heets = The um 0nd Function 'ip . 1owever.ll heets!% #im The um .getCell9yPosition!*4 &% > ?etCell .services. Add cell A$ in ever' sheet.&riting macros that act like built(in functions -lthough !alc finds and calls macros as normal functions.cell obKect supports the methods 'et$alue().get)alue!% +e3t umCells. If a cell range is given... they do not really behave as built=in functions.

getCount!% .s 6nteger #im o heets4 o heet4 oCells #im o7o(!%4 o7o(s!% o heets = ThisComponent. -isting /.rray!% returns the data as variant so strings 70M are also returned. !igure ".: orting ort column + descending and column A ascending ".& o heet = o heets. the macro cannot modify any value in the sheet from which the macro was called.get9y6nde3!i% oCells = o heet.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!% #im The um . .s #ouble #im i7o( .getCell7ange9y+ame!". o7o(s!% = oCells. sort on column 9 descending and then column . 70M get#ata!% returns data data as type #ouble4 so only 70M numbers are returned. Add cell A$:C) in ever' sheet Function umCells..get heets!% For i = * To o heets.which is more cumbersome than treating it as an array with two dimensions as is done in +isting #.s 6nteger4 i . )orting !onsider sorting the data in Figure %>.5C'"% 70M get#ata. First.ll heets = The um 0nd Function 'ip 2hen a macro is called as a !alc function.s 6nteger4 iCol .ascending.

select!oCell7ange% 70M The columns are numbered starting (ith *4 so 70M column . #im o ort#esc!*% . demonstrates how to sort on two columns. ort.+ame = " ortFields" o ort#esc!*%. .sun. ub ort7ange #im o heet #im oCell7ange 70M 70M 70M 70M #im > Calc sheet containing data to sort. oCell7ange.sun.scending = True 70M etup the sort descriptor. This is an array (ith t(o elements4 * and &. 70M The only purpose (ould be to emphasi@e the sorted data. ascending to decide the order.n array of sort fields determines the columns that are sorted.Property)alue 70M ?et the sheet named " heet&" o heet = ThisComponent. ort!o ort#esc!%% 0nd ub "/ Calc Macros . heets.s +e( com.util. ortField o ortFields!&% . >ThisComponent. To sort on only one column4 use5 #im o ortFields!*% .scending = F.getCurrentController. ort cells A":C) on heet ". o ortFields!*%.The eAample in +isting ?.star. o ortFields!&%.2 0 70M 6f column 9 has t(o cells (ith the same value4 70M then use column .s +e( com.star. 70M ort column 9 !column &% descending. is *4 column 9 is &4 etc.s +e( com. however.)alue = o ortFields!% 70M ort the range.get9y+ame!" heet&"% 70M ?et the cell range to sort oCell7ange = o heet.sun.star. > #ata range to sort. o ort#esc!*%.Field = & o ortFields!*%. -isting 1.Field = * o ortFields!&%.getCell7ange9y+ame!".&5C'"% 70M elect the range to sort.util.beans. ort. ortField 70M The sort descriptor is an array of properties. 70M The primary property contains the sort fields.

and writing your own macros without the macro recorder. using the macro recorder..Conclusion This chapter provides a brief overview on how to create libraries and modules. and writing your own macros for !alc could easily fill an entire boo. Dach topic deserves at least one chapter. using macros as !alc functions. In other words. this is Kust the beginning of what you can learnL Conclusion "1 .

Sign up to vote on this title
UsefulNot useful