Openoffice.org Macros Explained (2004)(Pitonyak)_en

499

Transcript of Openoffice.org Macros Explained (2004)(Pitonyak)_en

OpenOffice.org Macros Explained

Andrew Douglas Pitonyak

Hentzenwerke Publishing

Published by: Hentzenwerke Publishing 980 East Circle Drive Whitefish Bay WI 53217 USA Hentzenwerke Publishing books are available through booksellers and directly from the publisher. Contact Hentzenwerke Publishing at: 414.332.9876 414.332.9463 (fax) www.hentzenwerke.com [email protected] OpenOffice.org Macros Explained By Andrew Douglas Pitonyak Technical Editors: C. Robert Pearsall, Jean Hollis Weber, and Amy Boyer Copy Editor: Jeana Frazier Cover Art: Telling Stories by Todd Gnacinski, Milwaukee, WI Copyright 2004 by Andrew Douglas Pitonyak All other products and services identified throughout this book are trademarks or registered trademarks of their respective companies. They are used throughout this book in editorial fashion only and for the benefit of such companies. No such uses, or the use of any trade name, is intended to convey endorsement or other affiliation with this book. All rights reserved. No part of this book, or the e-book files available by download from Hentzenwerke Publishing, may be reproduced or transmitted in any form or by any means, electronic, mechanical photocopying, recording, or otherwise, without the prior written permission of the publisher, except that program listings and sample code files may be entered, stored and executed in a computer system. The information and material contained in this book are provided as is, without warranty of any kind, express or implied, including without limitation any warranty concerning the accuracy, adequacy, or completeness of such information or material or the results to be obtained from using such information or material. Neither Hentzenwerke Publishing nor the authors or editors shall be responsible for any claims attributable to errors, omissions, or other inaccuracies in the information or material contained in this book. In no event shall Hentzenwerke Publishing or the authors or editors be liable for direct, indirect, special, incidental, or consequential damages arising out of the use of such information or material. ISBN: 1-930919-51-4 Manufactured in the United States of America.

iii

Our Contract with You, the ReaderIn which we, the folks who make up Hentzenwerke Publishing, describe what you, the reader, can expect from this book and from us.

Hi there! Ive been writing professionally (in other words, eventually getting a paycheck for my scribbles) since 1974, and writing about software development since 1992. As an author, Ive worked with a half-dozen different publishers and corresponded with thousands of readers over the years. As a software developer and all-around geek, Ive also acquired a library of more than 100 computer and software-related books. Thus, when I donned the publishers cap seven years ago to produce the 1997 Developers Guide, I had some pretty good ideas of what I liked (and didnt like) from publishers, what readers liked and didnt like, and what I, as a reader, liked and didnt like. Now, with our new titles for 2004, were entering our seventh season. (For those who are keeping track, the 97 DevGuide was our first, albeit abbreviated, season, the batch of six Essentials for Visual FoxPro 6.0 in 1999 was our second, and, in keeping with the sports analogy, the books we published in 2000 through 2003 comprised our third and subsequent seasons.) John Wooden, the famed UCLA basketball coach, posited that teams arent consistent; theyre always getting betteror worse. Wed like to get better One of my goals for this season is to build a closer relationship with you, the reader. In order for us to do this, youve got to know what you should expect from us. You have the right to expect that your order will be processed quickly and correctly, and that your book will be delivered to you in new condition. You have the right to expect that the content of your book is technically accurate and up-to-date, that the explanations are clear, and that the layout is easy to read and follow without a lot of fluff or nonsense. You have the right to expect access to source code, errata, FAQs, and other information thats relevant to the book via our Web site. You have the right to expect an electronic version of your printed book to be available via our Web site. You have the right to expect that, if you report errors to us, your report will be responded to promptly, and that the appropriate notice will be included in the errata and/or FAQs for the book.

Naturally, there are some limits that we bump up against. There are humans involved, and they make mistakes. A book of 500 pages contains, on average, 150,000 words and several megabytes of source code. Its not possible to edit and re-edit multiple times to catch every last misspelling and typo, nor is it possible to test the source code on every permutation of development environment and operating systemand still price the book affordably. Once printed, bindings break, ink gets smeared, signatures get missed during binding. On the delivery side, Web sites go down, packages get lost in the mail. Nonetheless, well make our best effort to correct these problemsonce you let us know about them. In return, when you have a question or run into a problem, we ask that you first consult the errata and/or FAQs for your book on our Web site. If you dont find the answer there, please e-mail us at [email protected] with as much information and detail as possible, including 1) the steps to reproduce the problem, 2) what happened, and 3) what you expected to happen, together with 4) any other relevant information.

iv

Id like to stress that we need you to communicate questions and problems clearly. For example Bad reports: Your downloads dont work. Your Web site is down. The code in Chapter 10 caused an error. These types of complaints dont contain enough information for us to help you. Good reports: I get a 404 error when I click on the Download Source Code link on www.hentzenwerke.com/book/downloads.html. I performed the following steps to run the source code program DisplayTest.PRG in Chapter 10, and I received an error that said Variable m.liCounter not found. Now this is something we can help you with. Well do our best to get back to you within a couple of days, either with an answer or at least an acknowledgment that weve received your inquiry and that were working on it. On behalf of the authors, technical editors, copy editors, layout artists, graphical artists, indexers, and all the other folks who have worked to put this book in your hands, Id like to thank you for purchasing this book, and I hope that it will prove to be a valuable addition to your technical library. Please let us know what you think about this book were looking forward to hearing from you. As Groucho Marx once observed, Outside of a dog, a book is a mans best friend. Inside of a dog, its too dark to read. Whil Hentzen Hentzenwerke Publishing July 2004

v

List of ChaptersChapter 1: Getting Started Chapter 2: Language Constructs Chapter 3: Numerical Routines Chapter 4: Array Routines Chapter 5: Date Routines Chapter 6: String Routines Chapter 7: File Routines Chapter 8: Miscellaneous Routines Chapter 9: Universal Network Objects Chapter 10: UNO and the Dispatcher Chapter 11: StarDesktop Chapter 12: Generic Document Methods Chapter 13: Writer Documents Chapter 14: Calc Documents Chapter 15: Draw and Impress Documents Chapter 16: Library Management Chapter 17: Dialogs and Controls Chapter 18: Sources of Information 1 19 73 91 101 113 127 145 169 189 203 229 265 325 375 407 413 455

vi

vii

Table of ContentsOur Contract with You, the Reader List of Chapters Acknowledgments About the Authors How to Download the Files Icons Used in this Book iii v xv xvii xix xxi

Chapter 1: Getting StartedStoring a macro in a document library Step 1. Create a library Step 2. Create a module Step 3. Enter your first macro Storing a macro in the application library The Integrated Development Environment Using breakpoints Library management How libraries are stored Application libraries Document libraries Using the Macro Organizer Renaming modules and libraries Adding libraries Conclusion

11 2 4 5 8 9 12 12 13 13 14 15 15 16 17

Chapter 2: Language ConstructsCompatibility with Visual Basic Variables Constant, subroutine, function, label, and variable names Declaring variables Assigning values to variables Boolean variables are True or False Numeric variables String variables contain text Date variables Create your own data types A new way to declare variables Object variables Variant variables Constants The With statement Arrays Changing the dimension of an array The unexpected behavior of arrays Subroutines and functions Arguments Recursive routines Scope of variables, subroutines, and functions Local variables defined in a subroutine or function Variables defined in a module

1920 21 21 21 23 23 24 27 28 29 30 31 31 32 32 33 35 37 38 39 42 42 43 43

viii

Operators Mathematical and string operators Logical and bitwise operators Comparison operators Flow control Define a label as a jump target GoSub GoTo On GoTo and On GoSub If Then Else IIf Choose Select Case While ... Wend Do ... Loop For ... Next Exit Sub and Exit Function Error handling using On Error Ignore errors with On Error Resume Next Clear an error handler with On Error GoTo 0 Specify your own error handler with On Error GoTo Label Error handlerswhy use them? Conclusion

45 46 49 53 54 54 55 55 56 56 57 57 58 62 62 64 65 65 67 67 67 69 71

Chapter 3: Numerical RoutinesTrigonometric functions Rounding errors and precision Mathematical functions Numeric conversions Number to string conversions Simple formatting Other number bases, hexadecimal, octal, and binary Random numbers Conclusion

7374 76 78 80 84 84 85 88 89

Chapter 4: Array RoutinesArray() quickly builds a one-dimensional array with data DimArray creates empty multi-dimensional arrays Change the dimension of an array Array to String and back again Array inspection functions Conclusion

9192 93 94 95 96 99

Chapter 5: Date RoutinesRetrieve the current date and time Dates, numbers, and strings Locale formatted dates ISO 8601 dates Extract each part of a date Assembling dates from components Measuring elapsed time over short intervals How fast does this run? A real-world example! Long time intervals and special dates Conclusion

101101 102 103 105 106 107 108 109 111 112

ix

Chapter 6: String RoutinesASCII and Unicode values Standard string functions Substrings Aligning strings with LSet and RSet Fancy formatting with Format Converting data to a string

113114 117 119 121 122 125 126

Conclusion

Chapter 7: File RoutinesUsing URL notation to specify a file Directory manipulation functions File manipulation functions File attributes, bitmasks, and binary numbers Obtaining a directory listing Open a file Information about open files Reading and writing data Conclusion

127128 129 130 132 133 135 137 139 144

Chapter 8: Miscellaneous RoutinesDisplay and color Determine the GUI type Determine pixel size (in twips) Use color functions Flow control Return an argument Pause or end the macro Dynamic Link Libraries Calling external applications Dynamic Data Exchange User input and output Simple output Multi-line output Prompting for input Error-related routines Miscellaneous routines Inspection and identification of variables Routines you should not use and other curiosities Conclusion

145145 145 146 147 148 148 149 150 151 152 153 153 154 157 157 158 161 166 167

Chapter 9: Universal Network ObjectsBase types and structures UNO interface UNO service Context Inspecting Universal Network Objects A few considerations with UNO variables Built-in global UNO variables Creating UNO values for OOo internals Finding objects and properties UNO listeners Your first listener A complete listener: selection change listener Creating a UNO dialog Conclusion

169170 171 172 173 173 177 177 180 180 181 182 182 184 187

x

Chapter 10: UNO and the DispatcherThe environment Two different methods to control OOo Finding dispatch commands Global dispatch commands Calc dispatch commands Chart dispatch commands Draw dispatch commands Math dispatch commands Writer dispatch commands Writing a macro using the dispatcher Conclusion

189190 190 191 192 195 197 197 199 199 201 201

Chapter 11: StarDesktopThe Frame service The XIndexAccess interface Find frames with FrameSearchFlag constants The XEventBroadcaster interface The XDesktop interface Closing the desktop and contained components Enumerating components using XEnumerationAccess Current component Current frame The XComponentLoader interface Named parameters Error handling while loading a document Conclusion

203203 204 204 206 206 206 207 208 210 210 213 227 227

Chapter 12: Generic Document MethodsServices and interfaces Getting and setting properties: XPropertySet Document user fields: XDocumentInfoSupplier List event listeners: XEventsSupplier Link targets: XLinkTargetSupplier Accessing view data: XViewDataSupplier Close a document: XCloseable Draw Pages: XDrawPagesSupplier The model: XModel Saving a document: XStorable Manipulating styles: XStyleFamiliesSupplier Dealing with locale Printing a document: XPrintable Printing Writer documents Printing Calc documents Creating services: XMultiServiceFactory Document settings Conclusion

229229 231 233 233 234 236 236 237 240 243 245 249 255 258 260 261 263 264

Chapter 13: Writer DocumentsBasic building blocks Primary text content: the XText interface Text ranges: the XTextRange interface Inserting simple text Text content: the TextContent service Enumerating paragraphs Paragraph properties

265266 266 267 268 268 269 270

xi

Character properties Enumerating text sections (paragraph portions) Cursors View cursors Text (non-view) cursors Using cursors to traverse text Accessing content using cursors Selected text Is text selected? Selected text: Which end is which? Selected text framework Remove empty spaces and lines: A larger example Selected text, closing thoughts Search and replace Searching selected text or a specified range Searching for all occurrences Searching and replacing Advanced search and replace Text content Text tables Using the correct text object Methods and properties Simple and complex tables Tables contain cells Using a table cursor Text fields Text master fields Creating and adding text fields Bookmarks Conclusion

276 280 282 282 283 284 287 289 289 290 291 293 295 296 297 297 300 300 303 303 305 306 308 309 310 312 318 320 323 323

Chapter 14: Calc DocumentsAccessing sheets Sheet cells contain the data Cell address Cell data Cell properties Cell annotations Sheet cell ranges Sheet cell range properties Sheet cell range services Searching and replacing Merging cells Retrieving, inserting, and deleting columns and rows Retrieving and setting data as an array Computing functions on a range Clearing cells and cell ranges Automatic data fill Array formulas Computing multiple functions on a range Cells with the same formatting Sorting Sheets Linking to an external spreadsheet Finding dependencies by using auditing functions Outlines Copying, moving, and inserting cells

325326 327 328 328 330 333 333 334 337 341 342 343 344 345 345 345 347 348 350 351 354 355 356 357 358

xii

Data pilot tables Sheet cursors Calc documents Named ranges Protecting documents and sheets Controlling recalculation Using Goal Seek Writing your own spreadsheet functions Using the current controller Selected cells General functionality Converting Excel macros Control Calc from Microsoft Office A better macro recorder Conclusion

359 364 366 366 367 367 367 368 369 369 372 373 374 374 374

Chapter 15: Draw and Impress DocumentsDraw pages Generic draw page Combining shapes Shapes Common properties Shape types Forms Presentations Presentation draw pages Presentation shapes Conclusion

375375 377 378 380 381 388 399 401 403 404 405

Chapter 16: Library ManagementAccessing libraries using OOo Basic Libraries contained in a document Writing an installer Conclusion

407407 410 411 412

Chapter 17: Dialogs and ControlsMy first dialog The Properties dialog Starting a dialog from a macro Assign an event handler Dialog and control paradigm Dialog and control similarities Dialog-specific methods The dialog model Controls Control button Check box Radio button Group box Fixed line control Combo box Text edit controls Image control Progress control List box control Scroll bar control

413413 415 416 417 418 418 420 421 422 423 425 426 427 427 427 429 440 440 441 442

xiii

Using the Step property for multi-page AutoPilot dialogs The object inspectora final example Utility subroutines and functions Creating a dialog at run time Listeners Obtaining the debug information Conclusion

444 444 444 447 450 450 453

Chapter 18: Sources of InformationHelp pages included with OpenOffice.org Macros included with OpenOffice.org Web sites Reference material Macro examples Miscellaneous http://api.openoffice.org/ Mailing lists and newsgroups How to find answers Conclusion

455455 455 456 456 456 456 457 457 459 459

Index

461

xiv

xv

AcknowledgmentsI dedicate this book to my wife, Michelle; you are my life, a precious gift from God. I appreciate your encouragement and support while writing this book. Without your support, this book would not exist. Thanks to C. Robert Pearsall, Jean Hollis Weber, and Amy Boyer for editing the technical content. Thanks to Jeana Frazier for copy edit and layout. A document is only as good as its editors. You were tireless and patient to the end. Whil Hentzen, I appreciate your gentle guidance through the process. I cannot imagine using another publisher. Mike Jones, thanks for keeping my computers running and convincing me that I should try OpenOffice.org. You are a brilliant man and an excellent friend! Thanks to Andreas Bregas, Mathias Bauer, Stephan Wunderlich, Carsten Driesner, Stephan Bergmann, Jrg Barfurth, Michael Hnnig, Duncan Foster, and the other developers at Sun Microsystems for taking the time to answer my many questions. Andreas, you were very tolerant with my direct questionsthank you. Thanks to Bernard Marcelly, Olivier Bietzer, Andrew Brown, Berend Cornelius, Birgit Kellner, Hal Vaughan, Hermann Kienlein, Hermann-Josef Beckers, Kelvin Eldridge, Laurent Godard, Marc Messeant, Niklas Nebel, Oliver Brinzing, Paul Sobolik, Robert Black Eagle, Sasa Kelecevic, Solveig Haugland, Tony Bloomfield, Vance Lankhaar, Paolo Mantovani, and the rest of the volunteers who have provided me with advice and examples. You truly demonstrate how and why open-source software survives. Thanks to my parents for encouraging me to follow my dreams. Andrew Douglas Pitonyak

xvi

xvii

About the AuthorsAndrew Douglas PitonyakAuthor Andrew Pitonyak is a Lead Software Engineer for Qwest Communications International Inc. He has been using OpenOffice.org since it was StarOffice 5 and he is the author of Andrews Macro Document (http://www.pitonyak.org). He has a Master of Science degree in computer science and another in mathematics. In his spare time, Andrew participates in the contemporary worship team at church, is a trained Stephen Minister and a professional puppeteer, works on his house, and spends time with his wife. He is an NRA certified firearms instructor, and he holds a General class amateur radio license. Andrew requests that if you are browsing this book at a bookstore, you should say very loudly, so that everyone can hear, Wow! I cant believe that they have this book! and then purchase two copies. You can reach Andrew at [email protected].

Jean Hollis WeberTechnical Editor Jean Hollis Weber has more than 20 years of experience planning, writing, editing, indexing, and testing user manuals and online help for computer software and hardware. She has worked for numerous organizations including the Commonwealth Scientific and Industrial Research Organisation (CSIRO), IBM Australia, and Lexmark International Australia, both alone on small projects and as a team member and team leader on large projects. A technical publications consultant for the past 10 years, Jean has worked with clients, written books, taught short courses in technical writing and editing, and presented parts of graduate and undergraduate courses at several Australian universities. She is active in the Society for Technical Communication (STC) Australia Chapter and other professional organizations. Her Web site, The Technical Editors Eyrie (http://www.jeanweber.com), won a Merit Award in the STC-Australia online communication competition in 2002.

C. Robert PearsallTechnical Editor C. Robert (Bob) Pearsall is President of AXON Research (www.axonresearch.com), a consultancy specializing in the use of information technology to improve business operations and to enhance the effectiveness of knowledge workers. He specializes in clinical research and regulatory operations for the pharmaceutical and biotechnology life sciences industry. His clients have included small specialty firms, biotechnology therapy manufacturers, and large pharmaceutical companies. He has developed regulatory operations and technologies, and assisted the FDA in its initiative to develop electronic submissions standards. Bobs recent projects include designing tracking databases for regulated clinical research operations, and validating a laboratory blood sample tracking system near Chon Buri, Thailand. When he is not busy pulling rabbits from hats and working miracles for his clients, he enjoys travel, photography, an occasional cigar, and a bit of wine or single-malt scotch. He has been avoiding participation in the bell choir at his church, and recently celebrated the 20th anniversary of his electrical engineering degree from MIT. He also holds a Master of Science degree in nuclear engineering and habitually speaks at a variety of industry conferences.

Amy BoyerTechnical Editor Amy Boyer is Electronic Manuscript Specialist at University of California Press, where she maintains its editing system. She is also a freelance writer and editor. She holds a B.A. in mathematics from Oberlin College and an M.A. in English from University of California Davis. In her spare time she volunteers for the California Native Plant Society, attempts to grow jicama (among other vegetables), meditates, and works on a novel.

xviii

xix

How to Download the FilesHentzenwerke Publishing generally provides two sets of files to accompany its books. The first is the source code referenced throughout the text. Note that some books do not have source code; in those cases, a placeholder file is provided in lieu of the source code in order to alert you of the fact. The second is the e-book version (or versions) of the book. Depending on the book, we provide e-books in either the compiled HTML Help (.CHM) format, Adobe Acrobat (.PDF) format, or both. Heres how to get them.

Both the source code and e-book file(s) are available for download from the Hentzenwerke Web site. In order to obtain them, follow these instructions: 1. 2. 3. Point your Web browser to www.hentzenwerke.com. Look for the link that says Download. A page describing the download process will appear. This page has two sections: Section 1: If you were issued a user name/password directly from Hentzenwerke Publishing, you can enter them into this page. Section 2: If you did not receive a user name/password from Hentzenwerke Publishing, dont worry! Just enter your e-mail alias and look for the question about your book. Note that youll need your physical book when you answer the question.

4.

A page that lists the hyperlinks for the appropriate downloads will appear.

Note that the e-book file(s) are covered by the same copyright laws as the printed book. Reproduction and/or distribution of these files is against the law. If you have questions or problems, the fastest way to get a response is to e-mail us at [email protected].

xx

xxi

Icons Used in this BookThroughout this book, the following icons are used to point out special notes, tips, bugs, warnings, and compatibility issues.

This note icon calls out information of special interest, related topics, or important notes that dont fit well into the flow of the text. This tip icon marks ideas for shortcuts, alternate ways of accomplishing tasks that can make your life easier or save time, or techniques that arent immediately obvious. This bug icon indicates known bugs within OpenOffice.org, the Developers Guide, or other sources. This warning icon indicates pitfalls to watch out for, such as commands that have the ability to delete every file on your computer, unexpected behavior, or common errors made by users. In many ways, OOo Basic is similar to Visual Basic. This compatibility icon identifies behaviors, syntax, and constraints that are different in OOo Basic than in the different versions of Visual Basic.

xxii

Chapter 1: Getting Started

1

Chapter 1 Getting StartedIn OpenOffice.org, macros and dialogs are stored in documents and libraries. The included integrated development environment (IDE) is used to create and debug macros. This chapter introduces the basic concepts of starting the IDE and creating macros by showing the steps to produce a simple macro, which displays the text Hello World on the screen.

A macro is a saved sequence of commands or keystrokes that are stored for later use. An example of a simple macro is one that types your address. Macros support commands that allow a variety of advanced functions, such as making decisions (for example, if the balance is less than zero, color it red; if not, color it black), looping (if the balance is greater than zero, subtract 10 from it), and even interacting with a person (asking the user for a number). Some of these commands are based on the BASIC programming language. (BASIC is an acronym for Beginners Allpurpose Symbolic Instruction Code.) It is common to assign a macro to a keystroke or toolbar icon so that it can be quickly started. The OpenOffice.org macro language is very flexible, allowing automation of both simple and complex tasks. Although writing macros and learning about the inner workings of OpenOffice.org can be a lot of fun, it is not always the best approach. Macros are especially useful when you have to do a task the same way over and over again, or when you want to press a single button to do something that normally takes several steps. Once in a while you might write a macro to do something you cant otherwise do in OpenOffice.org, but in that case you should investigate thoroughly to be sure OOo cannot do it. For instance, a common request on some of the OpenOffice.org mailing lists is for a macro that removes empty paragraphs. This functionality is provided with AutoFormat (select Tools | AutoCorrect/AutoFormat | Options tab). It is also possible to use regular expressions to search for and replace empty space. There is a time and a purpose for macros and a time for other solutions. This chapter will begin to prepare you for the times when a macro is the solution of choice. OpenOffice.org is abbreviated as OOo. OpenOffice.org Basic is therefore abbreviated as OOo Basic. The OpenOffice.org macro language is based on the BASIC programming language. OOo Basic runs one line at a time. However, you usually need more than one line to get anything done, so you will typically write routinesalso known as proceduresthat consist of a number of lines that, when all are run, do a particular thing. For instance, you might write a routine that deletes a header from a file and inserts your preferred header. In OpenOffice.org, routines that are logically related are stored in a module. For example, a module might contain routines for finding common mistakes that require editing. Logically related modules are stored in a library, and libraries are stored in library containers. The OpenOffice.org application can act as a library container, as can any OOo document. Simply stated, the OpenOffice.org application and every OpenOffice.org document can contain libraries, modules, and macros. A dialog is a window that appears on the screen, usually to request input or present information. Dialogs usually disappear after the requested input is entered. User-created dialogs are stored in dialog libraries in the same way that macros are stored in macro libraries. Each library can contain multiple dialogs. Library containers can store both macro and dialog libraries. See Chapter 17, Dialogs and Controls, for more about dialogs.

Storing a macro in a document libraryEach OpenOffice.org document is a library container able to contain macros and dialogs. When a document contains the macros that it uses, possession of the document implies possession of the macros. This is a convenient distribution and storage method. Send the document to another person or location and the macros are still available and usable. The traditional method of introducing a programming language is by writing a program that somehow outputs the message Hello World. Entire Web sites exist with the sole purpose of showing Hello World programs in as many different programming languages as possible (for example, see http://www2.latech.edu/~acm/HelloWorld.shtml). Choosing not to break with tradition, my first macro shows a variation of Hello World.

2 OpenOffice.org Macros Explained

Step 1. Create a libraryAll OOo documents, regardless of document type, may contain macros. To add a macro to any OOo document, the document must be open for editing. Start by opening a new text document, which will be named Untitled1 assuming that no other untitled document is currently open. When a document is created, OpenOffice.org creates an empty library named Standard. The Standard library, however, remains empty until a new module is manually created. Use the Macro dialog to organize libraries and modules: select Tools | Macros | Macro (see Figure 1). The Macro from list shows the available library containers; this includes every open document as well as the application library container. The application library container is named soffice, but this is not shown in Figure 1. The document library containers are listed below the soffice container using the documents assigned name. Most library containers already have a library named Standard. Double-click a library container icon to toggle the display of the contained libraries. Double-click a library to toggle the display of the contained modules. The application library container is named soffice because of ties with StarOffice from Sun Microsystems. OpenOffice.org is based on code from StarOffice, and the two products continue to share a common code base.

Figure 1. Use the Macro dialog to create new macros and organize libraries. In Figure 1, the Standard library in the untitled document is highlighted. This library was automatically created when the new document was created. The document currently contains no modulesremember that macros are stored in modules. Although you could click the New button to create a new module, dont! The point of this section is to create a new library. Do not store your macros in the Standard library. Create a new library with a descriptive name and store your macros there. When a library is appended it will overwrite an existing library with the same name. If all of your libraries are named Standard, this prevents you from appending your libraries to other library containers. Click the Organizer button to open the Macro Organizer dialog (see Figure 2). As with the Macro dialog, all of the library containers are listed. In other words, each document is listed, as is the soffice application library container. In Figure 2, the Standard library is highlighted in the document Untitled1; scroll down the list to find Untitled1 if required. The Macro Organizer dialog is a tabbed dialog, and the tab in focus is Modules. As the name implies, the Modules tab deals with modules. Heres a description of the items in this dialog: The New Module button creates a new module in the selected library. The New Dialog button creates a new dialog in the selected library. The Delete button deletes the currently selected module; its not available unless a module is selected.

Chapter 1: Getting Started

3

The Edit button opens the currently selected module for editing in the IDE; its not available unless a module is selected. The Close button closes the Macro Organizer dialog.

Figure 2. Use the Macro Organizer dialog to organize modules. The purpose of this section is to create a meaningfully named library that is contained in the Untitled1 document. Click the Libraries tab to deal with libraries (see Figure 3).

Figure 3. Use the Macro Organizer dialog to organize libraries. When this portion of the dialog is displayed, the application library container (soffice) is selected in the Application/Document list. Select the Untitled1 document so that the changes are made to the untitled document. The buttons displayed on the Libraries tab affect libraries, not modules. Here are their descriptions: The New button creates a new library in the selected document or application. The Password button allows you to assign or change the password for the selected library. Note that you cannot assign a password to the default library. The Delete button deletes the currently selected module; its not available unless a module is selected.

4 OpenOffice.org Macros Explained

The Append button provides a mechanism for copying a library from another library container (document or application) to the library container selected in the Application/Document list. Library management is discussed later in this chapter. The Edit button opens the currently selected library for editing in the IDE. The Close button closes the Macro Organizer dialog.

Click the New button to create a new library (see Figure 4). Although the default name is Library1, it is better to choose a meaningful name such as MyFirstLibrary or TestLibrary. Click OK to create it.

Figure 4. Choose a meaningful name for the library. The Macro Organizer now contains the newly created library in the Library list (see Figure 5).

Figure 5. The document now contains the library named TestLibrary.

Step 2. Create a moduleMacros are stored in a module, so the next step is to create a module in the newly created library. Assuming that the Macro Organizer (see Figure 3) is still open, select the Modules tab (see Figure 6).

Figure 6. The TestLibrary contains one module named Module1.

Chapter 1: Getting Started The newly created TestLibrary is now displayed in the Macro Organizer. Select TestLibrary or any module contained in that library, and then click the New Module button to create a new module (see Figure 7). The default name is Module1; choose a more descriptive name for the module and click OK to create it.

5

Figure 7. Choose a meaningful module name. Use descriptive module names to avoid confusion. This is important when moving between modules. A common mistake is to highlight the wrong library container in either the Macro dialog or the Macro Organizer dialog. The most common mistake is to select a library or module in the application container (soffice) rather than a specific document. Find the document name in the list. The document name is determined by the title as set in the documents Properties dialog. Use File | Properties to open the documents Properties dialog. The title is set from the Description tab. If no title is set, the file name is used instead. Two documents with the same title in the documents Properties dialog use the same name in the Macro dialog, the Macro Organizer dialog, and the window title. This is confusing, so try to avoid it.

Step 3. Enter your first macroIf the Macro Organizer dialog is still open, you can highlight the newly created module and click the Edit button. This will open the Basic IDE. Another option is to use the Macro dialog. If the Macro Organizer dialog is open, click the Close button to open the Macro dialog. If the Macro Organizer dialog is not open, select Tools | Macros | Macro to open the Macro dialog (see Figure 8).

Figure 8. Select a specific macro.

6 OpenOffice.org Macros Explained

Heres a description of the buttons in the Macro dialog: The Run button runs the selected macro. The macro is selected in the right-hand list, and its name also appears in the top-left input box labeled Macro name. The Close button closes the Macro dialog. The Assign button associates a macro with a specific event. Assigning macros to events is discussed later. The Edit button opens the IDE and edits the selected macro. The Delete button deletes the selected macro. This button is present only if a module is selected. If a library or document is selected in the Macro from list, the Delete button changes to New. The New button creates a new macro in the selected library. The Organizer button opens the Macro Organizer dialog. The Help button opens the help system.

The purpose of the Macro dialog is to operate on individual macros. Select MyFirstModule and click the Edit button to open the Basic IDE; see Figure 9). One empty subroutine, Main, is automatically created when a module is created. The new button on the Macro dialog creates a second empty subroutine, Macro1. The IDE shown in Figure 9 was opened by clicking the library and then clicking the New button. Delete these subroutines and replace them with the code in Listing 1.

Figure 9. Develop macros in the IDE. Listing 1. The Hello World routines are found in this chapters source code files as SC01.sxw.Sub main HelloWorld2() End Sub Sub HelloWorld1 Print "Hello World One" End Sub Sub HelloWorld2 Print "Hello World Two" End Sub

Chapter 1: Getting Started

7

The IDE contains a Macro toolbar and a Function toolbar as labeled in Figure 9. (Most of the icons on the Macro toolbar are identified in Figure 13.) Rest your mouse cursor on a toolbar icon for a few seconds to read the text that appears; this provides a hint at what that icon does. Click the Compile icon to check the macro for syntax errors. No message is displayed unless an error is found (see Figure 10). The Compile icon compiles only the current module.

Figure 10. Click the Compile icon to find syntax errors such as a missing double quotation mark. Modify the code in Listing 1 to demonstrate an error. Remove the second double quotation mark from the Print statement in HelloWorld1 (see Figure 10). Then click the Compile icon. A dialog displays a relevant error message for the first error encountered. The error message in Figure 10 indicates that a double quotation mark was expected but not found. The first double quotation character is highlighted, and a red arrow marks the line with the error. Click the OK button to close the error dialog, fix the line by adding a double quotation mark at the end, and then compile the code again. Click the Run icon to run the first routine in the current module. It is not necessary to click the Compile icon first, because clicking the Run icon automatically compiles every module in the current library. Clicking the Run icon runs only the first routine in the module. For Listing 1, the Run icon runs the first subroutine, which is named main. The main subroutine calls the HelloWorld2 subroutine, displaying the dialog shown in Figure 11. Click OK to close the dialog, or click Cancel to to stop the macro.

Figure 11. Click OK to close the dialog. The Run icon always runs the first macro in the current module. As a result, a different approach is required to run HelloWorld1. To run HelloWorld1, you can use one of the following methods: Place HelloWorld1 first in the module and click the Run icon. Modify the main subroutine to call HelloWorld1 rather than HelloWorld2. Use the Macro dialog (shown in Figure 8) to run any routine in the module. Add a button to your OpenOffice.org document that calls HelloWorld1. This method is discussed later. Assign the macro to a keystroke. To do this, click Tools | Configure to open the Configuration dialog, and then select the Keyboard tab. Macro libraries are at the bottom of the Category list. You can also find this by clicking Tools | Macros | Macro, selecting the specific macro, and then clicking the Assign button to launch the Configuration window. Various tabs in this dialog allow you to assign the macro to execute as a menu item, from a keyboard key, a toolbar icon, or a system event. Add an icon to the toolbar that calls HelloWorld1.

8 OpenOffice.org Macros Explained

To use the Macro dialog to run any subroutine in a module, follow these steps: 1. 2. 3. 4. 5. 6. Select Tools | Macros | Macro to open the Macro dialog (see Figure 8). Find the document that contains the module in the Macro from list. Double-click a library to toggle the display of the contained modules. Select the module to display the contained subroutines and functions in the Existing macros in: list. Select the desired subroutine or function to runfor example, HelloWorld1. Click the Run button to run the subroutine or function. When developing a subroutine, first place it in a module so you can quickly run it by clicking the Run icon. Another solution is to use the first subroutine to call another, as shown in Listing 1. This is faster than using the Macro dialog. The code used in this chapter is available in an OpenOffice.org text document named SC01.sxw. Download and open this document. When a document containing macros is opened, OpenOffice.org issues a warning (see Figure 12). This warning is to help you avoid accidentally running a macro containing a virus. Although you can still manually run any macro using the Macro dialog, macro buttons in the document will not function. Click Run to fully enable the macro buttons added to SC01.sxw. You can configure a document to run a macro automatically when the document loads. This is how a macro virus spreads by using documents. If you dont expect a document to contain a macro, you should always click Do Not Run. This prevents any macro from running automatically when the document is loaded.

Figure 12. You just opened an OpenOffice.org document that contains a macro. SC01.sxw contains three buttons: Main, Hello World 1, and Hello World 2. Each button is configured to run the corresponding subroutine when the button is clicked. The buttons do nothing if you click Do Not Run when the document is loaded. It is possible to add a directory to the list of secure paths. If you are certain that a path contains documents that you can safely trust not to contain macro viruses, you can check the box, and the path will be added to the list of secure paths. In the future, all documents loaded from the same location will be considered safe, and macros will always run.

Storing a macro in the application libraryThe OpenOffice.org application itself is a library container. This is an excellent place to store code and dialogs common to multiple documents. Version control is easier if macros are stored in one location. If five documents all contain the same macro, not only is storage space wasted, but if the macro changes, you must change the macro in five different documents. To store a macro in the application libraries, use the same methods used for documents. The application-level container is named soffice. The OpenOffice.org application includes multiple libraries. The Standard library includes a module named Module1, which contains one empty macro that does nothing. Use the Macro Organizer dialog in Figure 3 to add new libraries.

Chapter 1: Getting Started

9

Uninstalling OpenOffice.org may delete libraries stored at the application level, so you should always keep a backup of your libraries. Reinstalling or installing a new version of OpenOffice.org may overwrite application-level libraries. Back up these libraries when you back up your documents. In most cases, the libraries that you created are still there, but the configuration files are new and do not reflect the new libraries. Therefore, its usually possible to restore your libraries from the standard library location. For more information, see the section titled Library management, later in this chapter. Each application library is stored in its own directory. To determine where OpenOffice.org stores application libraries, select Tools | Options. In the Options dialog, expand the OpenOffice.org branch in the tree menu and select Paths. The Basic entry shows the locations of the external libraries. Before installing a new version of OpenOffice.org, make a copy of all application-level libraries. If you install OOo into the same location, it overwrites the configuration file that tells OOo where your application-level libraries are. The libraries are usually still there but OOo does not know about them. To restore lost libraries, regardless of where they are located, use the Libraries tab on the Macro Organizer (see Figure 3). Verify that soffice is selected in the Application/Document list, and then click the Append button. Navigate to the directory containing the library that you want to add. Select the file script.xlb and click Open. Do this for each library that you want to restore. This method can also be used to add libraries stored in documents. Do not use the Standard library if you think youll ever want to append your library to another location. Store all of your modules in libraries with meaningful names that you create. The Standard library is special, and you cannot delete it or overwrite it. To practice adding a macro to the application-level library, open the Macro Organizer. Verify that the soffice library container is the current container. Click the New Module button to add new modules to the application-level libraries. To add new libraries, select the Libraries tab. Verify that soffice is selected in the Application/Document list, and then click the New button. Libraries stored in documents may be appended to the application library container. When a library is appended, it overwrites an existing library with the same name. It is, therefore, a good idea to create meaningful library names to hold macros. This limits problems moving macros between library containers.

The Integrated Development EnvironmentAn integrated development environment (IDE) is a set of programming tools used to facilitate the creation of software. OpenOffice.org includes a very capable IDE with tools that run, edit, and find errors in your macros. It is worth the time to become familiar with its features. Figure 13 shows the IDE with captions added for many of the icons and display areas. The central display area where macro code is listed is the editor window. Many of the features, such as Stop, Breakpoint, Single Step, and the Watch pane serve as a simple yet effective debugger for macro code. This section provides a quick overview of the standard functions of the IDE. Do not be surprised if you dont fully understand how to use them all at this point. You will become very familiar with these functions as you work through the examples. The first set of functions are used for debugging, and the ones described near the end of this section support the organization and management of objects in your macro programs, libraries, and documents. Following are the icon descriptions. The Compile icon compiles and performs a syntax check of only the current module. The Compile icon is useful if you dont want to run the macro but you want to verify that its syntactically correct. No message is displayed unless an error is found (see Figure 10). When an error is found, a dialog appears, indicating the error. An arrow in the Breakpoint column marks the line with the error, and the portion of the code that caused the error is highlighted. Click the OK button to close the error dialog. The process of compiling translates OOo macros into machine language, which the computer can understand and run. The Run icon compiles all of the modules in the current library and then runs the first subroutine or function in the current module. This is different from the Compile icon, which compiles only the current module.

10 OpenOffice.org Macros Explained

Figure 13. The IDE included with OpenOffice.org is very capable. The Stop icon stops a running macro. When you click this icon, you cant resume the macro; you must start it again, from the beginning. The Stop icon is enabled only while a macro is running. When enabled, the Stop icon resembles a traffic stop sign. The Procedure Step icon runs the current statement. If the macro is not yet running, the first routine in the module is started and marked as the current statement. The current statement has an arrow in the Breakpoint column, and the cursor is moved to that line. If, however, the macro is already running, the current statement runs and the next runnable statement is marked as current. The Procedure Step icon treats calls to other routines as a single statement and does not step into them. Notice that the icon has an arrow that curves around the curly brackets that represent a subroutine or function call. The Single Step icon runs the current statement. The behavior is the same as the Procedure Step icon except that subroutines and functions are not treated as a single statement. Each statement in the called routine is considered a statement. Subroutines and functions are stepped into, marking the called subroutine or function definition as the current statement. Notice that the icon contains an arrow that points into the curly brackets that represent a subroutine or function call. The Step Back icon runs the macro to the end of the current routine and then steps out of it. The effect is the same as repeatedly clicking the Procedure Step icon until the last statement in the current routine (End Sub or End Function) is current, and then clicking Procedure Step one more time to step out of the routine. The statement following the call to the current routine becomes the current statement. If you accidentally click Single Step rather than Procedure Step, click the Step Back icon once. Notice that the icon contains an arrow that leaves the curly brackets that represent a subroutine or function call. The Breakpoint icon sets a breakpoint at the statement containing the cursor. A red stop sign marks the line in the Breakpoint column. Double-click the Breakpoint column to toggle a breakpoint at that statement. Right-click a breakpoint in the Breakpoint column to activate or deactivate it. The Manage Breakpoints icon loads the Manage Breakpoints dialog (see Figure 14).

Chapter 1: Getting Started

11

Figure 14. Manually edit and configure breakpoints. The Add Watch icon assumes that the current word (the word that contains the icon) is a variable and adds this variable name to the Watch pane. The Object Catalog icon opens the Objects window (see Figure 15), where you can browse all of the currently available library containers. Use this window to see which libraries, modules, and subroutines are available. Double-click a subroutine to load it into the IDE. The functionality is similar to the Navigator in an OOo Writer document. You must save a file before its modules are available in the Object Catalog. Leave the Objects window open and use it as a navigator to quickly jump between modules, libraries, or even subroutines in the same module.

Figure 15. You can browse the available libraries and modules in the Objects window. The Macros icon loads the Macro dialog. Selecting Tools | Macros | Macro also loads the Macro dialog. The Modules icon loads the Macro Organizer dialog. This icon has the same effect as clicking the Organizer button in the Macro dialog (see Figure 2 and Figure 3).

12 OpenOffice.org Macros Explained

Select or place the cursor directly to the left of a parenthesis, and then click the Find Parentheses icon to find the matching parentheses. When the IDE matches parentheses, it selects the matching parentheses and everything that they enclose. To open the Controls window, click the Controls icon while editing a dialog. (For more information about controls, see Chapter 17, Dialogs and Controls.) To create a dialog for editing, click the Modules icon to load the Macro Organizer dialog. Click the New Dialog button to create a new dialog. See Chapter 17, Dialogs and Controls, for more about using and creating dialogs in macros. The last two icons, Insert Source Text and Save Source As, are used to insert text stored in an external source file into the current module, and to save the current module to an external text file. This is an excellent way to create a backup of a macro or to create a text file that can be easily sent to another person. This is different from the Disk icon, which is used to save the entire library or document that contains the module.

Using breakpointsIf you set a breakpoint in the code, the macro will stop running at that point. You can then inspect variables, continue running the macro, or single-step the macro. If a macro fails and you dont know why, single-stepping (running one statement at a time) allows you to watch a macro in action. When the macro fails, youll know how it got there. If a large number of statements run before the problem occurs, it may not be feasible to run one statement at a time, so you can set a breakpoint at or near the line that causes the problem. The program stops running at that point and you can single-step the macro and watch the behavior. The Breakpoint icon sets a breakpoint at the statement containing the cursor. A red stop sign marks the line in the Breakpoint column. Double-click in the Breakpoint column to toggle a breakpoint at that statement. Right-click a breakpoint in the Breakpoint column to activate or deactivate it. The Manage Breakpoints icon loads the Manage Breakpoints dialog (see Figure 14). All of the active breakpoints in the current IDE dialog appear in the lower list. To add a breakpoint, enter a line number in the entry field at the top and then click New. To delete a breakpoint, select a breakpoint in the list and click the Delete button. Clear the Active check box to disable the highlighted breakpoint without deleting it. The Pass Count input box indicates the number of times a breakpoint must be reached before it is considered active. If the pass count is four (4), then the fourth time that the statement containing the breakpoint is to be run, it will stop rather than run. This is extremely useful when a portion of the macro does not fail until it has been called multiple times. There are two things that cause a breakpoint to be ignored: a pass count that is not zero, and explicitly marking the breakpoint as not active in the Manage Breakpoints dialog. Every breakpoint has a pass count that is decremented toward zero when it is reached. If the result of decrementing is zero, the breakpoint becomes active and stays active because the pass count stays at zero thereafter. The pass count is not restored to its original value when the macro is finished or restarted. It is easy to monitor the value of variables from the IDE while a routine is running. Place the cursor next to or in any word in the Edit window and click the Add Watch icon to add the word to the Watch pane. The Watch pane displays the value of variables that are currently in scope. The text is displayed for variables that are not available. Another way to add variables to the Watch pane is to type the name into the Watch window and press Enter. To delete a name from the Watch pane, select it in the Watch pane or type the name into the Watch window and click the Remove Watch icon. Click a name in the Watch pane to place its name in the Watch window. A variable that is in scope is currently available or visible. For example, if the variable j is defined inside HelloWorld1, it is not visible (in scope) inside HelloWorld2. This is discussed later.

Library managementThis section deals with creating, transferring, and renaming libraries and modules. When considering library management, it is important to first understand some basics that have already been discussed: A library container contains zero or more libraries. Each library contains zero or more modules and dialogs. Each module contains zero or more macros.

Chapter 1: Getting Started

13

The application is a library container named soffice. Libraries stored in the application are globally available to all macros. Every document is a library container. The library named Standard is special; it always exists and cannot be overwritten. I recommend against using the Standard library. Always give meaningful names to the libraries and modules that you create. For example, Library1 and Module4 are not meaningful names, although AXONInvoiceForm1 might be more descriptive and helpful.

How libraries are storedOpenOffice.org libraries are stored as XML files that are easily editable using any text editor. In other words, it is easy for you to poke around and damage your files. Although manually editing your external libraries is generally considered foolish, I have had at least one instance where this was required, because OOo was unable to load a module that contained a syntax error. Manually editing OOo files is best left to advanced users. Beginning users may want to quickly skim through this material or skip to the next section.

Application librariesEach application library is stored in a single directory, and each module and dialog is contained in a single file. The Options dialog (Tools | Options | OpenOffice.org | Paths) contains an entry that identifies where libraries are located. The global libraries that are included with OpenOffice.org are stored in a shared basic directory under the directory in which OOo is installed. Examples:C:\Program Files\OpenOffice.1.1.1\share\basic /usr/local/OpenOffice.org1.1.1/share/basic 'A Windows installation 'A Linux installation

The libraries that you create are stored in different directories. On my Windows computer, I have a single-user installation, and on my Linux computer I have a multiple-person network installation. The choices that you make while installing OOo affect the location of your personal libraries. Here are two examples:C:\Program Files\OpenOffice.1.1.1\user\basic /home/andy/OpenOffice.org1.1.1/user/basic 'Windows user files 'Linux user files

Listing the shared directory shows one file for each application library that is included with OOo. The user directory, however, is a bit more interesting (see Table 1). Table 1. Files and some directories in my user/basic directory.Entrydialog.xlc script.xlc Standard Pitonyak PitonyakDialogs

DescriptionXML file that references every dialog file known to this user in OpenOffice.org. XML file that references every library file known to this user in OpenOffice.org. Directory containing the Standard library. Directory containing a library with code that I created. Directory containing a library with some code and a dialog.

Table 1 references the directories Pitonyak and PitonyakDialogs. The Pitonyak library and the PitonyakDialogs library are not related; their names are similar because I lacked creativity and good sense when I named them. It is not true that the library PitonyakDialogs contains the dialogs for the Pitonyak library.

14 OpenOffice.org Macros Explained

The files dialog.xlc and script.xlc contain a reference to all of the dialogs and libraries that are known to OOo. The visible librariesas seen in the Macro dialog and the Macro Organizer dialog (see Figure 16)are built from the files dialog.xlc and script.xlc. If these two files are overwritten, OOo will not know about your personal libraries even if they exist.

Figure 16. The Macro dialog and the Macro Organizer dialog show available libraries and modules. The Macro Organizer dialog shows that the PitonyakDialogs library contains two code modules and one dialog. Table 2 contains a listing of the files in the PitonyakDialogs directory. Notice that each module and dialog in a library has a corresponding file. Table 2. Files in the PitonyakDialogs library directory.Filedialog.xlb script.xlb Module1.xba SimpleObjectBrowserCode.xba SimpleObjectBrowser.xdl

DescriptionReferences the dialogs contained in this library. References the modules contained in this library. BASIC code in the module named Module1. BASIC code in the module named SimpleObjectBrowserCode. A dialog in the module named SimpleObjectBrowser.

The files dialog.xlc and script.xlc in Table 1 reference the files dialog.xlb and script.xlb in Table 2. In general, none of these files should be manually modified, but in an emergency, they may be modified by hand to correct certain types of errors.

Document librariesAn OpenOffice.org document, when saved to disk, is stored in the standard ZIP format. Any program that can view and extract ZIP files can be used to inspect an OOo documenthowever, some programs will require you to change the file extension to end with ZIP. After unzipping an OOo document, you will find files that contain the primary content, styles, and settings. The extracted document also contains three directories. The META-INF directory references all of the other files, embedded pictures, code libraries, and dialogs. The Dialogs directory contains all of the embedded dialogs, and the Basic directory contains all of the embedded libraries. Notice that libraries contained in the soffice application-level container are stored in a slightly different configuration than the libraries contained in a document. As an experiment, I took a document that contained numerous controls that called a specific library. I unzipped the document and then used a text-search tool to find all references to a specific library named CH03. After manually changing every occurrence of the text CH03 to CH04, I zipped the directory back into a single file, and OOo was

Chapter 1: Getting Started

15

able to read and use the file. I successfully changed the name of a contained library and every reference to the controls by editing the XML definitions. The point of this section is that, in an emergency, you can manually inspect a documents XML and potentially fix problems. This is usually NOT the best way to change the name of a documents libraries.

Using the Macro OrganizerThe Macro Organizer (Tools | Macros | Macro | Organizer) is able to satisfy most users needs in regards to organizing modules and libraries. The Modules tab of the Macro Organizer dialog (see Figure 16) provides the capability to create and delete modules. The Macro Organizer dialog also has a Libraries tab (see Figure 17) used to create and delete libraries. The Libraries tab contains a drop-down box at the top that is used to select the library container. In other words, you can select a specific open document or the application library container named soffice.

Figure 17. Use the Macro Organizer to create, add, and delete libraries. A documents name is the file name, unless the document title is set in the documents Properties dialog (File | Properties | Description). If the Title property is set, it is used as the document name in the window title, the Macro dialog, and the Macro Organizer dialog.

Renaming modules and librariesYou can change the name of a module or library from the Macro Organizer dialog. Module names are changed from the Modules tab, and library names are changed from the Libraries tab. When you change a library or module name, it doesnt change anything that references the contained macros. For example, if I write down your telephone number in my Palm Pilot and you change your telephone number, my Palm Pilot is not automatically updated. So, what might call a macro? When controls are embedded in a document or a dialog, they frequently use macros as event handlers. Macros call dialogs that are contained in libraries. Macros may be called from programs outside of OpenOffice.org. When you rename a module or a library, references to the contained macros are not updated.

16 OpenOffice.org Macros Explained

Renaming a library or module isnt a bad thing to do; just remember that things that reference the modules and libraries wont be updated. If nothing is referencing your code, feel free to change the module and library names. You can rename libraries and modules by using the Macro Organizer; the procedure is the same for both: 1. 2. 3. Find the library or module in the appropriate tab of the Macro Organizer (see Figure 16 and Figure 17). Select the library or module. Wait a moment and click on the library or module. The cursor should appear to edit the library or module name. I have found this to be a bit sensitive, and sometimes I must purposely single-click a few times. Do not accidentally double-click, because this opens the library or module contents for editing. Type a new name for the library or module and press the Enter key.

4.

I had a large document that contained numerous buttons. The buttons called macros in a library and I had to change the name of the library. Unfortunately, after I changed the name of the library, the buttons still pointed to the original library, which no longer existed. Feeling particularly daring, I unzipped the document into a temporary directory (remember that an OOo document file is really a ZIP file containing numerous files that, as a whole, are the document). I then used my favorite text editor to load each file and I changed the old library name to the new library name. When I was finished, I zipped all of the files and directories back into a single ZIP file and I had successfully changed all of the references. Manually editing an OOo document file by unzipping all of the contained files and directories and then zipping them back is an error-prone process. If you do it wrong, the document will stop working. In other words, keep a copy of the original file.

Adding librariesThe Append button (see Figure 17) in the Macro Organizer dialog opens the Append Libraries dialog, which is really a file-selection dialog. This dialog is used to select the file that contains the library to append. To add a library contained in a document, start by selecting the document. The Open button on the file-selection Append Libraries dialog opens the library-selection Append Libraries dialog (see Figure 18). Use the library-selection Append Libraries dialog to view the libraries contained in the selected document and select the libraries you want to append.

Figure 18. Use the Append Libraries dialog to select the libraries to add. The library-selection Append Libraries dialog in Figure 18 allows you to append as many libraries as you like. Existing libraries are not overwritten unless the Replace existing libraries box is checked. The Insert as reference check box is available only while appending libraries that are not contained in a document. Click OK to append the selected libraries. It is not possible to overwrite the Standard library. I recommend against using the Standard library because you cant append it to another document or the application.

Chapter 1: Getting Started

17

Libraries that are not contained in a document are stored in individual directories. To append a library that is not stored in a document, open the file-selection Append Libraries dialog (see Figure 19) and select the directory that contains the library files. It doesnt matter where the library files are stored. The files may be on a floppy disk as a backup, or they may be from the same directory used by OOo for application-level libraries. When I install a new version of OpenOffice.org, I append the libraries from my previous OOo installation. While appending a library that is not contained in a document, two files are shown: dialog.xlb and script.xlb (see Table 2 and Figure 19). Both files are required and automatically appended regardless of which file you choose. In other words, you can select either dialog.xlb or script.xlb; both will be appended.

Figure 19. It doesnt matter which file you choose; both are appended. When I install a new version of OOo, I append my personal libraries from the previously installed version. I also move my libraries to other computers and install them there. Chapter 16, Library Management, contains information and examples of manipulating and accessing libraries and modules using OOo Basic.

ConclusionMacros are stored in modules, modules are stored in libraries, and libraries are stored in library containers. The application is a library container, as is every document. The IDE is used to create and debug macros and dialogs. You have just completed one of the most difficult steps in writing macros for OpenOffice.org: writing your first macro! You are now ready to explore, try other macro examples, and create a few of your own. Updates and corrections to this chapter can be found on Hentzenwerkes Web site, www.hentzenwerke.com. Click Catalog and navigate to the page for this book.

18 OpenOffice.org Macros Explained

Chapter 2: Language Constructs

19

Chapter 2 Language ConstructsThe OpenOffice.org macro language is similar to the one in Microsoft Office because they are both based on BASIC. Both macro languages access the underlying implementation structures, which differ significantly and are therefore incompatible. This chapter emphasizes the portions of the language that do not access the underlying implementation.

This chapter shows how to assemble different components to produce an OOo macro that will compile and run. In a word: syntax. Correct syntax does not imply that the macro does what you want, only that the pieces are put together in a correct way. The phrases Can I drive? and May I drive? are both syntactically correct. The first phrase is about ability and the second phrase is about permission. In speech, these two questions may be understood to have the same meaning. The computer, on the other hand, does exactly what you ask, rather than what you mean. The primary components that syntactically constitute an OpenOffice.org macro are statements, variables, subroutines and functions, and flow-control constructs. A statement in a macrosometimes called a lineis a small, runnable portion of code that is usually written as a single line of text. Variables are containers that hold values that can change during execution of a macro. Subroutines and functions separate a macro into functional named groups of statements, allowing for better organization. Flow control directs which statements run and how many times. OpenOffice.org runs one line of a macro at a time. Each line of a macro is delimited exactly the way it sounds by a new line (see Listing 1). Listing 1. OpenOffice.org runs one line of a macro at a time.Print "This is line one" Print "This is line two"

Lines that are too long may use more than one line by appending an underscore (_) to the end of the line (see Listing 2). The underscore must be the last character on the line for it to act as a line-continuation character. The underscore has no special meaning when it isnt the last character of a line, allowing it to be used inside strings and in variable names. When used as a continuation character, spaces may precede the underscore and are in some cases required to separate the underscore from what precedes it. For example, splitting the line a+b+c after the b requires a space between the b and the underscore, or the underscore is considered part of the variable name. Spaces that inadvertently follow a continuation character may cause a compile-time error. Unfortunately, the error is not that something follows the underscore, but that the next line is invalid. Listing 2. Append an underscore to the end of a line to continue on the next line.Print "Strings are concatenated together " & _ "with the ampersand character"

You can place multiple statements on a single line by separating them with colons (see Listing 3). This is usually done for improved code readability. Each of the combined statements act as a single line of code while debugging the macro in the Integrated Development Environment (IDE). Listing 3, therefore, acts like three separate statements while using the IDE to single-step through the macro. Listing 3. Set the variables x, y, and z to zero.x = 0 : y = 0 : z = 0

Macros are generically called code. A programmer writes code, and OpenOffice.org runs one line of code at a time. You should liberally add remarks, which are also called comments, to all of the macros that you write. While writing a macro, remember that what is clear today may not be clear tomorrow, as time passes and new projects arise

20 OpenOffice.org Macros Explained

and memory fades all too quickly. The single quotation character and the keyword REM both indicate the start of a comment. All text on the same line following a comment indicator is ignored (see Listing 4). Comments are not considered runnable statements; they are ignored while single-stepping a macro. Listing 4. You should add comments to all of the macros that you write.REM Comments may start with the keyword REM. ReM It is not case-sensitive so this is also a comment. ' All text following the start of the comment is ignored X = 0 ' A comment may also start with a ' single quote z = 0 REM All text following the start of the comment is ignored

Keywords, variables, and routine names in OOo Basic are not case-sensitive. Therefore, REM, Rem, and rEm all start a comment. Nothing can follow a line-continuation character, and this includes comments. All text following a comment indicator is ignoredeven the continuation character. The logical result from these two rules is that a linecontinuation character can never occur on the same line as a comment. When anything follows a line-continuation character, the line is not continued. This may not cause an error. See Listing 5. Listing 5. OOo Basic does not generate a compilation error. Depending on the OOo version, a run-time error may be generated or the error may be ignored.For i = LBound(b()) To _ Rem hello UBound(b()) Print i Next

Compatibility with Visual BasicWith respect to syntax and BASIC functionality, OOo Basic (also known as Star Basic) is very similar to Visual Basic. The two Basic dialects are nothing alike when it comes to manipulating documents, but the general command set is is very similar. There are differences, however, and they are noted throughout the text where appropriate. Steps are being taken to improve the general compatibility between the two dialects. Some of the planned, and sometimes already working, enhancements are scheduled for release with OOo 2.0. Just remember that nothing is certain until it happens. I consider information on future enhancements as speculation until it is out, even if it seems very probable. Many of the planned changes are not backward compatible with existing behavior. To help resolve these conflicts, a new compiler option and a new run-time mode will be introduced to specify the behavior. The compiler option Option Compatible will direct some features. This option will affect only the module in which it is contained. Because a macro calls different modules during its execution, both the old and new behavior may be used, depending upon the existence of Option Compatible in each called module. Setting the option in one module and then calling another module will have no effect in the called module. In OOo 1.1.0, is not a valid variable name. If, however, a module contains Option Compatible, all characters defined as letters in the Latin-1 (ISO 8859-1) character set are accepted as part of an identifier name. This is just one of many changes that use Option Compatible. A run-time function, CompatibilityMode( True/False ), allows the behavior of run-time functions to be modified during the execution of a macro. This provides the flexibility to enable the new run-time behavior, perform some operations, and then disable the new run-time behavior. Hopefully, some method of probing the current mode will be provided. Both Visual Basic and OOo Basic support the rmdir() command to remove a directory. VBA can remove only empty directories, but OOo Basic can recursively remove an entire directory tree. If CompatibilityMode(True) is

Chapter 2: Language Constructs called prior to calling rmdir(), OOo Basic will act like VBA and generate an error if the specified directory is not empty. This is just one of many changes that use CompatibilityMode().

21

VariablesVariables are containers that hold values. OpenOffice.org supports different types of variables designed to hold different types of values. This section shows how to create, name, and use variables. Although OOo Basic does not force you to declare variables, you should declare every variable that you use. The reasons for this are developed throughout this section.

Constant, subroutine, function, label, and variable namesAlways choose meaningful names for your variables. Although the variable name var1 requires little thought during creation, FirstName is more meaningful. Some variable names are not particularly descriptive but are commonly used by programmers anyway. For example, i is commonly used as a shortened version of index, for a variable that is used to count the number of times a repetitive task is executed in a loop. OOo Basic imposes restrictions on variable names, including the following: A variable name cannot exceed 255 characters in length. Well, officially a variable name cannot exceed 255 characters. I tested names with more than 300 characters with no problems, but I dont recommend this. The first character of a variable name must be a letter: AZ or az. The numbers 09 and the underscore character (_) may be used in a variable name, but not as the first character. If a variable name ends with an underscore, it wont be mistaken for a line-continuation character. Variable names are not case sensitive, so FirstName and firstNAME both refer to the same variable. Variable names may contain spaces but must be enclosed in square brackets if they do. For example, [First Name]. Although this is allowed, it is considered poor programming practice. These restrictions also apply to constant, subroutine, function, and label names.

Declaring variablesSome programming languages require that you explicitly list all variables used. This process is called declaring variables. OOo Basic does not require this. You are free to use variables without declaring them. Although it is convenient to use variables without declaring them, it is error-prone. If you mistype a variable name, it becomes a new variable rather than raising an error. Place the keywords Option Explicit before any runnable code to cause OOo Basic to treat undeclared variables as run-time errors (see Listing 6). Comments may precede Option Explicit because they are not runnable. Although it would be even better if this became a compiletime error, OOo Basic does not resolve all variables and routines until run time. Listing 6. Use Option Explicit before the first runnable line in a macro.REM ***** BASIC Option Explicit *****

Use Option Explicit at the top of every macro that you write; it will save you a lot of time searching for errors in your code. When I am asked to debug a macro, the first thing I do is add Option Explicit at the top of each module. You can declare a variable with or without a type. A variable without an explicit type becomes a Variant, which is able to take on any type. This means that you can use a Variant to hold a numeric value and then, in the next line of code, overwrite the number with text. Table 1 shows the variable types supported by OOo Basic, the value that each type of variable contains immediately after declaration (initial value), and the number of bytes that each type uses.

22 OpenOffice.org Macros Explained

Table 1. Supported variable types and their initial values.TypeBoolean Currency Date Double Integer Long Object Single String Variant

Initial ValueFalse 0.0000 00:00:00 0.0 0 0 Null 0.0 Zero-length string Empty

Bytes1 8 8 8 2 4 varies 4 varies varies

DescriptionTrue or False Currency with 4 decimal places Dates and times Decimal numbers in the range of +/- 1.79769313486232 x 10E308 Integer from -32,768 through 32,767 Integer from -2147483648 through 2147483647 Object Decimal numbers in the range of +/- 3.402823 x 10E38 Text with up to 65536 characters May contain any data type

Although OOo Basic supports a Byte variable type, you cant directly declare and use one. The function CByte, as discussed later, returns a Byte value that may be assigned to a variable of type Variant. Use the DIM keyword to explicitly declare a variable before use (see Table 2). You can declare multiple variables on a single line, and you can give each variable a type when it is declared. Variables with no declared type default to type Variant. Table 2. Declaring simple variables.DeclarationDim Name Dim Name As String Dim Name$ Dim Name As String, Weight As Single Dim Width, Length Dim Weight, Height As Single

DescriptionName is type Variant because no type is stated. Name is type String because the type is explicitly stated. Name$ is type String because Name$ ends with a $. Name is type String and Weight is type Single. Width and Length are type Variant. Weight is type Variant and Height is type Single.

When multiple variables are declared in a single line, the type for each variable must be listed separately. In the last line of Table 2, Weight is a Variant, even if though it looks like it may be of type Single. Much of the available literature on OOo macro programming uses a variable naming scheme based on Hungarian notation. With Hungarian notation, you can determine a variables type from its name. In practice, everyone does this differently and with differing levels of adherence. This is purely a stylistic decision that some people love and some people hate. OOo Basic uses Def statements to facilitate the use of Hungarian notion. The Def statements, which are local to each module that uses them, provide a default type for an undeclared variable based on its name. Normally, all undeclared variables are of type Variant. The Def statement is followed by a comma-separated list of character ranges that specify the starting characters (see Listing 7). Listing 7. Declare untyped variables starting with i, j, k, or n to be of type Integer.DefInt i-k,n

Chapter 2: Language Constructs

23

Table 3 contains an example of each supported Def statement. Def statements, like Option statements, are placed in the module before any runnable line or variable declaration. The Def statement does not force a variable with a specific first letter to be of a certain type, but rather provides a default type other than Variant for variables that are used but not declared. If you use Option Explicit, and you should, you must declare all variables. This renders the Def statements useless because they affect only undeclared variables. Table 3. Examples of supported Def statements in OpenOffice.org.Def StatementDefBool b DefDate t DebDbl d DefInt i DefLng l DefObj o DefVar v

TypeBoolean Date Double Integer Long Object Variant

Visual Basic .NET does not support the commands in Table 3. I have never seen the Def statements usedprobably because it is considered bad programming practice to use variables without declaring them. Def statements would be more useful if they provided default types for declared variables with no declared type.

Assigning values to variablesThe purpose of a variable is to hold values. To assign a value to a variable, type the name of the variable, optional spaces, an equals sign, optional spaces, and the value to assign to the variable, like so:X = 3.141592654 y = 6

The optional keyword Let may precede the variable name but serves no purpose other than readability. A similar optional keyword, Set, meant for Object variables, serves no purpose other than readability. These keywords are rarely used. Visual Basic .NET does not support the keywords Set and Let.

Boolean variables are True or FalseBoolean variables are able to store only two values: True or False. They are internally represented by the Integer values -1 and 0, respectively. Any numeric value assigned to a Boolean that does not precisely evaluate to 0 is converted to True. The OOo help incorrectly states that any numeric value assigned to a Boolean that does not precisely evaluate to -1 is converted to False. The subroutine in Listing 8 demonstrates the current behavior.

24 OpenOffice.org Macros Explained

Listing 8. ExampleBooleanType is found in the Variables module in this chapters source code files as SC02.sxw.Sub ExampleBooleanType Dim b as Boolean b = True b = False b = (5 = 3) REM Set to False Print b REM Print False b = (5 < 7) REM Set to True Print b REM Print True b = 7 REM Set to True because 7 is not 0 End Sub

The internal binary representation of True as -1 has all of the bits set to 1. The internal binary representation of False as 0 has all of the bits set to 0. (Geek Note: The internal binary representations of these numeric values are equal to the standard twos-complement representations of those Integer values. This internal consistency is quite satisfying to those who think about such things.)

Numeric variablesNumeric variables, as the name implies, contain numbers. OOo Basic supports integers, floating-point, and currency numbers. Integers may be expressed as hexadecimal (base 16), octal (base 8), or the default decimal numbers (base 10). In common practice, OOo users almost always use decimal numbers, but the other types are presented here as well, for completeness. Decimal numbers, base 10, are composed of the 10 digits 0, 1, 2, 3, 4, 5, 6, 7, 8, and 9. Add 1 to 9 in decimal and the result is 10. Binary (base 2), octal (base 8), and hexadecimal (base 16) numbers are also commonly used in computing. Octal numbers are composed of the numbers 0, 1, 2, 3, 4, 5, 6, and 7. In octal, add 1 to 7 and the result is 10 (base 8). Hexadecimal numbers are composed of the 16 digits 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E, and F. Binary numbers are composed of the two digits 0 and 1. Table 4 contains the numbers from 0 through 18 in decimal, and their corresponding values in binary, octal, and hexadecimal bases. Table 4. Numbers in different bases.Decimal0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18

Binary0 1 10 11 100 101 110 111 1000 1001 1010 1011 1100 1101 1110 1111 10000 10001 10010

Octal0 1 2 3 4 5 6 7 10 11 12 13 14 15 16 17 20 21 22

Hexadecimal0 1 2 3 4 5 6 7 8 9 A B C D E F 10 11 12

Chapter 2: Language Constructs

25

It is common to state how much memory a data type uses in terms of the number of bits or bytes. For example, a 4-bit number can be used to express all the numbers from 0 through 15 (see Table 4). There are eight bits in a byte, so it is easy to convert between the number of bits and the number of bytes. A byte can express the same range of numerical values as 8 bits, as two hexadecimal digits (00 through FF), or as counting from 0 to 255 in decimal. Different number base systems are used to express values for different purposes; OOo Basic can be more easily applied to more situations because we can express numerical values in different bases. A discussion of other number bases is important because internally, computers represent their data in binary format. It is easy to convert between the binary, hexadecimal, and octal number bases; and for humans it is typically easier to visualize binary numbers when represented in other number bases. Integers are assumed to be expressed as decimal numbers. Commas are not allowed. Hexadecimal numbers are preceded by &H and octal numbers are preceded by &O (letter O, not a zero). Unfortunately, there is no easy method to enter binary numbers. Table 5 presents a few simple guidelines for entering numbers. Table 5. A few guidelines for entering numbers in OOo Basic.ExampleUse 1000 not 1,000 + 1000 &HFE is the same as 254 &O11 is the same as 9 Use 3.1415 not 3,1415 6.022E23 Use 6.6e-34 not 6.6e -34 6.022e+23 1.1e2.2 evaluates as 1.1e2

DescriptionWrite numbers without a thousands separator; do not use commas. A space is permitted between a leading plus or minus sign and the number. Precede a hexadecimal number with &H. Precede an octal number with &O. Do not use commas for the decimal. In scientific notation, the e can be uppercase or lowercase. Spaces are not allowed in a number. With the space, this evaluates as 6.6 - 34 = -27.4. The exponent may contain a leading plus or minus sign. The expon