0 penilaian0% menganggap dokumen ini bermanfaat (0 suara)
103 tayangan514 halaman
In OpenOffice.org (OOo), macros and dialogs are stored in documents and libraries. The included integrated development environment (IDE) is used to create and debug macros and dialogs.
In OpenOffice.org (OOo), macros and dialogs are stored in documents and libraries. The included integrated development environment (IDE) is used to create and debug macros and dialogs.
Hak Cipta:
Attribution Non-Commercial (BY-NC)
Format Tersedia
Unduh sebagai PDF, TXT atau baca online dari Scribd
In OpenOffice.org (OOo), macros and dialogs are stored in documents and libraries. The included integrated development environment (IDE) is used to create and debug macros and dialogs.
Hak Cipta:
Attribution Non-Commercial (BY-NC)
Format Tersedia
Unduh sebagai PDF, TXT atau baca online dari Scribd
OOME Third Edition Last Modified Tuesday, September 6, 2011 at 12:20:33 AM Document Reision: !20 General Information T"e contents of t"is document is #opyri$"t 2011 by Andre% D& 'itonya(& ) %i** ma(e a fina* *icense decision %"en ) am finis"ed& ) created a second edition t"at %as neer re*eased, %"ic" is %"y ) refer to t"is boo( as t"e t"ird edition& ) "ae been repeated*y as(ed about t"e coer pa$e so&&&& ) am neit"er an artist nor a desi$ner, so, ) "ired Amanda +ar"am ,see "ttp:--%%%&amandabar"am&com.& S"e did an a%esome /ob& Table of Contents General Information...................................................................................................................1 Table of Contents........................................................................................................................i 1. Introduction and housekeeping...........................................................................................11 1.1. Comments from the author..........................................................................................11 1.2. OpenOffice.org Bug....................................................................................................11 1.3. Environment and comments........................................................................................11 2. Getting Started....................................................................................................................12 2.1. Macro storage..............................................................................................................12 2.1.1. Library container.................................................................................................12 2.1.2. Libraries...............................................................................................................13 2.1.3. Modules and dialogs............................................................................................14 2.1.4. Key points............................................................................................................14 2.2. Creating new modules and libraries............................................................................14 2.3. Macro language...........................................................................................................16 2.4. Create a module in a document...................................................................................16 2.5. Integrated Debugging Environment............................................................................19 2.6. Enter the macro...........................................................................................................22 2.7. Run a macro................................................................................................................23 2.8. Macro security.............................................................................................................23 2.9. Using breakpoints........................................................................................................26 2.10. How libraries are stored............................................................................................26 2.11. How documents are stored........................................................................................27 2.12. Conclusion.................................................................................................................28 3. Language Constructs...........................................................................................................29 3.1. Compatibility with Visual Basic.................................................................................30 3.2. Compiler options and directives..................................................................................31 3.3. Variables.....................................................................................................................31 3.3.1. Constant, subroutine, function, label, and variable names..................................31 3.3.2. Declaring variables..............................................................................................32 3.3.3. Assigning values to variables..............................................................................34 3.3.4. Boolean variables are True or False....................................................................34 3.3.5. Numeric variables................................................................................................35 Integer variables.........................................................................................................36 Long Integer variables...............................................................................................37 Currency variables.....................................................................................................37 Single variables..........................................................................................................38 Double variables........................................................................................................38 3.3.6. String variables contain text................................................................................39 3.3.7. Date variables......................................................................................................40 3.3.8. Create your own data types.................................................................................41 3.3.9. Declare variables with special types....................................................................42 i 3.3.10. Object variables.................................................................................................43 3.3.11. Variant variables................................................................................................43 3.3.12. Constants...........................................................................................................44 3.4. The With statement.....................................................................................................45 3.5. Arrays..........................................................................................................................45 3.5.1. Changing the dimension of an array....................................................................48 3.5.2. The unexpected behavior of arrays......................................................................50 3.6. Subroutines and functions...........................................................................................52 3.6.1. Arguments...........................................................................................................53 Pass by reference or by value....................................................................................53 Optional arguments....................................................................................................56 Default argument values............................................................................................57 3.6.2. Recursive routines...............................................................................................57 3.7. Scope of variables, subroutines, and functions...........................................................59 3.7.1. Local variables defined in a subroutine or function ...........................................59 3.7.2. Variables defined in a module.............................................................................59 Global........................................................................................................................60 Public.........................................................................................................................60 Private or Dim............................................................................................................61 3.8. Operators.....................................................................................................................61 3.8.1. Mathematical and string operators......................................................................63 Unary plus (+) and minus (-).....................................................................................63 Exponentiation (^).....................................................................................................63 Multiplication (*) and Division (/)............................................................................64 Remainder after division (MOD)...............................................................................64 Integer division (\).....................................................................................................65 Addition (+), subtraction (-), and string concatenation (& and +).............................66 3.8.2. Logical and bit-wise operators............................................................................66 AND...........................................................................................................................69 OR..............................................................................................................................69 XOR...........................................................................................................................70 EQV...........................................................................................................................70 IMP............................................................................................................................71 NOT...........................................................................................................................72 3.8.3. Comparison operators..........................................................................................72 3.9. Flow control................................................................................................................73 3.9.1. Define a label as a jump target............................................................................73 3.9.2. GoSub..................................................................................................................73 3.9.3. GoTo....................................................................................................................74 3.9.4. On GoTo and On GoSub.....................................................................................74 3.9.5. If Then Else.........................................................................................................75 ii 3.9.6. IIf.........................................................................................................................76 3.9.7. Choose.................................................................................................................76 3.9.8. Select Case...........................................................................................................77 Case expressions........................................................................................................77 If Case statements are easy, why are they frequently incorrect?...............................78 Writing correct Case expressions..............................................................................79 3.9.9. While ... Wend.....................................................................................................81 3.9.10. Do ... Loop.........................................................................................................81 Exit the Do Loop.......................................................................................................82 Which Do Loop should I use?...................................................................................82 3.9.11. For ... Next.........................................................................................................83 3.9.12. Exit Sub and Exit Function................................................................................85 3.10. Error handling using On Error..................................................................................85 3.10.1. CVErr................................................................................................................86 3.10.2. Ignore errors with On Error Resume Next........................................................87 3.10.3. Clear an error handler with On Error GoTo 0...................................................88 3.10.4. Specify your own error handler with On Error GoTo Label.............................88 3.10.5. Error handlers why use them?......................................................................90 3.11. Conclusion.................................................................................................................92 4. Numerical Routines............................................................................................................93 4.1. Trigonometric functions..............................................................................................94 4.2. Rounding errors and precision....................................................................................96 4.3. Mathematical functions...............................................................................................99 4.4. Numeric conversions.................................................................................................100 4.5. Number to string conversions...................................................................................106 4.6. Simple formatting......................................................................................................106 4.7. Other number bases, hexadecimal, octal, and binary................................................107 4.8. Random numbers .....................................................................................................110 4.9. Conclusion.................................................................................................................111 5. Array Routines..................................................................................................................112 5.1. Array() quickly builds a one-dimensional array with data........................................113 5.2. DimArray creates empty multi-dimensional arrays..................................................115 5.3. Change the dimension of an array.............................................................................116 5.4. Array to String and back again..................................................................................117 5.5. Array inspection functions........................................................................................118 5.6. Conclusion.................................................................................................................121 6. Date Routines....................................................................................................................122 6.1. Retrieve the current date and time............................................................................123 6.2. Dates, numbers, and strings......................................................................................123 6.3. Locale formatted dates..............................................................................................125 6.4. ISO 8601 dates..........................................................................................................125 iii 6.5. Problems with dates..................................................................................................126 6.6. Extract each part of a date.........................................................................................130 6.7. Date arithmetic..........................................................................................................134 6.8. Assembling dates from components.........................................................................135 6.9. Measuring elapsed time over short intervals.............................................................136 6.10. How fast does this run? A real-world example!......................................................138 6.11. Long time intervals and special dates.....................................................................141 6.12. Conclusion...............................................................................................................142 7. String Routines..................................................................................................................143 7.1. ASCII and Unicode values........................................................................................145 7.2. Standard string functions...........................................................................................148 7.3. Substrings..................................................................................................................152 7.4. Replace......................................................................................................................153 7.5. Aligning strings with LSet and RSet.........................................................................154 7.6. Fancy formatting with Format..................................................................................156 7.7. Converting data to a string........................................................................................160 7.8. Advanced searching..................................................................................................162 7.9. Conclusion.................................................................................................................163 8. File Routines.....................................................................................................................164 8.1. Using URL notation to specify a file........................................................................165 8.2. Directory manipulation functions.............................................................................166 8.3. File manipulation functions.......................................................................................167 8.4. File attributes, bitmasks, and binary numbers...........................................................170 8.5. Obtaining a directory listing......................................................................................172 8.6. Open a file.................................................................................................................173 8.7. Information about open files.....................................................................................175 8.8. Reading and writing data..........................................................................................178 8.9. File and directory related services.............................................................................185 8.9.1. Path Settings......................................................................................................185 8.9.2. Path Substitution................................................................................................188 8.9.3. Simple File Access............................................................................................190 8.9.4. Streams..............................................................................................................191 8.9.5. Pipes..................................................................................................................194 8.10. Conclusion...............................................................................................................195 9. Miscellaneous Routines....................................................................................................196 9.1. Display and color .....................................................................................................196 9.1.1. Determine the GUI type....................................................................................196 9.1.2. Determine pixel size (in twips)..........................................................................197 9.1.3. Use color functions............................................................................................198 9.2. Flow control..............................................................................................................200 9.2.1. Return an argument...........................................................................................201 iv 9.2.2. Pause or end the macro......................................................................................202 9.2.3. Dynamic Link Libraries....................................................................................203 9.2.4. Calling external applications.............................................................................204 9.2.5. Dynamic Data Exchange...................................................................................205 9.3. User input and output................................................................................................206 9.3.1. Simple output.....................................................................................................207 9.3.2. Multi-line output................................................................................................208 9.3.3. Prompting for input...........................................................................................211 9.4. Error-related routines................................................................................................212 9.5. Miscellaneous routines..............................................................................................213 9.6. Partition.....................................................................................................................216 9.7. Inspection and identification of variables.................................................................218 9.8. Routines you should not use and other curiosities....................................................224 9.9. Routines I do not understand.....................................................................................225 9.10. Conclusion...............................................................................................................226 10. Universal Network Objects.............................................................................................227 10.1. Base types and structures........................................................................................228 10.2. UNO interface.........................................................................................................230 10.3. UNO service............................................................................................................231 10.4. Context....................................................................................................................234 10.5. Inspecting Universal Network Objects...................................................................234 10.6. Use Object or Variant..............................................................................................239 10.7. Comparing UNO variables......................................................................................240 10.8. Built-in global UNO variables................................................................................241 10.9. Creating UNO values for OOo internals.................................................................244 10.10. Finding objects and properties..............................................................................245 10.11. UNO listeners........................................................................................................246 10.11.1. Your first listener...........................................................................................247 10.11.2. A complete listener: selection change listener..............................................248 10.12. Creating a UNO dialog..........................................................................................250 10.13. Conclusion.............................................................................................................254 11. The Dispatcher................................................................................................................255 11.1. The environment.....................................................................................................255 11.1.1. Two different methods to control OOo...........................................................255 11.1.2. Finding dispatch commands............................................................................257 Use the WIKI...........................................................................................................257 Probe the interface...................................................................................................257 Read source code.....................................................................................................260 11.2. Writing a macro using the dispatcher......................................................................260 11.3. Conclusion...............................................................................................................260 12. StarDesktop.....................................................................................................................261 v 12.1. The Frame service...................................................................................................261 12.1.1. The XIndexAccess interface............................................................................262 12.1.2. Find frames with FrameSearchFlag constants.................................................262 12.2. The XEventBroadcaster interface...........................................................................264 12.3. The XDesktop interface..........................................................................................264 12.3.1. Closing the desktop and contained components..............................................265 12.3.2. Enumerating components using XEnumerationAccess...................................265 12.3.3. Current component..........................................................................................267 12.3.4. Current component (again)..............................................................................267 12.3.5. Current frame...................................................................................................267 12.4. Load a document.....................................................................................................268 12.4.1. Named parameters...........................................................................................272 12.4.2. Loading a template..........................................................................................275 12.4.3. Enabling macros while loading a document....................................................275 12.4.4. Importing and exporting..................................................................................276 12.4.5. Filter names.....................................................................................................277 12.4.6. Loading and saving documents.......................................................................283 12.4.7. Error handling while loading a document.......................................................285 12.5. Conclusion...............................................................................................................285 13. Generic Document Methods...........................................................................................286 13.1. Service Manager......................................................................................................286 13.2. Services and interfaces............................................................................................287 13.3. Getting and setting properties.................................................................................288 13.4. Document properties...............................................................................................290 13.4.1. Document properties from a closed document................................................292 13.4.2. Custom properties............................................................................................292 13.4.3. Deprecated document information object.......................................................293 13.5. List events...............................................................................................................294 13.5.1. Registering your own listener..........................................................................295 13.5.2. Intercepting dispatch commands.....................................................................296 13.6. Link targets..............................................................................................................299 13.7. Accessing view data: XViewDataSupplier.............................................................300 13.8. Close a document: XCloseable...............................................................................301 13.9. Draw Pages: XDrawPagesSupplier ........................................................................302 13.9.1. Draw and Impress............................................................................................302 13.9.2. Draw lines with arrows in Calc.......................................................................305 13.9.3. Writer...............................................................................................................307 13.10. The model..............................................................................................................308 13.10.1. Document arguments.....................................................................................308 13.11. Saving a document................................................................................................311 13.12. Manipulating styles...............................................................................................313 vi 13.13. Dealing with locale...............................................................................................319 13.14. Enumerating printers.............................................................................................326 13.15. Printing documents................................................................................................327 13.15.1. Printing Writer documents............................................................................331 13.15.2. Printing Calc documents................................................................................333 13.15.3. A Calc example with a Print listener.............................................................334 13.15.4. Print examples by Vincent Van Houtte.........................................................336 13.16. Creating services...................................................................................................346 13.17. Document settings.................................................................................................347 13.18. The coolest trick I know........................................................................................349 13.19. Converting to a URL in other languages...............................................................349 13.20. Conclusion.............................................................................................................349 14. Writer Documents...........................................................................................................350 14.1. Basic building blocks..............................................................................................351 14.1.1. Primary text content: the XText interface.......................................................351 14.1.2. Text ranges: the XTextRange interface...........................................................352 14.1.3. Inserting simple text........................................................................................354 14.1.4. Text content: the TextContent service.............................................................354 14.2. Enumerating paragraphs..........................................................................................356 14.2.1. Paragraph properties........................................................................................357 Insert a page break...................................................................................................361 Set the paragraph style.............................................................................................361 14.2.2. Character properties.........................................................................................362 14.2.3. Enumerating text sections (paragraph portions)..............................................366 14.3. Graphics..................................................................................................................368 14.4. Cursors....................................................................................................................373 14.4.1. View cursors....................................................................................................373 14.4.2. Text (non-view) cursors..................................................................................375 14.4.3. Using cursors to traverse text..........................................................................376 Keep the view cursor and text cursor in sync..........................................................378 14.4.4. Accessing content using cursors......................................................................379 14.5. Selected text............................................................................................................382 14.5.1. Is text selected?................................................................................................382 14.5.2. Selected text: Which end is which?.................................................................383 14.5.3. Selected text framework..................................................................................384 14.5.4. Remove empty spaces and lines: A larger example........................................386 What is white space?...............................................................................................386 Rank characters for deletion....................................................................................387 Use the standard framework....................................................................................388 The worker macro....................................................................................................388 14.5.5. Selected text, closing thoughts........................................................................390 vii 14.6. Search and replace...................................................................................................390 14.6.1. Searching selected text or a specified range....................................................392 Searching for all occurrences.......................................................................................392 14.6.2. Searching and replacing..................................................................................393 14.6.3. Advanced search and replace..........................................................................394 14.7. Text content.............................................................................................................397 14.8. Text tables...............................................................................................................397 14.8.1. Using the correct text object............................................................................400 14.8.2. Methods and properties...................................................................................401 14.8.3. Simple and complex tables..............................................................................403 14.8.4. Tables contain cells.........................................................................................404 14.8.5. Using a table cursor.........................................................................................406 14.9. Text fields................................................................................................................409 14.9.1. Text master fields............................................................................................417 14.9.2. Creating and adding text fields........................................................................419 14.10. Bookmarks............................................................................................................422 14.11. Sequence fields, references, and formatting.........................................................423 14.11.1. Formatting numbers and dates.......................................................................423 List formats known to the current document know.................................................423 Find or create a numeric format...............................................................................424 Default formats........................................................................................................425 14.11.2. Create a field master......................................................................................425 14.11.3. Insert a sequence field...................................................................................426 14.11.4. Replace text with a sequence field................................................................427 14.11.5. Create a GetReference field...........................................................................429 14.11.6. Replace text with a GetReference field.........................................................430 14.11.7. The worker that ties it all together.................................................................432 14.12. Table of contents...................................................................................................433 14.13. Conclusion.............................................................................................................439 15. Calc Documents..............................................................................................................440 15.1. Accessing sheets......................................................................................................441 15.2. Sheet cells contain the data.....................................................................................443 15.2.1. Cell address.....................................................................................................444 15.2.2. Cell data...........................................................................................................444 15.2.3. Cell properties.................................................................................................446 15.2.4. Cell annotations...............................................................................................450 15.3. Uninterpreted XML Attributes................................................................................451 15.4. Sheet cell ranges......................................................................................................452 15.4.1. Sheet cell range properties...............................................................................453 Validation settings...................................................................................................453 Conditional formatting.............................................................................................456 viii 15.4.2. Sheet cell range services..................................................................................456 Retrieving cells and ranges......................................................................................456 Querying cells..........................................................................................................457 Finding non-empty cells in a range.........................................................................458 Using complex queries............................................................................................459 Query Precedents................................................................................................461 15.4.3. Searching and replacing..................................................................................462 15.4.4. Merging cells...................................................................................................462 15.4.5. Retrieving, inserting, and deleting columns and rows....................................463 15.4.6. Retrieving and setting data as an array............................................................465 15.4.7. Computing functions on a range......................................................................466 15.4.8. Clearing cells and cell ranges..........................................................................467 15.4.9. Automatic data fill...........................................................................................467 15.4.10. Array formulas...............................................................................................469 15.4.11. Computing multiple functions on a range.....................................................470 15.4.12. Cells with the same formatting......................................................................472 15.4.13. Sorting...........................................................................................................474 15.5. Sheets......................................................................................................................478 15.5.1. Linking to an external spreadsheet..................................................................479 15.5.2. Finding dependencies by using auditing functions.........................................480 15.5.3. Outlines............................................................................................................483 15.5.4. Copying, moving, and inserting cells..............................................................483 15.5.5. Copy data between documents........................................................................484 Data functions..........................................................................................................484 Clipboard.................................................................................................................484 Transferable content................................................................................................485 15.5.6. Data pilot and pivot tables...............................................................................486 A data pilot example................................................................................................486 Generating the data.............................................................................................487 Creating the data pilot table................................................................................488 Manipulating data pilot tables.................................................................................490 Data pilot fields...................................................................................................490 Filtering data pilot fields.....................................................................................491 Tables..................................................................................................................492 15.5.7. Sheet cursors....................................................................................................493 15.6. Calc documents.......................................................................................................495 15.6.1. Named range....................................................................................................495 15.6.2. Database range.................................................................................................498 15.6.3. Filters...............................................................................................................499 15.6.4. Protecting documents and sheets.....................................................................502 15.6.5. Controlling recalculation.................................................................................502 ix 15.6.6. Using Goal Seek..............................................................................................502 15.7. Writing your own spreadsheet functions.................................................................503 15.8. Using the current controller....................................................................................504 15.8.1. Selected cells...................................................................................................505 Enumerating the selected cells.................................................................................506 Selecting text...........................................................................................................507 The active cell..........................................................................................................507 15.8.2. General functionality.......................................................................................508 15.9. Control Calc from Microsoft Office.......................................................................510 15.10. Accessing Calc functions......................................................................................511 15.11. Conclusion.............................................................................................................511 x 1. Introduction and housekeeping 0irst, t"ere %as t"e first edition of 1pen1ffice&or$ Macros 23p*ained ,11M2.& A fe% years *ater ) produced t"e second edition, updated to matc" 1pen1ffice&or$ ,11o. ersion 2&3, but t"e second edition %as neer re*eased& 4o%, ) fee* t"at it is time for a t"ird edition& Most of t"e content from preious editions is sti** "ere& T"e initia* c"apters dea*in$ %it" *an$ua$e synta3 are most*y unc"an$ed e3cept for t"e ne% features added to t"e *an$ua$e& T"e number of serices supported by 11o "as more t"an doub*ed since ) *ast pub*is"ed, and t"ere is si$nificant ne% capabi*ity& T"ere is, unfortunate*y, more capabi*ity t"an ) "ae time or room to document& 5nfortunate*y, as e3tensie as t"is boo( is, muc" is missin$& 6ou s"ou*d use t"is boo(, t"erefore, as a reference %it" numerous e3amp*es, but, a*%ays remember t"at 11o is constant*y c"an$in$ and supportin$ more features& T"e document contains buttons t"at tri$$er t"e macros in t"e te3t& T"is is fabu*ous %"i*e readin$ t"e ori$ina* source, but it proides for undesirab*e artifacts in printed form7 sorry about t"at& 1.1. Comments from the author ) am t"e primary aut"or of t"is document& ) do not ma(e a *iin$ %or(in$ %it" 11o, and not"in$ in "ere is re*ated to my primary day /ob& )n ot"er %ords, ) am simp*y anot"er member of t"e 11o community %"o does t"is most*y %it"out remuneration& ) receie numerous re8uests for "e*p because ) am "i$"*y isib*e in t"e 11o community& 5nfortunate*y, ) am oer9time9committed, and it is difficu*t to proide persona* "e*p to a**& ) en/oy "e*pin$ peop*e in my non9 e3istent spare time, but, be certain to use e3istin$ materia*, mai*in$ *ists, and forums if possib*e& ) occasiona**y proide so*utions on a commission basis, but ) *ac( t"e time for *ar$e tas(s& ) appreciate comments and bu$ reports& )f you "ae somet"in$ interestin$ t"at you t"in( s"ou*d be inc*uded, *et me (no%& )f you %ant to %rite an entire section or c"apter, do so& ) %i** *i(e*y "i$"*y edit %"at you produce& '*ease, proide feedbac( and su$$estions by sendin$ an emai* to andre%:pitonya(&or$& 1.2. OpenOffice.org Bug 11o uses sty*es to perform formattin$& ;"en somet"in$ c"an$es in t"e formattin$, t"erefore, you can assume t"at a different sty*e is used& ) use nice*y formatted code *istin$s, but, eery time t"e formattin$ c"an$es, t"is is a sty*e c"an$e& 11o "as a bu$ %"en a sty*e c"an$es more t"an 6!< times t"at causes 11o to cras" ,see "ttp:--%%%&openoffice&or$-issues-s"o%=bu$&c$i>id?@!1AB., %"ic" is %"y Andre%Macro&odt causes 11o to cras" %"en t"e document is c*osed& ) e3pect t"at t"is document %i** "ae t"e same prob*em& ;"en ) reac" t"at point, t"is document %i** become most*y use*ess& So, if you "ae otes aai*ab*e, ote for issue @!1AB& Tip A fi3 is sc"edu*ed to be re*eased in 11o ersion 3&!& ) s"ou*d persona**y t"an( +artosC, a community member, and a** t"e ot"ers %"o %or(ed for a reso*ution of t"is bu$& 1.3. Environment and comments T"e primary %or( on t"is boo( %as performed usin$ t"e 6!9bit 1fficia* Linu3 ersion runnin$ on 0edora Linu3& Some bu$s %ere found based on t"e 6!9bit distribution& T"e te3t probab*y contains errors, and ) *i(e to "ear about t"em& 11 2. Getting tarted )n 1pen1ffice&or$ ,11o., macros and dia*o$s are stored in documents and *ibraries& T"e inc*uded inte$rated dee*opment enironment ,)D2. is used to create and debu$ macros and dia*o$s& T"is c"apter introduces t"e basic concepts of startin$ t"e )D2 and creatin$ macros by s"o%in$ t"e steps to produce a simp*e macro, %"ic" disp*ays t"e te3t DEe**o ;or*dF on t"e screen& A macro is a saed se8uence of commands or (eystro(es stored for *ater use& An e3amp*e of a simp*e macro is one t"at DtypesF your address& Macros support commands t"at a**o% a ariety of adanced functions, suc" as ma(in$ decisions ,for e3amp*e, if t"e ba*ance is *ess t"an Cero, co*or it red7 if not, co*or it b*ac(., *oopin$ ,%"i*e t"e ba*ance is $reater t"an Cero, subtract 10., and een interactin$ %it" a person ,as(in$ t"e user for a number.& Some of t"ese commands are based on t"e +AS)# pro$rammin$ *an$ua$e& ,+AS)# is an acronym for +e$innerGs A**9purpose Symbo*ic )nstruction #ode&. )t is common to assi$n a macro to a (eystro(e or too*bar icon so t"at it can be 8uic(*y started& A dia*o$ H or dia*o$ bo3 H is a type of %indo% used to "ae a Ddia*o$F %it" a user& T"e dia*o$ may present information to t"e user, or obtain input from t"e user& 6ou can create your o%n dia*o$s and store t"em in a modu*e %it" your macros& T"e 1pen1ffice&or$ macro *an$ua$e is ery f*e3ib*e, a**o%in$ automation of bot" simp*e and comp*e3 tas(s& A*t"ou$" %ritin$ macros and *earnin$ about t"e inner %or(in$s of 1pen1ffice&or$ can be a *ot of fun, it is not a*%ays t"e best approac"& Macros are especia**y usefu* %"en you "ae to do a tas( t"e same %ay oer and oer a$ain, or %"en you %ant to press a sin$*e button to do somet"in$ t"at norma**y ta(es seera* steps& 1nce in a %"i*e, you mi$"t %rite a macro to do somet"in$ you canGt ot"er%ise do in 1pen1ffice&or$, but in t"at case you s"ou*d inesti$ate t"orou$"*y to be sure 11o cannot do it& 0or instance, a common re8uest on some of t"e 1pen1ffice&or$ mai*in$ *ists is for a macro t"at remoes empty para$rap"s& T"is functiona*ity is proided %it" Auto0ormat ,se*ect Tools > AutoCorrect Options > Options tab and c"ec( Remove blank paragraphs.& )t is a*so possib*e to use re$u*ar e3pressions to searc" for and rep*ace empty space& T"ere is a time and a purpose for macros, and a time for ot"er so*utions& T"is c"apter %i** prepare you for t"e times %"en a macro is t"e so*ution of c"oice& 2.1. Macro storage )n 1pen1ffice&or$, routines t"at are *o$ica**y re*ated are stored in a modu*e& 0or e3amp*e, a modu*e mi$"t contain routines for findin$ common mista(es t"at re8uire editin$& Lo$ica**y re*ated modu*es are stored in a *ibrary, and *ibraries are stored in *ibrary containers& T"e 1pen1ffice&or$ app*ication can act as a *ibrary container, as can any 11o document& Simp*y stated, t"e 1pen1ffice&or$ app*ication and eery 1pen1ffice&or$ document can contain *ibraries, modu*es, and macros& #ontainer A *ibrary container contains Cero or more *ibraries& Library A *ibrary contains Cero or more modu*es and dia*o$s& Modu*e A modu*e contains Cero or more subroutines or functions& 2.1.1. !ibrar" container An 11o document is a *ibrary container, as is t"e app*ication itse*f& )f a specific document re8uires a macro, it is usefu* to store t"at macro in t"e document& T"e adanta$e is t"at t"e macro stays %it" t"e document& T"is is a*so an easy %ay to send macros to ot"ers& )f seera* documents use t"e same macros, "o%eer, t"en eery document %i** "ae a copy, and, if you c"an$e t"e macro, t"en you must c"an$e it in eery document t"at contains t"e macro& Macros contained in 12 a document are isib*e on*y to t"at document& )t is not easy, t"erefore, to ca** a macro in a document from outside of t"at document& TIP Do not ,e3cept in rare e3ceptions. store macros t"at %i** be ca**ed from outside a document in a document7 because macros contained in a document are isib*e on*y to t"at document& T"e app*ication *ibrary container "as t%o primary components, macros distributed %it" 11o, and macros t"at you create& T"e 11o macro dia*o$ s"o%s your macros in a container named DMy MacrosF, and t"ose distributed as D1pen1ffice&or$ MacrosF ,see 0i$ure 1.& 1pen1ffice&or$ Macros are stored in a directory %it" t"e app*ication, and My Macros are stored in your user directories& 5se Tools > Macros > Organize Macros > OpenOffice.org Basic to open t"e 11o +asic Macros dia*o$ ,see 0i$ure 1.& T"e *ibrary containers are t"e "i$"est *ee* ob/ects s"o%n in t"e DMacro fromF area& Figure 1. Use the OOo Macros dialog to create new macros and organize libraries. 2.1.2. !ibraries A library container contains one or more *ibraries, and a library contains one or more modu*es and dia*o$s& Doub*e9c*ic( on a *ibrary container in 0i$ure 1 to see t"e contained *ibraries& Doub*e9c*ic( on a *ibrary to *oad t"e *ibrary and see t"e contained modu*es and dia*o$s& T"e 11o Macros dia*o$ uses a different icon to distin$uis" *oaded *ibraries7 in 0i$ure 2, Standard and IrayDyn are *oaded, t"e ot"er *ibraries are not& TIP T"e icons and co*ors t"at you see on your computer may be different t"an t"ose s"o%n in t"e screen s"ots& Different ersions of 11o may use different icons and co*ors& and more t"an one icon set is supported& 5se Tools > Options > OpenOffice.org > View to c"an$e t"e icon siCe and sty*e& 13 Figure 2. Loaded libraries are shown differently. 2.1.#. Modules and dialogs A modu*e is typica**y used to $roup simi*ar functiona*ity at a *o%er *ee* t"an a *ibrary& T"e macros are stored in t"e modu*es& To create a ne% modu*e, se*ect a *ibrary and c*ic( 4e%& 2.1.$. %e" points T"in$s to consider: 6ou can import *ibraries from one *ibrary container to anot"er& )mport a modu*e by importin$ t"e *ibrary t"at contains t"e modu*e& )t is not possib*e to simp*y import a sin$*e modu*e usin$ t"e J5)& 5se descriptie names for *ibraries, modu*es, and macros& Descriptie names reduce t"e *i(e*i"ood of a name co**ision, %"ic" "ampers *ibrary import& T"e Standard *ibrary is specia*7 it is automatica**y *oaded so t"e contained macros are a*%ays aai*ab*e& T"e Standard *ibrary is automatica**y created by 11o and cannot be imported& Macros contained in a *ibrary are not aai*ab*e unti* after t"e *ibrary is *oaded& T"e Macro or$aniCer dia*o$ a**o%s you to create ne% modu*es, but not ne% *ibraries& T"e (ey points *isted aboe "ae certain conse8uences7 for e3amp*e, ) rare*y store macros in t"e Standard *ibrary because ) cannot import t"e *ibrary to anot"er *ocation& My usua* usa$e for t"e standard *ibrary is for macros ca**ed from buttons in a document& T"e macros in t"e standard *ibrary t"en *oad t"e actua* %or( macros in ot"er *ibraries, and ca** t"em& 2.2. Creating new modules and libraries T"e 4e% button on t"e Macros dia*o$ a*%ays creates a ne% subroutine in t"e se*ected *ibrary ,see 0i$ure 1 and 0i$ure 2.& A ne% modu*e is created if t"e *ibrary does not yet contain a modu*e& 14 0rom t"e Macros dia*o$, c*ic( t"e 1r$aniCer button to open t"e 11o Macro 1r$aniCer dia*o$ ,see 0i$ure 3.& T"e Modu*es and Dia*o$s tabs are a*most identica*& 5se t"e Modu*es or Dia*o$s tab to create, de*ete, and rename modu*es or dia*o$s& Figure 3. Modules tab of the OOo Macro Organizer dialog. 5se t"e Libraries tab ,see 0i$ure !. to create, de*ete, rename, import, and e3port *ibraries& Figure 4. Libraries tab of the OOo Macro Organizer dialog. T"e first step is to se*ect t"e desired *ibrary container from t"e Location drop9do%n& To rename a *ibrary, doub*e c*ic( on t"e *ibrary and t"en edit t"e name in p*ace& 15 TIP ) find renamin$ modu*es and *ibraries in t"e Macro 1r$aniCer dia*o$s to be frustratin$& 0or renamin$ *ibraries, doub*e or trip*e c*ic( on t"e *ibrary name t"en %ait a fe% seconds& Try a$ain& Try one more time& #*ic( on anot"er *ibrary& Doub*e or trip*e c*ic( on t"e *ibrary name7 you $et t"e idea& T"e easiest met"od to c"an$e a modu*e name is to ri$"t c*ic( on t"e modu*e name in t"e tabs at t"e bottom of t"e )D2 and c"oose rename ,see 0i$ure 11.& 2.3. Macro language T"e 1pen1ffice&or$ macro *an$ua$e is based on t"e +AS)# pro$rammin$ *an$ua$e& T"e standard macro *an$ua$e is officia**y tit*ed Star+asic, but, it is a*so referred to as 11o +asic, or +asic& Many different pro$rammin$ *an$ua$es can be used to automate 11o& 11o proides easy support for macros %ritten in +asic, KaaScript, 'yt"on, and +eanS"e**& )n t"is document, my primary concern is +asic& 2.4. Create a module in a document 2ac" 11o document is a *ibrary container ab*e to contain macros and dia*o$s& ;"en a document contains t"e macros t"at it uses, possession of t"e document imp*ies possession of t"e macros& T"is is a conenient distribution and stora$e met"od& Send t"e document to anot"er person or *ocation, and t"e macros are sti** aai*ab*e and usab*e& 1. To add a macro to any 11o document, t"e document must be open for editin$& Start by openin$ a ne% te3t document, %"ic" %i** be named D5ntit*ed 1F L assumin$ t"at no ot"er untit*ed document is current*y open& 2. 5se Tools > Macros > Organize Macros > OpenOffice.org Basic to open t"e 11o +asic Macros dia*o$ ,see 0i$ure 1.& 3. #*ic( t"e 1r$aniCer button to open t"e 11o Macro 1r$aniCer dia*o$, t"en c*ic( on t"e Libraries tab ,see 0i$ure !.& !. Se*ect D5ntit*ed 1F from t"e *ocation drop9do%n& Figure 5. Libraries tab of the OOo Macro Organizer dialog. A. #*ic( 4e% to open t"e 4e% Library dia*o$& 16 Figure 6. New library dialog. 6. T"e defau*t name is Library1, %"ic" is not ery descriptie& #"oose a descriptie name and c*ic( 1<& T"e ne% *ibrary is s"o%n in t"e *ist& 0or t"is e3amp*e, ) named t"e *ibrary DEe**o;or*dF& Figure 7. he new library is shown in the list. M. )n t"e Modu*es tab, se*ect t"e Ee**o;or*d *ibrary& 11o created t"e modu*e named DModu*e1F %"en t"e *ibrary %as created& Tip A*t"ou$" Modu*e1 is created %"en t"e *ibrary is created, a bu$ in 11o 3&2 may preent t"e modu*e from disp*ayin$ %it"out c*osin$ and re9openin$ t"e dia*o$& 17 Figure 8. he new library is shown in the list. @. #*ic( 4e% to open t"e 4e% Modu*e dia*o$& T"e defau*t name is Modu*e2, because Modu*e1 a*ready e3ists& Figure 9. New module dialog. B. 5se a descriptie name and c*ic( 1<& Modu*e1 is fina**y disp*ayed ,bu$ in 3&2&0., as is t"e ne%*y created modu*e& 18 Figure 10. he new module is shown in the list. 10. Se*ect Ee**oModu*e and c*ic( 2dit& 11. At t"is point, ) saed t"e document and named it DDe*MeDocF because ) intended to de*ete t"e document %"en ) %as finis"ed %it" t"e e3amp*e& Se*ect a name t"at %or(s %e** for you& )f you reopen t"e dia*o$ s"o%n in 0i$ure 10, t"e document name %i** be s"o%n rat"er t"an D5ntit*ed 1F& At t"is point, t"e )nte$rated Debu$$in$ 2nironment ,)D2. is opened to edit t"e macro& 2.. !ntegrated "ebugging Environment 5se t"e +asic )nte$rated Debu$$in$ 2nironment ,)D2. to create and run macros ,see 0i$ure 11.& T"e )D2 p*aces si$nificant functiona*ity in a *itt*e space& T"e too*bar icons are described in Tab*e 1& T"e top *eft corner /ust aboe t"e editin$ %indo% contains a drop9do%n *ist t"at s"o%s t"e current *ibrary& T"e portion in t"e s8uare brac(ets identifies t"e *ibrary container, and t"e portion fo**o%in$ identifies t"e *ibrary& T"is proides a 8uic( met"od to c"oose a *ibrary& 19 Figure 11. !asic "ntegrated #ebugging $nvironment. Rest your mouse cursor on a too*bar icon for a fe% seconds to read t"e te3t t"at appears7 t"is proides a "int at %"at t"at icon does& Table 1. oolbar icons in the !asic "#$. Icon Key Description #tr*N4 #reate a ne% 11o document& #tr*N1 1pen an e3istin$ 11o document& #tr*NS Sae t"e current *ibrary& )f t"e *ibrary is in a document, t"en t"e document is saed& #tr*N' 'rint t"e macro to t"e printer& #tr*NO 'aste t"e c*ipboard& #tr*NP 5ndo t"e *ast operation& #tr*NO Redo t"e *ast operation t"at %as undone& 1pen t"e 1b/ect cata*o$ ,see 0i$ure 12.& Se*ect t"e macro and doub*e9c*ic( on t"e macro& 1pen t"e 11o Macros dia*o$ ,see 0i$ure 2.& Se*ect a macro and c*ic( edit or run& T"is is a s"ort9 cut for Tools > Macros > Organize Macros > OpenOffice.org Basic& 20 Icon Key Description Se*ect a modu*e& T"is opens t"e 11o Macro 1r$aniCer dia*o$ %it" t"e Modu*es tab se*ected ,see 0i$ure 3.& Se*ect a modu*e and c*ic( 2dit& 1pen t"e 11o "e*p, %"ic" contains numerous usefu* e3amp*es for +asic& #*ic( t"e #ompi*e icon to c"ec( t"e macro for synta3 errors& 4o messa$e is disp*ayed un*ess an error is found& T"e #ompi*e icon compi*es on*y t"e current modu*e& 0A Run t"e first macro in t"e current modu*e& ;"i*e stopped ,from a brea(point, or sin$*e steppin$, t"is continues t"e e3ecution.& To run a specific macro, use to open t"e 11o +asic Macros dia*o$, se*ect t"e desired macro, and c*ic( Run& S"iftN0A Stop t"e current*y runnin$ macro& S"iftN0@ Step oer t"e current statement& ;"en a macro stops at a brea(point, t"is e3ecutes t"e current statement& #an a*so be used to start a macro runnin$ in sin$*e step mode& 0@ Step into& T"is is t"e same as Step oer e3cept if t"e current statement ca**s anot"er macro, it sin$*e steps into t"at macro so t"at you can %atc" t"at macro e3ecute& Step out runs t"e macro to t"e end of t"e current subroutine or function& S"iftN0B To$$*es a brea(point on - off at t"e current cursor position in t"e )D2& An icon , . is disp*ayed to t"e *eft of t"e *ine to s"o% t"at a brea(point is set for t"at *ine& 6ou can a*so doub*e9c*ic( in t"e brea(point area to to$$*e a brea(point on - off& 1pen t"e mana$e brea(points dia*o$ ,see 0i$ure 1M., %"ic" a**o%s you to se*ectie*y turn brea(points on or off, and a*so, to preent a brea(point from tri$$erin$ unti* it "as been reac"ed a certain number of times& 0M Se*ect a ariab*e and c*ic( t"e ;atc" icon to add t"e ariab*e to t"e %atc" %indo%& 6ou can a*so enter t"e ariab*e name into t"e ;atc" input *ine and press enter& 0ind parent"eses& )nsert +asic source& 1pen a dia*o$ to se*ect a preious*y saed basic fi*e and insert it& Sae t"e current modu*e as a te3t fi*e on dis(& 11o stores modu*es on dis( in a specia* encoded format& 0i*es saed usin$ t"is met"od are standard te3t fi*es& T"is is an e3ce**ent %ay to create a bac(up of a macro or to create a te3t fi*e t"at can be easi*y sent to anot"er person& T"is is different from t"e Dis( icon, %"ic" is used to sae t"e entire *ibrary or document t"at contains t"e modu*e& )mport a dia*o$ from anot"er modu*e& Modu*e names are *isted a*on$ t"e bottom of t"e )D2& Modu*e nai$ation buttons are to t"e *eft of t"e modu*e names& T"e buttons disp*ay t"e first, preious, ne3t, and *ast modu*e in t"e current *ibrary& Ri$"t c*ic( on a modu*e name to: )nsert a ne% modu*e or dia*o$& De*ete a modu*e or dia*o$& Rename a modu*e7 t"is is t"e easiest %ay t"at ) (no% to rename a modu*e or dia*o$& Eide a modu*e or dia*o$& 1pen t"e 11o +asic 1r$aniCation dia*o$& 21 5se to open t"e 1b/ects cata*o$ ,see 0i$ure 12., se*ect a macro and doub*e9c*ic( on t"e macro to edit t"at macro& Figure 12. Ob%ects catalog. 2.#. Enter the macro #"an$e t"e te3t in t"e )D2 to read as s"o%n in Listin$ 1& #*ic( t"e run icon& Listing 1. &ello 'orld macro REM ***** BASIC ***** Option Explicit Sub Main Print "Hello World" End Sub Table 2. Line by line description of Listing (. Line Description REM ***** BASIC ***** +asic comment, t"is *ine is i$nored& A comment may a*so be$in %it" a sin$*e 8uote c"aracter& Option Explicit Te**s t"e basic interpreter t"at it is an error to use a ariab*e t"at is not e3p*icit*y defined& Misspe**ed ariab*es are *i(e*y to be cau$"t as an error at compi*e time& Sub Main )ndicates t"at t"is is t"e be$innin$ of t"e definition of a subroutine named Main& Print "Hello World" T"e 'rint command& End Sub 2nd t"e Main subroutine& 22 T"e macro in Listin$ 1 is te3t t"at a "uman can read& T"e computer must trans*ate macro te3t into somet"in$ t"at t"e computer can use& T"e process of conertin$ t"e "uman readab*e macro into somet"in$ t"at t"e computer can read is ca**ed compi*in$& )n ot"er %ords, a macro is %ritten as *ines of te3t t"at are compi*ed to prepare a runnab*e pro$ram& 2.$. %un a macro T"e Run icon a*%ays runs t"e first macro in t"e current modu*e& As a resu*t, a different approac" is re8uired if more t"an one macro is in a modu*e& T"e fo**o%in$ options can be used: Place the macro first in the module, and click the Run icon. Use the first macro to call the desired macro. I like this method during development. I keep a main macro as the first thing that does nothing. During development, I change the main macro to call the macro of interest. For general use, I let the main macro at the top call the most frequently run macro. Use the Macro dialog (see Figure 2) to run any routine in the module. Add a button to your a document or toolbar that calls the macro. Assign the macro to a keystroke. Use Tools > Customize to open the Customize dialog. Select the Keyboard tab. Macro libraries are at the bottom of the Category list. This is also available with Tools > Macros > Organize Macros > OpenOffice.org Basic, select the macro, and click the Assign button to launch the Customize dialog. Various tabs in this dialog allow you to assign the macro to execute as a menu item, from a toolbar icon, or a system event. To use t"e Macro dia*o$ to run any subroutine in a modu*e, fo**o% t"ese steps: 1. Select Tools > Macros > Organize Macros > OpenOffice.org Basic to open the Macro dialog (see Figure 2). 2. Find the document that contains the module in the Macro from list. 3. Double-click a library to toggle the display of the contained modules. 4. Select the module to display the contained subroutines and functions in the Existing macros in: <selected module name> list. 5. Select the desired subroutine or function to run for example, HelloWorld. 6. Click the Run button to run the subroutine or function. 2.&. Macro securit' Dependin$ on "o% 11o is confi$ured, you may not be ab*e to run macros in a document& ;"en ) open a document containin$ a macro, t"e %arnin$ in 0i$ure 13 is disp*ayed& )f you do not e3pect a macro or do not trust t"e source, t"en c"oose to disab*e macros& Remember, ) am ab*e to %rite a macro t"at destroys your computer& 23 Figure 13. he opened document contains a macro. 5se Tools > Options > OpenOffice.org > Security to open t"e Security tab of t"e 1ptions dia*o$& Figure 14. Options dialog) security tab. #*ic( t"e Macro Security button to open t"e Macro Security dia*o$& #"oose a *ee* t"at fits your comfort *ee*& Medium security uses t"e confirmation dia*o$ in 0i$ure 13, %"ic" is re*atie*y 8uic( and unobtrusie& 24 Figure 15. Macro *ecurity dialog) *ecurity Level tab. 6ou can set trusted *ocations and certificates t"at a**o% documents to *oad %it"out confirmation based on eit"er %"ere t"ey are stored, or t"e certificate used to si$n a document& Figure 16. Macro *ecurity dialog) rusted *ources tab. 25 2.(. )sing brea*points )f you set a brea(point in t"e code, t"e macro stops runnin$ at t"at point& 6ou can t"en inspect ariab*es, continue runnin$ t"e macro, or sin$*e9step t"e macro& )f a macro fai*s and you donGt (no% %"y, sin$*e9 steppin$ ,runnin$ one statement at a time. a**o%s you to %atc" a macro in action& ;"en t"e macro fai*s, youG** (no% "o% it $ot t"ere& )f a *ar$e number of statements run before t"e prob*em occurs, it may not be feasib*e to run one statement at a time, so you can set a brea(point at or near t"e *ine t"at causes t"e prob*em& T"e pro$ram stops runnin$ at t"at point, and you can sin$*e9step t"e macro and %atc" t"e be"aior& T"e brea(point 1n-1ff icon sets a brea(point at t"e statement containin$ t"e cursor& A red stop si$n mar(s t"e *ine in t"e brea(point co*umn& Doub*e9c*ic( in t"e brea(point co*umn to to$$*e a brea(point at t"at statement& Ri$"t9c*ic( a brea(point in t"e +rea(9point co*umn to actiate or deactiate it& 5se t"e Mana$e +rea(points icon to *oad t"e Mana$e +rea(points dia*o$& A** of t"e actie brea(points in t"e current modu*e are *isted by *ine number& To add a brea(point, enter a *ine number in t"e entry fie*d and c*ic( 4e%& To de*ete a brea(point, se*ect a brea(point in t"e *ist and c*ic( t"e De*ete button& #*ear t"e Actie c"ec( bo3 to disab*e t"e "i$"*i$"ted brea(point %it"out de*etin$ it& T"e 'ass #ount input bo3 indicates t"e number of times a brea(point must be reac"ed before it is considered actie& )f t"e pass count is four ,!., t"en t"e fourt" time t"at t"e statement containin$ t"e brea(point is to be run, it %i** stop rat"er t"an run& T"is is e3treme*y usefu* %"en a portion of t"e macro does not fai* unti* it "as been ca**ed mu*tip*e times& Figure 17. Manage !reakpoints dialog. T"ere are t%o t"in$s t"at cause a brea(point to be i$nored: a pass count t"at is not Cero, and e3p*icit*y mar(in$ t"e brea(point as Dnot actieF in t"e Mana$e brea(points dia*o$& 2ery brea(point "as a pass count t"at is decremented to%ard Cero %"en it is reac"ed& )f t"e resu*t of decrementin$ is Cero, t"e brea(point becomes actie and stays actie because t"e pass count stays at Cero t"ereafter& T"e pass count is not restored to its ori$ina* a*ue %"en t"e macro is finis"ed or restarted& 2.1+. ,ow libraries are stored Macro *ibraries are stored as IML fi*es t"at are easi*y editab*e usin$ any te3t editor& )n ot"er %ords, it is easy for you to po(e around and dama$e your fi*es& T"is is adanced materia* t"at you may %ant to i$nore& )f you do not understand IML and %"y t"e fi*e contains Q$t7 rat"er t"an R, per"aps you s"ou*d not edit t"e fi*es& A*t"ou$" manua**y editin$ your e3terna* *ibraries is $enera**y considered foo*is", ) "ae "ad at *east one instance %"ere t"is %as re8uired, because 11o %as unab*e to *oad a modu*e t"at contained a synta3 error& 26 2ac" *ibrary is stored in a sin$*e directory, and eac" modu*e and dia*o$ is contained in a sin$*e fi*e& T"e $*oba* *ibraries t"at are inc*uded %it" 1pen1ffice&or$ are stored in a s"ared basic directory under t"e directory in %"ic" 11o is insta**ed& 23amp*es: C:\Prora! "ile#\OpenO$$ice%&'\#(are\ba#ic )A Windo*# in#tallation +opt+openo$$ice&or+ba#i#%&'+#(are+ba#ic )A ,inux in#tallation 1pen1ffice&or$ stores user9specific data in a directory under t"e userGs "ome directory& T"e *ocation is operatin$ system specific& 5se Tools > Options > OpenOffice.org > Paths to ie% %"ere ot"er confi$uration data is stored& Eere are some e3amp*es %"ere my basic macros are stored: C:\-ocu!ent# and Settin#\and.\Application -ata\OpenO$$ice&or\%\u#er\ba#ic )Windo*# /P C:\0#er#\piton.a1a\App-ata\Roa!in\OpenO$$ice&or\%\u#er\ba#ic )Windo*# 2 +(o!e+and.+OpenO$$ice&or+%+u#er+ba#ic ),inux 5ser macros are stored in 1pen1ffice&or$S3SuserSbasic& 2ac" *ibrary is stored in its o%n directory off t"e basic directory& T"e user directory contains t%o fi*es and one directory for eac" *ibrary ,see Tab*e 3.& Table 3. +iles and some directories in my user,basic directory. Entry Description dia*o$&3*c IML fi*e t"at references eery dia*o$ fi*e (no%n to t"is user in 1pen1ffice&or$& script&3*c IML fi*e t"at references eery *ibrary fi*e (no%n to t"is user in 1pen1ffice&or$& Standard Directory containin$ t"e Standard *ibrary& 'itonya( Directory containin$ a t"e *ibrary named 'itonya(& 'itonya(Dia*o$s Directory containin$ t"e *ibrary named 'itonya(Dia*o$s& T"e fi*es dia*o$&3*c and script&3*c contain a reference to a** of t"e dia*o$s and *ibraries (no%n to 11o& )f t"ese t%o fi*es are oer%ritten, 11o %i** not (no% about your persona* *ibraries een if t"ey e3ist& 6ou can, "o%eer, eit"er manua**y edit t"e fi*es, or, een easier, use t"e 11o Macro 1r$aniCer dia*o$ to import t"e *ibraries ,because you can import a *ibrary based on t"e directory.& T"e directory containin$ a *ibrary contains a sin$*e fi*e for eac" modu*e and dia*o$ in t"e *ibrary& T"e directory a*so contains t"e fi*es dia*o$&3*b and script&3*b, %"ic" references t"e modu*es& 2.11. ,ow documents are stored T"e standard 11o formats use a standard P)' fi*e to store a** of t"e components& Any pro$ram t"at can ie% and e3tract P)' fi*es can be used to inspect an 11o document L "o%eer, some pro$rams %i** re8uire you to c"an$e t"e fi*e e3tension to end %it" P)'& After unCippin$ an 11o document, you %i** find fi*es t"at contain t"e primary content, sty*es, and settin$s& T"e e3tracted document a*so contains t"ree directories& T"e M2TA9)40 directory references a** of t"e ot"er fi*es, embedded pictures, code *ibraries, and dia*o$s& T"e Dia*o$s directory contains a** of t"e embedded dia*o$s, and t"e +asic directory contains a** of t"e embedded *ibraries& T"e point to a** t"is is t"at in an emer$ency, you can manua**y inspect a documentGs IML and potentia**y fi3 prob*ems& 27 2.12. Conclusion Macros and dia*o$s are stored in modu*es, modu*es are stored in *ibraries, and *ibraries are stored in *ibrary containers& T"e app*ication is a *ibrary container, as is eery document& T"e )D2 is used to create and debu$ macros and dia*o$s& 6ou "ae /ust comp*eted one of t"e most difficu*t steps in %ritin$ macros for 1pen1ffice&or$: %ritin$ your first macroT 6ou are no% ready to e3p*ore, try ot"er macro e3amp*es, and create a fe% of your o%n& 28 #. !anguage Constructs T"e 1pen1ffice&or$ macro *an$ua$e is simi*ar to t"e one in Microsoft 1ffice because t"ey are bot" based on +AS)#& +ot" macro *an$ua$es access t"e under*yin$ imp*ementation structures, %"ic" differ si$nificant*y and are t"erefore incompatib*e& T"is c"apter emp"asiCes t"e portions of t"e *an$ua$e t"at do not access t"e under*yin$ imp*ementation& T"is c"apter s"o%s "o% to assemb*e different components to produce an 11o macro t"at %i** compi*e and run& )n a %ord: synta3& #orrect synta3 does not imp*y t"at t"e macro does %"at you %ant, on*y t"at t"e pieces are put to$et"er in a correct %ay& T"e p"rases D#an ) drie>F and DMay ) drie>F are bot" syntactica**y correct& T"e first p"rase is about abi*ity, and t"e second p"rase is about permission& )n speec", t"ese t%o 8uestions may be understood to "ae t"e same meanin$& T"e computer, on t"e ot"er "and, does e3act*y %"at you as(, rat"er t"an %"at you mean& T"e primary components t"at syntactica**y constitute an 1pen1ffice&or$ macro are statements, ariab*es, subroutines, and functions, and f*o%9contro* constructs& A statement is a sma**, runnab*e portion of code t"at is usua**y %ritten as a sin$*e *ine of te3t& Oariab*es are containers t"at "o*d a*ues t"at can c"an$e durin$ macro e3ecution& Subroutines and functions separate a macro into functiona* named $roups of statements, a**o%in$ for better or$aniCation& 0*o% contro* directs %"ic" statements run and "o% many times& 11o runs one *ine of a macro at a time& 2ac" *ine of a macro is de*imited e3act*y t"e %ay it sounds7 by a ne% *ine ,see Listin$ 2.& Listing 2. wo line macro Print "3(i# i# line one" Print "3(i# i# line t*o" Lines t"at are too *on$ may use more t"an one *ine by appendin$ an underscore ,=. to t"e end of t"e *ine ,see Listin$ 3.& T"e underscore must be t"e *ast c"aracter on t"e *ine for it to act as a *ine9continuation c"aracter& T"e underscore "as no specia* meanin$ %"en it isnGt t"e *ast c"aracter of a *ine, a**o%in$ it to be used inside strin$s and in ariab*e names& ;"en used as a continuation c"aracter, spaces may precede t"e underscore and are in some cases re8uired to separate t"e underscore from %"at precedes it& 0or e3amp*e, sp*ittin$ t"e *ine DaNbNcF after t"e b re8uires a space bet%een t"e b and t"e underscore, or t"e underscore is considered part of t"e ariab*e name& Spaces t"at inadertent*y fo**o% a continuation c"aracter may cause a compi*e9 time error& 5nfortunate*y, t"e error does not state t"at somet"in$ fo**o%s t"e underscore, but t"at t"e ne3t *ine is ina*id& Listing 3. -ppend an underscore to the end of a line to continue on the ne.t line. Print "Strin# are concatenated toet(er " 4 5 "*it( t(e a!per#and c(aracter" TIP ;"en anyt"in$ fo**o%s a *ine9continuation c"aracter, t"e ne3t *ine is not ta(en as its continuation& Sometimes, %"en ) copy code *istin$s from %eb sites and paste t"em into t"e )D2, an e3tra space is added at t"e end of a *ine, %"ic" brea(s *ine continuation& 6ou can p*ace mu*tip*e statements on a sin$*e *ine by separatin$ t"em %it" co*ons& T"is is usua**y done for improed code readabi*ity& 2ac" of t"e combined statements act as a sin$*e *ine of code %"i*e debu$$in$ t"e macro in t"e )nte$rated Dee*opment 2nironment ,)D2.& Listin$ !, t"erefore, acts *i(e t"ree separate statements %"i*e usin$ t"e )D2 to sin$*e9step t"rou$" t"e macro& Listing 4. *et the variables .) y) and z to zero. x 6 7 : . 6 7 : 8 6 7 29 6ou s"ou*d *ibera**y add remar(s, %"ic" are a*so ca**ed comments, to a** of t"e macros t"at you %rite& ;"i*e %ritin$ a macro, remember t"at %"at is c*ear today may not be c*ear tomorro%, as time passes and ne% pro/ects arise and memory fades a** too 8uic(*y& 6ou can start a comment %it" eit"er t"e sin$*e 8uotation c"aracter, or t"e (ey%ord R2M& A** te3t on t"e same *ine fo**o%in$ a comment indicator is i$nored& #omments are not considered runnab*e statements7 t"ey are i$nored %"i*e sin$*e9steppin$ a macro& Listing 5. -dd comments to all of the macros that you write. REM Co!!ent# !a. #tart *it( t(e 1e.*ord REM& ReM It i# not ca#e9#en#iti:e #o t(i# i# al#o a co!!ent& ) All text $ollo*in t(e #tart o$ t(e co!!ent i# inored / 6 7 ) A co!!ent !a. al#o #tart *it( a ) #inle ;uote 8 6 7 REM All text $ollo*in t(e #tart o$ t(e co!!ent i# inored TIP <ey%ords, ariab*es, and routine names in 11o +asic are not case9sensitie& T"erefore, R2M, Rem, and r2m a** start a comment& 4ot"in$ can fo**o% a *ine9continuation c"aracter, and t"is inc*udes comments& A** te3t fo**o%in$ a comment indicator is i$nored L een t"e continuation c"aracter& T"e *o$ica* resu*t from t"ese t%o ru*es is t"at a *ine9 continuation c"aracter can neer occur on t"e same *ine as a comment& 3.1. Compatibilit' with -isual Basic ;it" respect to synta3 and +AS)# functiona*ity, 11o +asic is ery simi*ar to Oisua* +asic& T"e t%o +asic dia*ects are not"in$ a*i(e %"en it comes to manipu*atin$ documents, but t"e $enera* command set is ery simi*ar& Steps %ere ta(en to improe t"e $enera* compatibi*ity bet%een t"e t%o dia*ects& Many en"ancements %ere re*eased %it" 11o 2&0& Many of t"e c"an$es are not bac(%ard compatib*e %it" e3istin$ be"aior& To "e*p reso*e t"ese conf*icts, a ne% compi*er option and a ne% run9time mode %ere introduced to specify t"e ne% compatib*e be"aior& T"e compi*er option D1ption #ompatib*eF directs some features& T"is option affects on*y t"e modu*e in %"ic" it is contained& +ecause a macro ca**s different modu*es durin$ its e3ecution, bot" t"e o*d and ne% be"aior may be used, dependin$ upon t"e e3istence of D1ption #ompatib*eF in eac" ca**ed modu*e& Settin$ t"e option in one modu*e and t"en ca**in$ anot"er modu*e "as no effect in t"e ca**ed modu*e& A run9time function, #ompatibi*ityMode, True-0a*se ., a**o%s t"e be"aior of run9time functions to be modified durin$ t"e e3ecution of a macro& T"is proides t"e f*e3ibi*ity to enab*e t"e ne% run9time be"aior, perform some operations, and t"en disab*e t"e ne% run9time be"aior& #ompatibi*ityMode,0a*se. oerrides 1ption #ompatib*e for t"e ne% runtime be"aior& Eopefu**y, some met"od of probin$ t"e current mode %i** be proided& Oisua* basic a**o%s any Latin91 ,)S1 @@AB91. c"aracter as a a*id ariab*e name, 11o does not& Settin$ D1ption #ompatib*eF a**o%s DUF to be considered a a*id ariab*e name& T"is is /ust one of many c"an$es t"at use D1ption #ompatib*e&F T"e #ompatibi*ityMode,. function neit"er enab*es nor disab*es t"e ne% e3tended identifier names because #ompatibi*ityMode,. is not ca**ed unti* run time and ariab*e names are reco$niCed at compi*e time& +ot" Oisua* +asic and 11o +asic support t"e rmdir,. command to remoe a directory& O+A can remoe on*y empty directories, but 11o +asic can recursie*y remoe an entire directory tree& )f #ompatibi*ityMode,True. is ca**ed prior to ca**in$ rmdir,., 11o +asic %i** act *i(e O+A and $enerate an error if t"e specified directory is not empty& T"is is /ust one of many c"an$es t"at use #ompatibi*ityMode,.& 30 Star+asic is muc" more for$iin$ t"an O+A& )t is easier, t"erefore, to conert simp*e macros from O+A to 11o +asic& A fe% e3amp*es, in 11o +asic, DsetF is optiona* durin$ assi$nment& T"erefore, D#et x 6 <F %or(s in bot" O+A and 11o +asic, but Dx 6 <F fai*s in O+A and %or(s %it" 11o +asic& Anot"er e3amp*e is t"at array met"ods are far more stab*e and for$iin$ in 11o t"an in O+A7 for e3amp*e, t"e functions to determine array bounds ,L+ound and 5+ound. %or( fine %it" empty arrays, %"ereas O+A cras"es& 3.2. Compiler options and directives A compi*er conerts a macro into somet"in$ t"at t"e computer is ab*e to run& #ompi*er be"aior can be contro**ed t"rou$" commands suc" as D1ption 23p*icitF at t"e top of a modu*e before a** ariab*es, subroutines, and functions& A compi*er option contro*s t"e compi*ers be"aior for t"e modu*e containin$ t"e option& Table 4. /ompiler options and directives. Option Description Def Jie a defau*t type to undec*ared ariab*es based on t"e ariab*es name& 1ption +ase #ontro* %"et"er t"e first array inde3 is 0 or 17 assumin$ it is not specified& 1ption #ompatib*e #ause Star +asic to act more *i(e O+& 1ption 23p*icit 0orce a** ariab*es to be defined& ;"i*e t"e macro runs, if a ariab*e t"at "as not yet been defined is used, an error occurs& 3.3. -ariables Oariab*es are containers t"at "o*d a*ues& 1pen1ffice&or$ supports different types of ariab*es desi$ned to "o*d different types of a*ues& T"is section s"o%s "o% to create, name, and use ariab*es& A*t"ou$" 11o +asic does not force you to dec*are ariab*es, you s"ou*d dec*are eery ariab*e t"at you use& T"e reasons for t"is are dee*oped t"rou$"out t"is section& #.#.1. Constant& subroutine& function& label& and 'ariable names A*%ays c"oose meanin$fu* names for your ariab*es& A*t"ou$" t"e ariab*e name Dar1F re8uires *itt*e t"ou$"t durin$ creation, D0irst4ameF is more meanin$fu*& Some ariab*e names are not particu*ar*y descriptie but are common*y used by pro$rammers any%ay& 0or e3amp*e, DiF is common*y used as a s"ortened ersion of Dinde3,F for a ariab*e t"at is used to count t"e number of times a repetitie tas( is e3ecuted in a *oop& 11o +asic imposes restrictions on ariab*e names, inc*udin$ t"e fo**o%in$: 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: A-Z or a-z. If Option Co!patible is used, then all characters defined as letters in the Latin-1 (ISO 8859-1) character set are accepted as part of an identifier name. The numbers 0-9 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. 31 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. TIP T"ese restrictions a*so app*y to constant, subroutine, function, and *abe* names& #.#.2. (eclaring 'ariables Some pro$rammin$ *an$ua$es re8uire t"at you e3p*icit*y *ist a** ariab*es used& T"is process is ca**ed Ddec*arin$ ariab*es&F 11o +asic does not re8uire t"is& 6ou are free to use ariab*es %it"out dec*arin$ t"em& A*t"ou$" it is conenient to use ariab*es %it"out dec*arin$ t"em, it is error9prone& )f you mistype a ariab*e name, it becomes a ne% ariab*e rat"er t"an raisin$ an error& '*ace t"e (ey%ords D1ption 23p*icitF before any runnab*e code in eery modu*e to cause 11o +asic to treat undec*ared ariab*es as run9time errors& #omments may precede 1ption 23p*icit because t"ey are not runnab*e& A*t"ou$" it %ou*d be een better if t"is became a compi*e9time error, 11o +asic does not reso*e a** ariab*es and routines unti* run time& Listing 6. Use Option $.plicit before the first runnable line in a module. REM ***** BASIC ***** Option Explicit TIP 5se D1ption 23p*icitF at t"e top of eery modu*e t"at you %rite7 it %i** sae you a *ot of time searc"in$ for errors in your code& ;"en ) am as(ed to debu$ a macro, t"e first t"in$ ) do is add D1ption 23p*icitF at t"e top of eac" modu*e& T"e scope for options is t"e modu*e %"ic" contains t"e option& )n ot"er %ords, settin$ option e3p*icit in one modu*e, t"en ca**in$ anot"er modu*e, %i** not cause undec*ared ariab*es in t"e ca**ed modu*e to cause a runtime error7 un*ess t"e ca**ed modu*e a*so "as Doption e3p*icitF& 6ou can dec*are a ariab*e %it" or %it"out a type& A ariab*e %it"out an e3p*icit type becomes a Oariant, %"ic" is ab*e to ta(e on any type& T"is means t"at you can use a Oariant to "o*d a numeric a*ue and t"en, in t"e ne3t *ine of code, oer%rite t"e number %it" te3t& Tab*e A s"o%s t"e ariab*e types supported by 11o +asic, t"e a*ue t"at eac" type of ariab*e contains immediate*y after dec*aration ,Dinitia* a*ueF., and t"e number of bytes t"at eac" type uses& )n 11o +asic, a ariab*eVs type can be dec*ared by appendin$ a specia* c"aracter to t"e end of t"e name %"en it is dec*ared& T"e 'ost co*umn in Tab*e A contains t"e supported c"aracters t"at can be post9fi3ed to a ariab*eVs name %"en t"e ariab*e is dec*ared& Table 5. *upported variable types and their initial values. Type Post Initial Bytes Convert Description +oo*ean 0a*se 1 #+oo* True or 0a*se #urrency : 0&0000 @ ##ur #urrency %it" ! decima* p*aces Date 00:00:00 @ #Date Dates and times Doub*e W 0&0 @ #Db* Decima* numbers in t"e ran$e of N-91&MBM6B313!@6232 3 10230@ )nte$er X 0 2 #)nt )nte$er from 932,M6@ t"rou$" 32,M6M Lon$ Q 0 ! #Ln$ )nte$er from 921!M!@36!@ t"rou$" 21!M!@36!M 32 Type Post Initial Bytes Convert Description 1b/ect 4u** aries 1b/ect Sin$*e T 0&0 ! #Sn$ Decima* numbers in t"e ran$e of N-93&!02@23 3 1023@ Strin$ Y ZZ aries #Str Te3t %it" up to 6AA36 c"aracters Oariant 2mpty aries #Oar May contain any data type A*t"ou$" 11o +asic supports a +yte ariab*e type, you canGt direct*y dec*are and use one& T"e function #+yte, as discussed *ater, returns a +yte a*ue t"at may be assi$ned to a ariab*e of type Oariant& ;it" 11o ersion 2&0, you can dec*are a ariab*e of type +yte, but t"e ariab*e is assumed to be an e3terna**y defined ob/ect of type +yte rat"er t"an an interna**y defined +yte ariab*e& 5se t"e D)M (ey%ord to e3p*icit*y dec*are a ariab*e before use ,see Tab*e 6.& 6ou can dec*are mu*tip*e ariab*es on a sin$*e *ine, and you can $ie eac" ariab*e a type %"en it is dec*ared& Oariab*es %it" no dec*ared type defau*t to type Oariant& Table 6. #eclaring simple variables. Declaration Description Dim 4ame 4ame is type Oariant because no type is stated& Dim 4ame As Strin$ 4ame is type Strin$ because t"e type is e3p*icit*y stated& Dim 4ameY 4ameY is type Strin$ because 4ameY ends %it" a Y& Dim 4ame As Strin$, ;ei$"t As Sin$*e 4ame is type Strin$ and ;ei$"t is type Sin$*e& Dim ;idt", Len$t" ;idt" and Len$t" are type Oariant& Dim ;ei$"t, Eei$"t As Sin$*e ;ei$"t is type Oariant and Eei$"t is type Sin$*e& TIP ;"en mu*tip*e ariab*es are dec*ared in a sin$*e *ine, t"e type for eac" ariab*e must be *isted separate*y& )n t"e *ast *ine of Tab*e A, ;ei$"t is a Oariant, een t"ou$" it *oo(s *i(e it may be of type Sin$*e& Muc" of t"e aai*ab*e *iterature on 11o macro pro$rammin$ uses a ariab*e namin$ sc"eme based on Eun$arian notation& ;it" Eun$arian notation, you can determine a ariab*eGs type from its name& )n practice, eeryone does t"is different*y and %it" differin$ *ee*s of ad"erence& T"is is a sty*istic decision t"at some peop*e *oe and some peop*e "ate& 11o +asic uses Def[typeR statements to faci*itate t"e use of Eun$arian notion& T"e Def statements, %"ic" are *oca* to eac" modu*e t"at uses t"em, proide a defau*t type for an undec*ared ariab*e based on its name& 4orma**y, a** undec*ared ariab*es are of type Oariant& T"e Def statement is fo**o%ed by a comma9separated *ist of c"aracter ran$es t"at specify t"e startin$ c"aracters ,see Listin$ M.& Listing 7. #eclare untyped variables starting with i) %) k) or n to be of type "nteger. -e$Int i91=n Tab*e M contains an e3amp*e of eac" supported Def statement& Def statements, *i(e 1ption statements, are p*aced in t"e modu*e before any runnab*e *ine or ariab*e dec*aration& T"e Def statement does not force a ariab*e %it" a specific first *etter to be of a certain type, but rat"er proides a defau*t type ot"er t"an Oariant 33 for ariab*es t"at are used but not dec*ared& ) "ae neer seen t"e Def statement used and ) recommend t"at you do not use t"e Def statement& TIP )f you use D1ption 23p*icit,F and you s"ou*d, you must dec*are a** ariab*es& T"is renders t"e Def[typeR statements use*ess because t"ey affect on*y undec*ared ariab*es& Table 7. $.amples of supported #ef statements in OpenOffice.org. Def Statement Type Def+oo* b +oo*ean DefDate t Date DebDb* d Doub*e Def)nt i )nte$er DefLn$ * Lon$ Def1b/ o 1b/ect DefOar Oariant #.#.#. )ssigning 'alues to 'ariables T"e purpose of a ariab*e is to "o*d a*ues& To assi$n a a*ue to a ariab*e, type t"e name of t"e ariab*e, optiona* spaces, an e8ua*s si$n, optiona* spaces, and t"e a*ue to assi$n to t"e ariab*e, *i(e so: / 6 %&>?><@'A<? . 6 A T"e optiona* (ey%ord Let may precede t"e ariab*e name but seres no purpose ot"er t"an readabi*ity& A simi*ar optiona* (ey%ord, Set, meant for 1b/ect ariab*es, seres no purpose ot"er t"an readabi*ity& T"ese (ey%ords are rare*y used& #.#.$. *oolean 'ariables are True or +alse +oo*ean ariab*es "ae t%o a*id a*ues: True or 0a*se& T"ey are interna**y represented by t"e )nte$er a*ues 91 and 0, respectie*y& Any numeric a*ue assi$ned to a +oo*ean t"at does not precise*y ea*uate to 0 is conerted to True& T"e macro in Listin$ @ introduces a fe% ne% concepts& A strin$ ariab*e, s, accumu*ates t"e resu*ts of t"e ca*cu*ations, %"ic" are disp*ayed in a dia*o$ ,see 0i$ure 1@.& Addin$ #ERY,10. to t"e strin$ causes a ne% *ine to be printed in t"e dia*o$& 5nfortunate*y, accumu*atin$ t"e resu*ts in a strin$ proides a more comp*icated macro t"an usin$ simp*e statements suc" as DPrint CBoolB<6%CF, but t"e resu*ts are easier to understand ,see 0i$ure 1@.& )n t"e 11o ersion of t"e document, a button is fre8uent*y aai*ab*e t"at a**o%s you to run t"e macro immediate*y& Listing 8. #emonstrate conversion to type boolean. Sub Exa!pleBoolean3.pe -i! b a# Boolean -i! # a# Strin b 6 3rue b 6 "al#e b 6 B< 6 %C REM Set to "al#e # 6 "B< 6 %C 6D " 4 b 34 b 6 B< E 2C REM Set to 3rue # 6 # 4 CHRFB>7C 4 "B< E 2C 6D " 4 b b 6 2 REM Set to 3rue becau#e 2 i# not 7 # 6 # 4 CHRFB>7C 4 "B2C 6D " 4 b M#Box # End Sub Figure 18. he dialog displayed by Listing 0. T"e interna* binary representation of True as 91 "as a** of t"e bits set to 1& T"e interna* binary representation of 0a*se as 0 "as a** of t"e bits set to 0& #.#.,. -umeric 'ariables 4umeric ariab*es contain numbers& 11o +asic supports inte$ers, f*oatin$9point, and currency numbers& )nte$ers may be e3pressed as "e3adecima* ,base 16., octa* ,base @., or t"e defau*t decima* numbers ,base 10.& )n common practice, 11o users a*most a*%ays use decima* numbers, but t"e ot"er types are presented "ere as %e**, for comp*eteness& A discussion of ot"er number bases is important because interna**y, computers represent t"eir data in binary format& )t is easy to conert bet%een t"e binary, "e3adecima*, and octa* number bases7 and for "umans it may be easier to isua*iCe binary numbers %"en represented in ot"er number bases& Decima* numbers, base 10, are composed of t"e 10 di$its 0, 1, 2, 3, !, A, 6, M, @, and B& Add 1 to B in decima* and t"e resu*t is 10& +inary ,base 2., octa* ,base @., and "e3adecima* ,base 16. numbers are a*so common*y used in computin$& 1cta* numbers are composed of t"e numbers 0, 1, 2, 3, !, A, 6, and M& )n octa*, add 1 to M and t"e resu*t is 10 ,base @.& Ee3adecima* numbers are composed of t"e 16 di$its 0, 1, 2, 3, !, A, 6, M, @, B, A, +, #, D, 2, and 0& +inary numbers are composed of t"e t%o di$its 0 and 1& Tab*e @ contains t"e numbers from 0 t"rou$" 1@ in decima*, and t"eir correspondin$ a*ues in binary, octa*, and "e3adecima* bases& Table 8. Numbers in different bases. Decimal Binary Octal Hexadecimal 0 0 0 0 1 1 1 1 2 10 2 2 3 11 3 3 ! 100 ! ! A 101 A A 6 110 6 6 M 111 M M 35 Decimal Binary Octal Hexadecimal @ 1000 10 @ B 1001 11 B 10 1010 12 A 11 1011 13 + 12 1100 1! # 13 1101 1A D 1! 1110 16 2 1A 1111 1M 0 16 10000 20 10 1M 10001 21 11 1@ 10010 22 12 )nte$ers are assumed to be e3pressed as decima* numbers& #ommas are not a**o%ed& Ee3adecima* numbers are preceded by DQEF and octa* numbers are preceded by DQ1F ,*etter 1, not a Cero.& 5nfortunate*y, t"ere is no easy met"od to enter binary numbers& Tab*e B presents a fe% simp*e $uide*ines for enterin$ numbers& Table 9. - few guidelines for entering numbers in OOo !asic. Example Description 5se 1000 not 1,000 ;rite numbers %it"out a t"ousands separator7 do not use commas& N 1000 A space is permitted bet%een a *eadin$ p*us or minus si$n and t"e number& QE02 is t"e same as 2A! 'recede a "e3adecima* number %it" QE& Q111 is t"e same as B 'recede an octa* number %it" Q1& 5se 3&1!1A not 3,1!1A Do not use commas for t"e decima*& 6&022223 )n scientific notation, t"e DeF can be uppercase or *o%ercase& 5se 6&6e93! not 6&6e 93! Spaces are not a**o%ed in a number& ;it" t"e space, t"is ea*uates as 6&6 9 3! ? 92M&!& 6&022eN23 T"e e3ponent may contain a *eadin$ p*us or minus si$n& 1&1e2&2 ea*uates as 1&1e2 T"e e3ponent must be an inte$er& T"e fractiona* portion is i$nored& )n $enera*, assi$nin$ a Strin$ to a numeric ariab*e sets t"e ariab*e to Cero and does not $enerate an error& )f t"e first c"aracters in t"e strin$ represent a number, "o%eer, t"en t"e strin$ is conerted to a number and t"e non9numeric portion of t"e strin$ is i$nored L numeric oerf*o% is possib*e& !nteger variables An inte$er is a %"o*e number t"at may be positie, ne$atie, or e8ua* to Cero& )nte$er ariab*es are a $ood c"oice for numbers representin$ non9fractiona* 8uantities, suc" as a$e or number of c"i*dren& )n 11o +asic, )nte$er ariab*es are 169bit numbers supportin$ a ran$e from 932M6@ t"rou$" 32M6M& 0*oatin$9point numbers assi$ned to an inte$er are rounded to t"e nearest )nte$er a*ue& Appendin$ a ariab*e name %it" DXF %"en it is dec*ared is a s"ortcut to dec*arin$ it as type )nte$er& Listing 9. #emonstrate integer variables. Sub Exa!pleInteer3.pe 36 -i! i> A# Inteer= i'G REM i> and i' are bot( Inteer :ariable# -i! $' A# -ouble -i! #F $'6 %&< i>6 $' REM i> i# rounded to ? # 6 "%&<7 6D " 4 i> $'6 %&?@ i'6 $' REM i' i# rounded to % # 6 # 4 CHRFB>7C 4 "%&?@ 6D " 4 i' M#Box # End Sub Figure 19. #emonstrating integer variables in Listing 1. .ong !nteger variables DLon$F is an inte$er type t"at "as a $reater ran$e t"an type )nte$er& Lon$ ariab*es are 329bit numbers supportin$ a ran$e from 92,1!M,!@3,6!@ t"rou$" 2,1!M,!@3,6!M& Lon$ ariab*es use t%ice as muc" memory as )nte$er ariab*es but t"ey can "o*d numbers t"at are much *ar$er in ma$nitude& 0*oatin$9point numbers assi$ned to type Lon$ are rounded to t"e nearest Lon$ a*ue& Appendin$ a ariab*e name %it" DQF %"en it is dec*ared is a s"ortcut to dec*arin$ it as type Lon$& T"e output from Listin$ 10 is t"e same as Listin$ B ,see 0i$ure 1B.& Listing 10. #emonstrate long variables. Sub Exa!ple,on3.pe -i! Hu!berO$-o#4= Hu!berO$Cat# A# ,on ) Bot( :ariable# are ,on -i! $' A# -ouble -i! #F $'6 %&< Hu!berO$-o# 6 $' REM round to ? # 6 "%&<7 6D " 4 Hu!berO$-o# $'6 %&?@ Hu!berO$Cat# 6 $' REM round to % # 6 # 4 CHRFB>7C 4 "%&?@ 6D " 4 Hu!berO$Cat# M#Box # End Sub Currenc' variables #urrency ariab*es, as t"e name imp*ies, are desi$ned to "o*d financia* information& T"e #urrency type %as ori$ina**y introduced to aoid t"e roundin$ be"aior of t"e f*oatin$9point types Sin$*e and Doub*e& Oisua* +asic &42T remoed t"e #urrency type in faor of t"e Decima* type& #urrency ariab*es are 6!9bit, fi3ed9precision numbers& #a*cu*ations are performed to four decima* p*aces and 1A non9decima* di$its accuracy& T"is yie*ds a ran$e from 9B22,33M,203,6A@,!MM&A@0@ t"rou$" 37 NB22,33M,203,6A@,!MM&A@0M& Appendin$ a ariab*e name %it" D:F %"en it is dec*ared is a s"ortcut to dec*arin$ it as type #urrency& Listing 11. #emonstrate currency variables. Sub Exa!pleCurrenc.3.pe -i! Inco!eI= Co#tPer-o A# Currenc. Inco!eI 6 ''>%?&%2 Co#tPer-o 6 >77&7 + %&7 REM Print# a# ''>%?&%277 Print "Inco!e 6 " 4 Inco!eI REM Print# a# %%&%%%% Print "Co#t Per do 6 " 4 Co#tPer-o End Sub /ingle variables Sin$*e ariab*es, un*i(e )nte$er ariab*es, can "ae a fractiona* portion& T"ey are ca**ed Df*oatin$9point numbersF because, un*i(e #urrency ariab*es, t"e number of decima*s a**o%ed is not fi3ed& Sin$*e ariab*es are 329bit numbers t"at are accurate to about seen disp*ayed di$its, ma(in$ t"em suitab*e for mat"ematica* operations of aera$e precision& T"ey support positie or ne$atie a*ues from 3&!02@23 3 1023@ to 1&!012B@ 3 1029!A& Any number sma**er in ma$nitude t"an 1&!012B@ 3 1029!A becomes Cero& Appendin$ a ariab*e name %it" DTF %"en it is dec*ared is a s"ortcut to dec*arin$ it as type Sin$*e& Listing 12. #emonstrate single variables. Sub Exa!pleSinle3.pe -i! Jallon#0#ed A# Sinle= Mile# A# Sinle= !pK Jallon#0#ed 6 >2&% Mile# 6 <?'&@ !pK 6 Mile# + Jallon#0#ed Print ""uel e$$icienc. 6 " 4 !pK End Sub "ouble variables Doub*e ariab*es are simi*ar to Sin$*e ariab*es e3cept t"at t"ey use 6! bits and "ae about 1A si$nificant di$its& T"ey are suitab*e for "i$"9precision mat"ematica* operations& Doub*e ariab*es support positie or ne$atie a*ues from 1&MBM6B313!@6232 3 10230@ to !&B!06A6!A@!12!M 3 102932!& Any number sma**er in ma$nitude t"an !&B!06A6!A@!12!M 3 102932! becomes Cero& Appendin$ a ariab*e %it" DWF %"en it is dec*ared is a s"ortcut to dec*arin$ it as type Doub*e& Listing 13. #emonstrate double variables. Sub Exa!ple-ouble3.pe -i! Jallon#0#ed A# -ouble= Mile# A# -ouble= !pL Jallon#0#ed 6 >2&% Mile# 6 <?'&@ !pL 6 Mile# + Jallon#0#ed Print ""uel e$$icienc. 6 " 4 !pL End Sub 38 #.#... tring 'ariables contain text Strin$ ariab*es are used to "o*d te3t& )n 11o, te3t is stored as 5nicode ersion 2&0 a*ues, %"ic" proides $ood support for mu*tip*e *an$ua$es& 2ac" Strin$ ariab*e can "o*d up to 6A,A3A c"aracters& Appendin$ a ariab*e %it" DYF %"en it is dec*ared is a s"ortcut to dec*arin$ it as type Strin$& Listing 14. #emonstrate string variables. Sub Exa!pleStrin3.pe -i! "ir#tHa!e A# Strin= ,a#tHa!eF "ir#tHa!e 6 "Andre*" ,a#tHa!eF 6 "Piton.a1" Print "Hello " 4 "ir#tHa!e 4 " " 4 ,a#tHa!eF End Sub Figure 20. #emonstrating string variables in Listing (2. A*%ays remember t"at strin$s are *imited to 6A,A3A c"aracters& A macro counted t"e number of c"aracters in a te3t document by conertin$ t"e document to a strin$ and t"en ta(in$ t"e *en$t"& T"e macro %or(ed unti* t"e document contained more t"an 6A,A3A c"aracters& )n Oisua* +asic &42T, Strin$ ariab*es may contain appro3imate*y 2 bi**ion 5nicode c"aracters& '*ace t%o doub*e 8uote c"aracters in a ro% to insert a doub*e 8uotation c"aracter into a strin$& S 6 "S(e #aid ""Hello""" REM S(e #aid "Hello" Oisua* +asic strin$ constants are aai*ab*e %"en usin$ D1ption #ompatib*eF ,see Tab*e 10.& 6ou must use 1ption #ompatib*e for t"e modu*e rat"er t"an usin$ #ompatibi*ityMode,True. because t"e strin$ constant is reco$niCed at compi*e time rat"er t"an run time& Table 10. 3isual !asic4compatible string constants. Constant Vale Description b#r #ERY,13. #arria$e return b#rLf #ERY,13. Q #ERY,10. #arria$e return-*inefeed combination b0orm0eed #ERY,12. 0orm feed bLf #ERY,10. Line feed b4e%Line #ERY,13. Q #ERY,10. or #ERY,10. '*atform9specific ne%*ine c"aracter L %"ateer is appropriate b4u**#"ar #ERY,0. #"aracter %it" AS#)) a*ue 0 b4u**Strin$ ZZ 2mpty strin$& T"is is a strin$ %it" a terminatin$ nu**& bTab #ERY,B. EoriConta* tab bOertica*Tab #ERY,11. Oertica* tab 39 T"e strin$ constants in Tab*e 10 a**o% you to define constant strin$s %it" specia* c"aracters& 'reious*y, you "ad to define t"e strin$ by usin$ code t"at ca**ed t"e #ERY,. function& Option Co!patible Con#t #Jreetin A# Strin 6 "Hello" 4 :bCr 4 "Mo(nn." ) 3(i# contain# a CR& #.#./. (ate 'ariables Date ariab*es contain date and time a*ues& 11o +asic stores dates interna**y as a Doub*e& Dates, *i(e a** numerica* types, are initia*iCed to Cero, %"ic" corresponds to December 30, 1@BB at 00:00:00& Addin$ or subtractin$ 1 to-from a date corresponds to addin$ or subtractin$ a day& 1ne "our, one minute, and one second correspond to t"e numbers 1-2!, 1-,2! \ 60., and 1-,2! \ 60 \ 60., respectie*y& T"e date functions supported by 11o +asic are introduced in Tab*e 11 and fu**y discussed *ater& Listing 15. #emonstrate date variables. Sub Exa!ple-ate3.pe -i! tHo* A# -ate= t3oda. A# -ate -i! tBirt(-a. A# -ate tHo* 6 Ho*BC t3oda. 6 -ateBC tBirt(-a. 6 -ateSerialB>22A= 2= ?C Print "3oda. 6 " 4 t3oda. Print "Ho* 6 " 4 tHo* Print "A total o$ " 4 Bt3oda. 9 tBirt(-a.C 45 " da.# (a:e pa##ed #ince " 4 tBirt(-a. End Sub 4e$atie numbers are a*id and correspond to dates before December 30, 1@BB& Kanuary 1, 0001, corresponds to t"e f*oatin$9point number 96B3,ABA& #ontinuin$ bac(%ard produces dates t"at are +&#& ,+efore #"rist, sometimes a*so referred to as +&#&2&, meanin$ +efore t"e #"ristian 2ra, or +efore t"e #ommon 2ra. rat"er t"an A&D& ,Anno Domini.& A t"orou$" discussion of date "and*in$ is presented *ater& 40 Table 11. +unctions and subroutines related to dates and times. !nction Type Description #Date,e3pression. Date #onert a number or strin$ to a date& #Date0rom)so,strin$. Date #onert to a date from an )S1 @601 date representation& #DateTo)so,date. Strin$ #onert a date to an )S1 @601 date representation& Date,. Strin$ Return t"e current date as a Strin$& DateSeria*,yr, mnt", day. Date #reate a date from component pieces: 6ear, Mont", Day& DateOa*ue,date. Date 23tract t"e date from a date-time a*ue by truncatin$ t"e decima* portion& Day,date. )nte$er Return t"e day of t"e mont" as an )nte$er from a Date a*ue& JetSystemTic(s,. Lon$ Return t"e number of system tic(s as a Lon$& Eour,date. )nte$er Return t"e "our as an )nte$er from a Date a*ue& )sDate,a*ue. +oo*ean )s t"is a date> Minute,date. )nte$er Return t"e minute as an )nte$er from a Date a*ue& Mont",date. )nte$er Return t"e mont" as an )nte$er from a Date a*ue& 4o%,. Date Return t"e current date and time as a Date ob/ect& Second,date. )nte$er Return t"e seconds as an )nte$er from a Date a*ue& Time,. Strin$ Return t"e time as a Strin$& Timer,. Date Return t"e number of seconds since midni$"t as a Date& #onert to a Lon$& TimeSeria*,"our, min, sec. Date #reate a date from component pieces: Eours, Minutes, Seconds& ;ee(Day,date. )nte$er Return t"e inte$er 1 t"rou$" M, correspondin$ to Sunday t"rou$" Saturday& 6ear,date. )nte$er Return t"e year as an )nte$er from a Date a*ue& #.#.0. Create "our o1n data t"pes )n most imp*ementations of t"e +AS)# pro$rammin$ *an$ua$e, you can create your o%n data types& 11o +asic a**o%s you to define and use your o%n data types& Listing 16. #emonstrate user defined types. 3.pe Per#on3.pe "ir#tHa!e A# Strin ,a#tHa!e A# Strin End 3.pe Sub Exa!pleCreateHe*3.pe -i! Per#on A# Per#on3.pe Per#on&"ir#tHa!e 6 "Andre*" Per#on&,a#tHa!e 6 "Piton.a1" PrintPer#onBPer#onC End Sub Sub PrintPer#onBxC Print "Per#on 6 " 4 x&"ir#tHa!e 4 " " 4 x&,a#tHa!e End Sub 41 TIP A*t"ou$" user9defined types cannot direct*y contain an array, you can mana$e t"em in a ariant type& )n 11o ersion 3&2, t"ere are t"ree %ays t"at you can instantiate an instance of a user defined type& )n t"e fo**o%in$ e3amp*e, t"e co*on ,:. is used to p*ace t%o statements on t"e same *ine& -i! x A# He* Per#on3.pe ) 3(e oriinal *a. to do it& -i! . A# Per#on3.pe ) He* i# no loner re;uired& -i! 8 : 8 6 CreateObNectB"Per#on3.pe"C ) Create t(e obNect *(en de#ired& ;"en you create your o%n type, you create a structure ,fre8uent*y ca**ed a struct.& 11o "as many predefined interna* structures& A common*y used structure is Dcom&sun&star&beans&'ropertyOa*ueF& T"e interna* 11o structures can be created in t"e same %ay as user defined types, and a*so usin$ #reate5noStruct ,see 10& 5niersa* 4et%or( 1b/ects on pa$e 22M.& -i! a A# He* co!&#un&#tar&bean#&Propert.Oalue -i! b A# He* co!&#un&#tar&bean#&Propert.Oalue -i! c : c 6 CreateObNectB"co!&#un&#tar&bean#&Propert.Oalue"C -i! d : d 6 Create0noStructB"co!&#un&#tar&bean#&Propert.Oalue"C A*t"ou$" t"e structureVs type is Dcom&sun&star&beans&'ropertyOa*ueF, it is common to abbreiate t"e type name as t"e *ast portion of t"e name L in t"is case, D'ropertyOa*ueF& Many of t"e ob/ects in 11o "ae simi*ar, *on$, cumbersome names, %"ic" are simi*ar*y abbreiated in t"is boo(& Most ariab*es copy by a*ue& T"is means t"at %"en ) assi$n one ariab*e to anot"er, t"e a*ue from one is p*aced into t"e ot"er& T"ey do not reference t"e same data7 t"ey contain t"eir o%n copy of t"e data& T"is is a*so true of user9defined types and interna* 11o structures& Oariab*es t"at can be defined in t"is %ay are copied by a*ue& 1t"er types used interna**y by 11o, ca**ed 5niersa* 4et%or( 1b/ects, are copied by reference& A*t"ou$" t"ese are discussed *ater, it is important to start t"in(in$ about %"at "appens %"en one ariab*e is assi$ned to anot"er& )f ) assi$n one ariab*e to anot"er and it is copied by reference, t"en bot" ariab*es refer to t"e same data& )f t%o ariab*es refer to t"e same data, and if ) c"an$e one ariab*e, t"en ) c"an$e bot"& #.#.2. (eclare 'ariables 1ith special t"pes 6ou can use t"e (ey%ords DAs 4e%F to define a ariab*e as a (no%n 541 struct& T"e %ord DstructF is an abbreiated form of t"e %ord DstructureF t"at is fre8uent*y used by computer pro$rammers& A struct "as one or more data members, eac" of %"ic" may "ae different types& Structs are used to $roup associated data to$et"er& 1ption #ompatib*e proides a ne% synta3 to define ariab*es of (no%n and un(no%n types& A simp*e e3amp*e is dec*arin$ a ariab*e of a specific type een if t"e type is not (no%n to 11o +asic& Option Co!patible )Supported in OOo '&7 Sub Main -i! oOar> A# ObNect -i! oOar' A# M.3.pe Set oOar> 6 He* M.3.pe )Supported in OOo '&7 Set oOar' 6 He* M.3.pe )Supported in OOo '&7 Set oOar' 6 He* Pour3.pe )Error= declared a# M.3.pe not Pour3.pe& A ne% 1L2 ob/ect factory %as introduced %it" 11o 2&0, %"ic" a**o%s ne% types to be created& T"e ne% functiona*ity a**o%s 11o +asic to manipu*ate Microsoft ;ord documents on Microsoft ;indo%s operatin$ systems if Microsoft 1ffice is a*so insta**ed on t"e computer& Sub Main 42 -i! W A# Word&Application Set W 6 He* Word&Application REM -i! W A# He* Word&Application )3(i# *or1# in OOo '&7 REM W 6 CreateObNectB"Word&Application"C )3(i# *or1# in OOo '&7 W&Oi#ible 6 3rue End Sub T"e use of #reate1b/ect,. does not re*y on D1ption #ompatib*eF because t"is functiona*ity is proided by t"e ne% 1L2 ob/ect factory re*eased %it" 11o 2&0& #.#.13. Ob4ect 'ariables An 1b/ect is a comp*e3 data type t"at can contain more t"an a sin$*e piece of data& T"e code in Listin$ 16 s"o%s an e3amp*e of a comp*e3 data type& )n 1pen1ffice&or$, 1b/ect ariab*es are intended to "o*d comp*e3 data types created and defined by 11o +asic& ;"en a ariab*e of type 1b/ect is first dec*ared, it contains t"e specia* a*ue 4u**, %"ic" indicates t"at no a*id a*ue is present& 5se t"e Oariant type, not 1b/ect, to refer to 1pen1ffice&or$ interna*s& T"is is discussed *ater& #.#.11. 5ariant 'ariables Oariant ariab*es are ab*e to "o*d any data type& T"ey ta(e on t"e type of %"ateer is assi$ned to t"em& ;"en a ariab*e of type Oariant is first dec*ared, it contains t"e specia* a*ue 2mpty, %"ic" indicates t"at no a*ue "as been assi$ned to t"e ariab*e& A Oariant may be assi$ned an inte$er in one statement and t"en assi$ned te3t in t"e ne3t& 4o typecastin$ occurs %"en assi$nin$ data to a Oariant7 it simp*y becomes t"e appropriate type& T"e c"ame*eon9*i(e be"aior of Oariant ariab*es a**o%s t"em to be used as any ot"er ariab*e type& Eo%eer, t"is f*e3ibi*ity comes %it" a cost: time& 1ne fina* prob*em is t"at it isnGt a*%ays obious %"at type a Oariant %i** become after ma(in$ some assi$nments& Listing 17. #emonstrate variant types. Sub Exa!ple3e#tOariant# -IM # A# Strin -IM : A# Oariant REM : #tart# E!pt. # 6 # 4 "> : 3.peHa!e 6 " 4 3.peHa!eB:C 4 " Oalue 6 " 4 : 4 CHRFB>7C : 6 "ab'>2" : REM : beco!e# a Strin # 6 # 4 "' : 3.peHa!e 6 " 4 3.peHa!eB:C 4 " Oalue 6 " 4 : 4 CHRFB>7C : 6 3rue : REM : beco!e# a Boolean # 6 # 4 "% : 3.peHa!e 6 " 4 3.peHa!eB:C 4 " Oalue 6 " 4 : 4 CHRFB>7C : 6 B<6<C : REM : beco!e# an Inteer rat(er t(an a Boolean # 6 # 4 "? : 3.peHa!e 6 " 4 3.peHa!eB:C 4 " Oalue 6 " 4 : 4 CHRFB>7C : 6 >'%&?<A : REM -ouble # 6 # 4 "< : 3.peHa!e 6 " 4 3.peHa!eB:C 4 " Oalue 6 " 4 : 4 CHRFB>7C : 6>'% : REM Inteer # 6 # 4 "A : 3.peHa!e 6 " 4 3.peHa!eB:C 4 " Oalue 6 " 4 : 4 CHRFB>7C : 6 >'>2<AQ@?' : REM 3(i# could be a ,on but it turn# into a -ouble # 6 # 4 "2 : 3.peHa!e 6 " 4 3.peHa!eB:C 4 " Oalue 6 " 4 : 4 CHRFB>7C M#Box #= 7= "3(e Oariant 3a1e# Man. 3.pe#" End Sub Oisua* +asic &42T does not support type Oariant& 5ndec*ared ariab*es are of type 1b/ect& 43 Figure 21. 3ariant takes the assigned type. ;"en data is assi$ned to a Oariant, t"e data is not conerted to an appropriate type, but rat"er t"e Oariant becomes t"e type of t"e data& )n *ine 6 of 0i$ure 21, t"e Oariant is an )nte$er& )n *ine M, t"e number is too *ar$e to be an )nte$er, but it is sma** enou$" to be a Lon$& 11o +asic c"ooses to conert %"o*e numbers *ar$er t"an an inte$er and a** f*oatin$9point numbers into a Doub*e, een if t"ey can be e3pressed as a Sin$*e or a Lon$& #.#.12. Constants A constant is a ariab*e %it" no type, and t"at cannot c"an$e a*ue& T"e ariab*e is defined to be a p*ace"o*der t"at is substituted by t"e e3pression t"at defines t"e constant& #onstants are defined %it" t"e (ey%ord #onst& T"e constant name can be any a*id ariab*e name& Con#t Con#tHa!e6Expre##ion #onstants improe macros in many %ays& #onsider a Jraity constant fre8uent*y used in p"ysics& '"ysics sc"o*ars %i** reco$niCe t"is as t"e acce*eration due to $raity in meters per second s8uared& Con#t Jra:it. 6 @&Q> Eere are some specific benefits of usin$ constants: #onstants improe t"e readabi*ity of a macro& T"e %ord Jraity is easier to reco$niCe t"an t"e a*ue B&@1& #onstants are easy to mana$e& )f ) re8uire $reater precision or if t"e $raitationa* pu** c"an$es, ) "ae to c"an$e t"e a*ue in on*y one *ocation& #onstants "e*p preent difficu*t9to9find errors by c"an$in$ run9time errors into compi*e9time errors& Typin$ DJreityF rat"er t"an DJraityF is a compi*e9time error, %"i*e mistypin$ DB&@1F as DB&1@F is not& ;"i*e a a*ue *i(e B&@1 may be obious to you, it may not be as obious to ot"ers readin$ your code *ater& )t becomes %"at pro$rammers ca** a Dma$ic number,F and e3perienced pro$rammers try to aoid ma$ic numbers at a** costs& T"eir une3p*ained meanin$s ma(e for difficu*ties in maintainin$ code *ater, %"en t"e ori$ina* pro$rammer is not aai*ab*e to e3p*ain L or "as for$otten t"e detai*s entire*y& TIP 1pen1ffice&or$ defines t"e constant 'i& T"is is a mat"ematica* constant %it" a a*ue of appro3imate*y 3&1!1AB26A3A@BMB323@A& 44 3.4. 0he 1ith statement T"e ;it" statement is used to simp*ify accessin$ comp*e3 data types& Listin$ 16 defines a data type t"at contains t%o different ariab*es: 0irst4ame and Last4ame& 6ou can access t"ese ariab*es by p*acin$ a period bet%een t"e ariab*e name and t"e data item& Sub Exa!pleCreateHe*3.pe -i! Per#on A# Per#on3.pe Per#on&"ir#tHa!e 6 "Andre*" Per#on&,a#tHa!e 6 "Piton.a1" &&& End Sub 1r&&& t"e ;it" statement proides a s"ortcut for accessin$ mu*tip*e data e*ements from t"e same ariab*e& Sub Exa!pleCreateHe*3.pe -i! Per#on A# Per#on3.pe Wit( Per#on &"ir#tHa!e 6 "Andre*" &,a#tHa!e 6 "Piton.a1" End Wit( &&& End Sub Simi*ar*y: -i! oProp A# He* co!&#un&#tar&bean#&Propert.Oalue oProp&Ha!e 6 "Per#on" )Set Ha!e Propert. oProp&Oalue 6 "Bo. Bill" )Set Oalue Propert. 5sin$ ;it": -i! oProp A# He* co!&#un&#tar&bean#&Propert.Oalue Wit( oProp &Ha!e 6 "Per#on" )Set Ha!e Propert. &Oalue 6 "Bo. Bill" )Set Oalue Propert. End Wit( 3.. 2rra's An array is a data structure in %"ic" simi*ar e*ements of data are arran$ed in an inde3ed structure L for e3amp*e, a co*umn of names or a tab*e of numbers& See Tab*e 12& An array a**o%s you to store many different a*ues in a sin$*e ariab*e, and uses parent"eses to define and access array e*ements& 11o +asic does not support t"e use of s8uare brac(ets as used by ot"er *an$ua$es suc" as # and Kaa& Array ariab*es are dec*ared usin$ t"e Dim statement& T"in( of a one9dimensiona* array as a co*umn of a*ues and a t%o9dimensiona* array as a tab*e of a*ues& Ei$"er dimensions are supported but difficu*t to isua*iCe& An array inde3 may be any )nte$er a*ue from 932,M6@ t"rou$" 32,M6M& 45 Table 12. #eclaring an array is easy5 Definition Elements Description -i! aB<C A# Inteer 6 0rom 0 t"rou$" A inc*usie& -i! bB< 3o >7C A# Strin 6 0rom A t"rou$" 10 inc*usie& -i! cB9< 3o <C A# Strin 11 0rom 9A t"rou$" A inc*usie& -i! dB<= > 3o AC A# Inteer 36 Si3 ro%s %it" si3 co*umns from 0 t"rou$" A and 1 t"rou$" 6& -i! eB< 3o >7= '7 3o '<C A# ,on 36 Si3 ro%s %it" si3 co*umns from A t"rou$" 10 and 20 t"rou$" 2A& TIP 6ou must dec*are array ariab*es before usin$ t"em, een if you donGt use D1ption 23p*icit&F )f t"e *o%er dimension of an array is not specified, t"e defau*t *o%er bound of an array is Cero& ,'ro$rammers ca** t"ese arrays DCero9based&F. T"us, an array %it" fie e*ements %i** "ae e*ements numbered a,0. t"rou$" a,!.& 5se t"e (ey%ords D1ption +ase 1F to c"an$e t"e defau*t *o%er bound of an array to start at 1 rat"er t"an 0& T"is must be done before any ot"er e3ecutab*e statement in t"e pro$ram& Option Ba#e R 7 S > T TIP Specify t"e *o%er bound of an array rat"er t"an re*yin$ on t"e defau*t be"aior& T"is is more portab*e and it %i** not c"an$e %"en t"e 1ption +ase statement is used& Dim a,3. a**o%s for four e*ements: a,0., a,1., a,2., and a,3.& 1ption +ase does not c"an$e t"e number of e*ements t"at an array can store7 it c"an$es on*y "o% t"ey are inde3ed& 5sin$ 1ption +ase 1, t"e same statement sti** a**o%s for four e*ements: a,1., a,2., a,3., and a,!.& ) consider t"is be"aior unintuitie and recommend a$ainst usin$ 1ption +ase& )f you %ant specific array bounds, t"e preferred option is to e3p*icit*y dec*are t"e array bounds& 0or e3amp*e, Dim a,1 To !.& 1ption +ase "as ris(s in terms of communicatin$ c*ear documentation and ensurin$ portabi*ity& Oisua* +asic "and*es 1ption +ase 1 different*y from 11o +asic7 O+ c"an$es t"e *o%er bound to 1 but does not c"an$e t"e upper bound& Oisua* +asic &42T no *on$er supports 1ption +ase& ;it" D1ption #ompatib*e,F D1ption +ase 1F does not increase t"e upper bound by 1& )n ot"er %ords, 11o +asic acts *i(e O+& Accessin$ and c"an$in$ t"e a*ues in an array is easy& )nitia*iCin$ an array t"is %ay is tedious& Listing 18. #emonstrate simple array. Sub Exa!pleSi!pleArra.> -i! aB'C A# Inteer= bB9' 3o >C A# ,on -i! !B> 3o '= % 3o ?C
REM -id .ou 1no* t(at !ultiple #tate!ent# can be placed REM on a #inle line i$ #eparated b. a colonU aB7C 6 7 : aB>C 6 > : aB'C 6 ' bB9'C 6 9' : bB9>C 6 9> : bB7C 6 7 : bB>C 6 > !B>= %C 6 % : !B>= ?C 6 ? !B'= %C 6 A : !B'= ?C 6 Q Print "!B'=%C 6 " 4 !B'=%C Print "bB9'C 6 " 4 bB9'C 46 End Sub To 8uic(*y fi** a Oariant array, use t"e Array function ,see Listin$ 1B., %"ic" returns a Oariant array %it" t"e inc*uded data& T"e functions L+ound and 5bound return t"e *o%er bound and upper bound of an array& Routines supported by 11o +asic are summariCed in Tab*e 13, and discussed t"orou$"*y *ater& Listing 19. Use -rray67 to 8uickly fill an array. Sub Exa!pleArra."unction -i! a= iG= #F a 6 Arra.B"Vero"= >= Pi= Ho*C Re! Strin= Inteer= -ouble= -ate "or i 6 ,BoundBaC 3o 0BoundBaC #F 6 #F 4 i 4 " : " 4 3.peHa!eBaBiCC 4 " : " 4 aBiC 4 CHRFB>7C Hext M#Box #F= 7= "Exa!ple o$ t(e Arra. "unction" End Sub Figure 22. #ifferent variable types in the same array. A ariab*e defined as an array but not dimensioned, suc" as Dim a,., is ca**ed an empty array& Test for an empty array by comparin$ t"e upper bound of t"e array to t"e *o%er bound& )f t"e upper bound is *ess t"an t"e *o%er bound, t"e array is empty and no dimensions "ae been set& An array t"at "as been dimensioned, suc" as Dim a,A., is not empty& T"e be"aior for L+ound and 5+ound "as c"an$ed oer time& Some re*eases of 11o produce an error for 5+ound,b. and some do not& A** ersions s"ou*d %or( correct*y %it" 5+ound,b,..& At t"e time of t"is %ritin$, t"e upper and *o%er array bounds for c ,in Listin$ 20. fai*s because c is an empty ob/ect& Listing 20. 9arentheses are not always re8uired but are always allowed. Sub Arra.-i!en#ionError On Error Joto ErrorHandler -i! aBC= bB> 3o 'C= c -i! i,ine A# Inteer -i! #F REM Oalid con#truct# i,ine 6 > : # 6 "a 6 B" 4 ,BoundBaBCC 4 "= " i,ine 6 ' : # 6 # 4 0BoundBaC 4 "C"d i,ine 6 % : # 6 # 4 CHRFB>7C 4 "b 6 B" 4 ,BoundBbBCC 4 "= " i,ine 6 ? : # 6 # 4 0BoundBbC 4 "C" i,ine 6 < : # 6 # 4 CHRFB>7C 4 "c 6 B" 4 ,BoundBcBCC 4 "= " i,ine 6 A : # 6 # 4 0BoundBcC 4 "C" M#Box #= 7= ",Bound and 0Bound" Exit Sub ErrorHandler: # 6 # 4 CHRFB>7C 4 "Error " 4 Err 4 ": " 4 ErrorF 4 " Bline : " 4 i,ine 4 "C" 47 Re#u!e Hext End Sub Table 13. *ummary of subroutines and functions related to arrays. !nction Description Array,ar$s. Return a Oariant array t"at contains t"e ar$uments& DimArray,ar$s. Return an empty Oariant array& T"e ar$uments specify t"e dimension& )sArray,ar. Return True if t"is ariab*e is an array, 0a*se ot"er%ise& Koin,array. Koin,array, de*imiter. #oncatenate t"e array e*ements separated by t"e optiona* strin$ de*imiter and return as a Strin$& T"e defau*t de*imiter is a sin$*e space& L+ound,array. L+ound,array, dimension. Return t"e *o%er bound of t"e array ar$ument& T"e optiona* dimension specifies %"ic" dimension to c"ec(& T"e first dimension is 1& ReDim ar,ar$s. As Type #"an$e t"e dimension of an array usin$ t"e same synta3 as t"e D)M statement& T"e (ey%ord 'resere (eeps e3istin$ data intact L ReDim 'resere 3,1 To !. As )nte$er& Sp*it,str. Sp*it,str, de*imiter. Sp*it,str, de*imiter, n. Sp*it t"e strin$ ar$ument into an array of strin$s& T"e defau*t de*imiter is a space& T"e optiona* ar$ument DnF *imits t"e number of strin$s returned& 5+ound,array. 5+ound,array, dimension. Return t"e upper bound of t"e array ar$ument& T"e optiona* dimension specifies %"ic" dimension to c"ec(& T"e first dimension is 1& #.,.1. Changing the dimension of an arra" T"e desired dimension of an array is not a*%ays (no%n a"ead of time& Sometimes, t"e dimension is (no%n7 but it c"an$es periodica**y, and t"e code must be c"an$ed& An array ariab*e can be dec*ared %it" or %it"out specifyin$ t"e dimensions& 11o +asic proides a fe% different met"ods to set or c"an$e t"e dimensions of an array& T"e Array function $enerates a Oariant array t"at contains data& T"is is a 8uic( %ay to initia*iCe an array& 6ou are not re8uired to set t"e dimension of t"e array, but, if you do, it %i** c"an$e to become t"e array returned by t"e Array function& -i! aBC a 6 Arra.B%&>?><@'A<?= "PI"= @&Q>= "Jra:it."C T"e ar$uments passed to t"e Array function become data in t"e returned Oariant array& T"e DimArray function, on t"e ot"er "and, interprets t"e ar$uments as t"e dimensions of an array to create ,see Listin$ 21.& T"e ar$uments can be e3pressions, so a ariab*e can be used to set t"e dimension& Listing 21. Redimension array. Sub Exa!ple-i!Arra. -i! aBC= iG -i! #F a 6 Arra.B>7= >>= >'C # 6 "" 4 ,BoundBaBCC 4 " " 4 0BoundBaBCC Re! 7 ' aBC 6 -i!Arra.B%C REM t(e #a!e a# -i! aB%C aBC 6 -i!Arra.B'= >C REM t(e #a!e a# -i! aB'=>C i 6 ? a 6 -i!Arra.B%= iC Re! t(e #a!e a# -i! aB%=?C 48 # 6 # 4 CHRFB>7C 4 ,BoundBaBC=>C 4 " " 4 0BoundBaBC=>C Re! 7= % # 6 # 4 CHRFB>7C 4 ,BoundBaBC='C 4 " " 4 0BoundBaBC='C Re! 7= ? aBC 6 -i!Arra.BC REM an e!pt. arra. M#Box #= 7= "Exa!ple -i! Arra." End Sub T"e Array and DimArray functions bot" return an array of Oariants& T"e ReDim statement c"an$es t"e dimension of an e3istin$ array& T"is can c"an$e bot" indiidua* dimensions and t"e number of dimensions& T"e ar$uments can be e3pressions because t"e ReDim statement is ea*uated at run time& -i! eBC A# Inteer= i A# Inteer i 6 ? Re-i! eB<C A# Inteer REM -i!en#ion i# >= a #i8e o$ 7 3o < i# :alid& Re-i! eB% 3o >7C A# Inteer REM -i!en#ion i# >= a #i8e o$ % 3o >7 i# :alid& Re-i! eB%= iC A# Inteer REM -i!en#ion i# '= a #i8e o$ B7 3o %= 7 3o ?C i# :alid& Some tips re$ardin$ arrays: L+ound and 5+ound %or( %it" empty arrays& An empty array "as one dimension& T"e *o%er bound is Cero and t"e upper bound is 91& 5se ReDim to cause an e3istin$ array to become empty& T"e ReDim statement supports t"e (ey%ord 'resere& T"is attempts to sae t"e data %"en t"e dimensions of an array are c"an$ed& )ncreasin$ t"e dimension of an array preseres a** of t"e data, but decreasin$ t"e dimension causes data to be *ost by truncation& Data can be truncated at eit"er end& )f an e*ement in t"e ne% array e3isted in t"e o*d array, t"e a*ue is unc"an$ed& 5n*i(e some ariants of +AS)#, 11o +asic a**o%s a** dimensions of an array to be c"an$ed %"i*e sti** preserin$ data& -i! aBC A# Inteer Re-i! aB%= %= %C A# Inteer aB>=>=>C 6 > : aB>= >= 'C 6 ' : aB'= >= >C 6 % Re-i! pre#er:e aB9> 3o ?= ?= ?C A# Inteer Print "B" 4 aB>=>=>C 4 "= " 4 aB>= >= 'C 4 "= " 4 aB'= >= >C 4 "C" ReDim specifies bot" t"e dimensions and an optiona* type& )f t"e type is inc*uded, it must matc" t"e type specified %"en t"e ariab*e is dec*ared or 11o $enerates a compi*e9time error& Listin$ 22 is a uti*ity function t"at accepts a simp*e array and returns a strin$ %it" a** of t"e e*ements in t"e array& T"e ReDim e3amp*e code, a*so in Listin$ 22, uses ArrayToStrin$& Listing 22. Utility function array to string. REM Arra.3oStrin accept# a #i!ple arra. and place# t(e :alue REM o$ eac( ele!ent in t(e arra. into a #trin& "unction Arra.3oStrinBaBC A# OariantC A# Strin -i! iG= #F "or iG 6 ,BoundBaBCC 3o 0BoundBaBCC #F 6 #F 4 iG 4 " : " 4 aBiGC 4 CHRFB>7C Hext Arra.3oStrin 6 #F End "unction Sub Exa!pleRe-i!Pre#er:e -i! aB<C A# Inteer= bBC= cBC A# Inteer aB7C 6 7 : aB>C 6 > : aB'C 6 ' : aB%C 6 % : aB?C 6 ? : aB<C 6 < 49 Re! a i# di!en#ioned $ro! 7 to < *(ere aBiC 6 i M#Box Arra.3oStrinBaBCC= 7 = "aBC at #tart" Re! a i# re9di!en#ioned $ro! > to % *(ere aBiC 6 i Re-i! Pre#er:e aB> 3o %C A# Inteer M#Box Arra.3oStrinBaBCC= 7 = "aBC a$ter Re-i!" Re! Arra.BC return# a Oariant t.pe Re! b i# di!en#ioned $ro! 7 to @ *(ere bBiC 6 iW> b 6 Arra.B>= '= %= ?= <= A= 2= Q= @= >7C M#Box Arra.3oStrinBbBCC= 7 = "bBC at initial a##in!ent" Re! b i# di!en#ioned $ro! > to % *(ere bBiC 6 iW> Re-i! Pre#er:e bB> 3o %C M#Box Arra.3oStrinBbBCC= 7 = "bBC a$ter Re-i!" Re! 3(e $ollo*in i# HO3 :alid becau#e t(e arra. i# alread. di!en#ioned Re! to a di$$erent #i8e Re! a 6 Arra.B7= >= '= %= ?= <C
Re! c i# di!en#ioned $ro! 7 to < *(ere cBiC 6 i Re! I$ "Re-i!" (ad been done on c= t(en t(i# *ould HO3 *or1 c 6 Arra.B7= >= '= "t(ree"= ?= <C M#Box Arra.3oStrinBcBCC= 7 = "Inteer arra. cBC A##ined to a Oariant" Re! Ironicall.= t(i# i# allo*ed but c *ill contain no dataK Re-i! Pre#er:e cB> 3o %C A# Inteer M#Box Arra.3oStrinBcBCC= 7 = "Re-i! Inteer cBC a$ter a##ined Oariant" End Sub Oisua* +asic "as different ru*es for c"an$in$ t"e dimensions of an array, and t"ese ru*es c"an$e bet%een ersions of Oisua* +asic& As a $enera* ru*e, 11o +asic is more f*e3ib*e& #.,.2. The unexpected beha'ior of arra"s Assi$nin$ one )nte$er ariab*e to anot"er copies t"e a*ue, and t"e ariab*es are not re*ated in any ot"er %ay& )n ot"er %ords, if you c"an$e t"e first ariab*eGs a*ue, t"e second ariab*eGs a*ue does not c"an$e& T"is is not true for array ariab*es& Assi$nin$ one array ariab*e to anot"er ma(es a reference to t"e first array rat"er t"an copyin$ t"e data& A** c"an$es made to eit"er are automatica**y seen by t"e ot"er& )t doesnGt matter %"ic" one is c"an$ed7 t"ey are bot" affected& T"is is t"e difference bet%een Dpass by valueF ,inte$ers. and Dpass by referenceF ,arrays.& Listing 23. -rrays copy as references. Sub Exa!pleArra.Cop.I#Re$ -i! aB<C A# Inteer= cB?C A# Inteer= #F cB7C 6 ? : cB>C 6 % : cB'C 6 ' : cB%C 6 > : cB?C 6 7 aBC 6 cBC aB>C 6 2 cB'C 6 >7 #F 6 "**** aBC *****" 4 CHRFB>7C 4 Arra.3oStrinBaBCC 4 CHRFB>7C 45 CHRFB>7C 4 "**** cBC *****" 4 CHRFB>7C 4 Arra.3oStrinBcBCC M#Box #F= 7 = "C(ane One= C(ane Bot(" End Sub 50 To i**ustrate t"at arrays are assi$ned by reference, create t"ree arrays L a,., b,., and c,. L as s"o%n in 0i$ure 23& )nterna**y, 11o +asic creates t"ree arrays t"at are referenced by a,., b,., and c,.& Figure 23. -ssigning an array assigns a reference. Assi$n array a,. to array b,., and bot" a,. and b,. reference t"e same data& T"e ariab*e a,. does not reference t"e ariab*e b,., it references t"e same data referenced by b,. ,see 0i$ure 2!.& T"erefore, c"an$in$ a,. a*so c"an$es b,.& T"e ori$ina* array referenced by a,. is no *on$er referenced& Figure 24. -ssigning an array assigns a reference. Assi$n array b,. to array c,., and bot" b,. and c,. reference t"e same data& T"e ariab*e a,. remains unc"an$ed, as s"o%n in 0i$ure 2A& Figure 25. -ssigning an array assigns a reference. TIP Type c"ec(in$ is not performed %"en an array is assi$ned to anot"er array& Do not assi$n arrays of different types to eac" ot"er& +ecause no type c"ec(in$ is performed %"en an array is assi$ned to anot"er array, une3pected and obscure prob*ems can occur& T"e Array function returns a Oariant array, and is t"e 8uic(est met"od to assi$n mu*tip*e a*ues to an array ariab*e& An obious prob*em is t"at an )nte$er array may contain Strin$ a*ues if it references a Oariant array& A *ess obious prob*em is t"at t"e ReDim statement %or(s based on t"e dec*ared type& T"e statement DReDim 'resereF on an )nte$er array assi$ned to a Oariant array fai*s to presere t"e data& -i! aBC A# Inteer REM -eclare aBC a# an InteerBC aBC 6 Arra.B7= >= '= %= ?= <= AC REM A##in a OariantBC to an InteerBC 51 Re-i! Pre#er:e aB> 3o %C A# Inteer REM 3(i# *ipe# t(e arra. To safe*y assi$n arrays %"i*e maintainin$ t"e correct data type, anot"er met"od is re8uired& #opy eac" e*ement in t"e array indiidua**y& T"is a*so preents t%o array ariab*es from referencin$ t"e same array& Listing 24. More comple. array e.ample. Sub Exa!pleSetIntArra. -i! iABC A# Inteer SetIntArra.BiA= Arra.B@= Q= "2"= "#ix"CC M#Box Arra.3oStrinBiAC= 7= "A##in a Oariant to an Inteer" End Sub REM -i!en#ion t(e $ir#t arra. to (a:e t(e #a!e di!en#ion# a# t(e #econd& REM Per$or! an ele!ent9b.9ele!ent cop. o$ t(e arra.& Sub SetIntArra.BiArra.BC A# Inteer= :BC A# OariantC -i! i A# ,on Re-i! iArra.B,BoundB:BCC 3o 0BoundB:BCCC A# Inteer "or i 6 ,BoundB:C 3o 0BoundB:C iArra.BiC 6 :BiC Hext End Sub 3.#. /ubroutines and functions Subroutines are used to $roup *ines of code into meanin$fu* pieces of %or(& A function is a subroutine t"at returns a a*ue& T"e use of subroutines and functions faci*itates testin$, code reuse, and readabi*ity& T"is in turn reduces errors& T"e (ey%ord Sub defines t"e be$innin$ of a subroutine, and 2nd Sub defines t"e end of a subroutine& Sub "ir#tSub Print "Runnin "ir#tSub" End Sub To use a subroutine, p*ace t"e name of t"e subroutine t"at you %ant to ca** on a *ine& T"e name can optiona**y be preceded by t"e (ey%ord #a**& Sub Main Call "ir#tSub ) Call Sub "ir#tSub "ir#tSub ) Call Sub "ir#tSub aain End Sub Subroutine and function names must be uni8ue in a modu*e& T"ey are sub/ect to t"e same namin$ conentions as ariab*es, inc*udin$ t"e use of spaces in t"eir names& Sub One Xna!e *it( #paceY End Sub Sub Xna!e *it( #paceY Print "I a! (ere" End Sub Oisua* +asic a**o%s a subroutine to be preceded by optiona* (ey%ords suc" as 'ub*ic or 'riate& Startin$ %it" 11o 2&0, you can define a routine as pub*ic or priate, but t"e routine is a*%ays pub*ic un*ess #ompatibi*ityMode,True. is used first& 52 Dec*are a subroutine as priate by precedin$ Sub %it" t"e (ey%ord 'riate& Pri:ate Sub Pri:Sub Print "In Pri:ate Sub" bbxx 6 ? End Sub 5sin$ 1ption #ompatibi*e is not sufficient to enab*e 'riate scope, #ompatibi*ityMode,True. must be used& Sub 3e#tPri:ateSub Co!patibilit.ModeB"al#eC )Re;uired onl. i$ Co!patibilit.ModeB3rueC alread. u#ed& Call Pri:SubBC )3(i# call *or1#& Co!patibilit.ModeB3rueC )3(i# i# re;uired= e:en i$ Option Co!patible i# u#ed Call Pri:SubBC )Runti!e error Bi$ Pri:Sub i# in a di$$erent !oduleC& End Sub T"e (ey%ord 0unction is used to dec*are a function %"ic", *i(e a ariab*e, can define t"e type it returns& )f t"e type is not dec*ared, t"e return type defau*ts to Oariant& 6ou can assi$n t"e return a*ue at any point and as many times as you %ant before t"e function ends& T"e *ast a*ue assi$ned is returned& Sub te#t Print "3(e $unction return# " 4 3e#t"unc End Sub "unction 3e#t"unc A# Strin 3e#t"unc 6 "(ello" End "unction #...1. )rguments A ariab*e t"at is passed to a routine is ca**ed an ar$ument& Ar$uments must be dec*ared& T"e same ru*es for dec*arin$ ariab*e types app*y to dec*arin$ ar$ument types& A routine name can optiona**y be fo**o%ed by parent"eses, bot" %"en it is defined and %"en it is ca**ed& A routine t"at accepts ar$uments can optiona**y enc*ose t"e ar$ument *ist in parent"eses& T"e ar$ument *ist fo**o%s t"e routine name on t"e same *ine& +*an( space is a**o%ed bet%een t"e name of t"e routine and t"e ar$ument *ist& Listing 25. *imple argument testing. Sub Exa!plePara!3e#t>BC Call Para!3e#t>B'= "3*o"C Call Para!3e#t> >= "One" End Sub Sub Para!3e#t>Bi A# Inteer= #FC Print "Inteer 6 " 4 i 4 " Strin 6 " 4 #F End Sub 3ass b' reference or b' value +y defau*t, ar$uments are passed by reference rat"er t"an by a*ue& )n ot"er %ords, %"en t"e ca**ed subroutine modifies an ar$ument, t"e ca**er sees t"e c"an$e& 6ou can oerride t"is be"aior by usin$ t"e +yOa* (ey%ord& T"is causes a copy of t"e ar$ument ,rat"er t"an a reference to t"e ar$ument. to be sent ,see Listin$ 26 and 0i$ure 26.& 53 TIP #onstants passed as ar$uments by reference cause une3pected be"aior if t"eir a*ue is modified in t"e ca**ed routine& T"e a*ue may arbitrari*y c"an$e bac( inside t"e ca**ed routine& 0or e3amp*e, ) "ad a subroutine t"at %as supposed to decrement an )nte$er ar$ument in a *oop unti* it %as Cero7 t"e ar$ument neer became Cero& Listing 26. -rguments by reference and by value. Sub Exa!pleAru!entOalAndRe$BC -i! i>G= i'G i> 6 > : i' 6 > Aru!entOalAndRe$Bi>= i'C M#Box "Aru!ent pa##ed b. re$erence *a# > and i# no* " 4 i> 4 CHRFB>7C 45 "Aru!ent pa##ed b. :alue *a# > and i# #till " 4 i' 4 CHRFB>7C End Sub Sub Aru!entOalAndRe$BiRe$G= B.Oal iOalC iRe$ 6 iRe$ W > ) 3(i# *ill a$$ect t(e caller iOal 6 iOal 9 > ) 3(i# *ill not a$$ect t(e caller End Sub Figure 26. 9ass by reference allows changes to be passed back to the caller. Oisua* +asic supports t"e optiona* (ey%ord +yRef& T"is (ey%ord %as introduced into 11o +asic startin$ %it" 11o 2&0& 4ote t"at pass by reference is t"e defau*t be"aior& A ariab*e cannot be passed by a*ue if t"e type does not matc"& T"e macros in Listin$ 2M and Listin$ 2@ differ in t"e type used to dec*are t"e parameter& Listing 27. *imple swap with a string parameter. Sub #S*apB #-atu! A# Strin C -i! a#-atu!B> to %C A# Strin -i! #-u!!. A# Strin a#-atu!6SplitB#-atu!= "&"C #-u!!.6a#-atu!B7C a#-atu!B7C6a#-atu!B'C a#-atu!B'C6#-u!!. #-atu!6MoinBa#-atu!="9"C End Sub Listing 28. *imple swap with a variant parameter. Sub :S*apB :-atu! A# Oariant C -i! a#-atu!B> to %C A# Strin -i! #-u!!. A# Strin a#-atu!6SplitB:-atu!= "&"C #-u!!.6a#-atu!B7C 54 a#-atu!B7C6a#-atu!B'C a#-atu!B'C6#-u!!. :-atu!6MoinBa#-atu!="9"C End Sub T"e fo**o%in$ macro uses a ariant and a strin$ to ca** a macro t"at accepts a ariant, and t"e macro t"at accepts t"e strin$& 'assin$ a ariant to a met"od t"at accepts a strin$ parameter basses t"e a*ue by reference& T"e une3pected t"in$ is t"at passin$ a strin$ to t"e met"od t"at accepts a ariant, passes t"e a*ue by reference& Listing 29. est reference by parameter type. Sub pa##B.Re$erence3e#ter -i! :Oar A# Oariant -i! #Oar A# #trin -i! # A# Strin :Oar6"7>&7'&'7>>" #Oar6"7>&7'&'7>>" # 6 :Oar 4 " #S*apB :ariant :ar #trin para! C 66D " #S*apB:OarC # 6 # 4 :Oar 4 CHRFB>7C # 6 # 4 #Oar 4 " #S*apB #trin :ar #trin para! C 66D " #S*apB#OarC # 6 # 4 #Oar 4 CHRFB>7C :Oar6"7>&7'&'7>>" #Oar6"7>&7'&'7>>" # 6 # 4 :Oar 4 " :S*apB :ariant :ar :ariant para! C 66D " :S*apB:OarC # 6 # 4 :Oar 4 CHRFB>7C # 6 # 4 #Oar 4 " :S*apB #trin :ar :ariant para! C 66D " :S*apB#OarC # 6 # 4 #Oar 4 CHRFB>7C M#BoxB#C End Sub )t is important t"at you understand %"en a ariab*e is passed to a met"od as a reference or a a*ue& )t is e8ua**y important to understand %"en t"e a*ue contained in a ariab*e is copied by a*ue or copied by reference& Oariab*es %it" simp*e types copy by a*ue7 for e3amp*e, assi$nin$ one inte$er ariab*e to anot"er& Arrays a*%ays copy by reference& )f you assi$n one array to anot"er, bot" ariab*es reference and modify t"e same array& 541 Serices copy by reference& T"is means t"at you can do t"in$s suc" as oDoc ? T"is#omponent, and bot" ariab*es reference t"e same ob/ect& Structs copy by a*ue& T"is frustrates many peop*e %"en t"ey first encounter t"e be"aior, but t"ere is a ery $ood reason for it& 0irst, t"e prob*em7 oBorder&3op,ine&Outer,ineWidt( 6 ' 55 fai*s because TopLine is a struct and t"e a*ue is returned as a copy rat"er t"an a reference& T"e code as s"o%n c"an$es t"e outer *ine %idt" on a copy of t"e struct rat"er t"an t"e struct associated %it" t"e border ob/ect& T"e correct %ay to c"an$e t"e border is ,: 6 oBorder&3op,ine : :&Outer,ineWidt( 6 ' : oBorder&3op,ine 6 :.& A *ead dee*oper c*aimed t"at one or t%o serices and strutcs do not assi$n - copy as e3pected, but "e cou*d not remember %"ic"& ) "ae not encountered t"e ob/ects t"at io*ate t"e $uide*ines, but, ) try to remember t"e prob*em so t"at ) am not ta(en una%are& Optional arguments 6ou can dec*are ar$uments as optiona* by precedin$ t"em %it" t"e (ey%ord 1ptiona*& A** of t"e ar$uments fo**o%in$ an optiona* ar$ument must a*so be optiona*& 5se t"e )sMissin$ function to determine if an optiona* ar$ument is missin$& Listing 30. Optional arguments. REM Ma1e te#t call# *it( optional aru!ent#& REM Call# *it( Inteer and Oariant aru!ent# #(ould .ield t(e #a!e re#ult& REM 0n$ortunatel.= t(e. do not& Sub Exa!pleArOptionalBC -i! #F # 6 "Oariant Aru!ent# BC 6D " 4 3e#tOptBC 4 CHRFB>7C 45 "Inteer Aru!ent# BC 6D " 4 3e#tOptIBC 4 CHRFB>7C 45 "999999999999999999999999999999999999999999999" 4 CHRFB>7C 45 "Oariant Aru!ent# B==C 6D " 4 3e#tOptB==C 4 CHRFB>7C 45 "Inteer Aru!ent# B==C 6D " 4 3e#tOptIB==C 4 CHRFB>7C 45 "999999999999999999999999999999999999999999999" 4 CHRFB>7C 45 "Oariant Aru!ent# B>C 6D " 4 3e#tOptB>C 4 CHRFB>7C 45 "Inteer Aru!ent# B>C 6D " 4 3e#tOptIB>C 4 CHRFB>7C 45 "999999999999999999999999999999999999999999999" 4 CHRFB>7C 45 "Oariant Aru!ent# B='C 6D " 4 3e#tOptB='C 4 CHRFB>7C 45 "Inteer Aru!ent# B='C 6D " 4 3e#tOptIB='C 4 CHRFB>7C 45 "999999999999999999999999999999999999999999999" 4 CHRFB>7C 45 "Oariant Aru!ent# B>='C 6D " 4 3e#tOptB>='C 4 CHRFB>7C 45 "Inteer Aru!ent# B>='C 6D " 4 3e#tOptIB>='C 4 CHRFB>7C 45 "999999999999999999999999999999999999999999999" 4 CHRFB>7C 45 "Oariant Aru!ent# B>==%C 6D " 4 3e#tOptB>==%C 4 CHRFB>7C 45 "Inteer Aru!ent# B>==%C 6D " 4 3e#tOptIB>==%C 4 CHRFB>7C M#Box #= 7= "Optional Aru!ent# o$ 3.pe Oariant or Inteer" End Sub REM Return a #trin t(at contain# eac( aru!ent& I$ t(e aru!ent REM i# !i##in= t(en an M i# u#ed in it# place& "unction 3e#tOptBOptional :>= Optional :'= Optional :%C A# Strin 3e#tOpt 6 "" 4 II"BI#Mi##inB:>C= "M"= StrB:>CC 45 II"BI#Mi##inB:'C= "M"= StrB:'CC 45 II"BI#Mi##inB:%C= "M"= StrB:%CC End "unction REM Return a #trin t(at contain# eac( aru!ent& I$ t(e aru!ent REM i# !i##in= t(en an M i# u#ed in it# place& "unction 3e#tOptIBOptional i>G= Optional i'G= Optional i%GC A# Strin 56 3e#tOptI 6 "" 4 II"BI#Mi##inBi>C= "M"= StrBi>CC 45 II"BI#Mi##inBi'C= "M"= StrBi'CC 45 II"BI#Mi##inBi%C= "M"= StrBi%CC End "unction 6ou can omit any optiona* ar$uments& Listin$ 30 demonstrates t%o functions t"at accept optiona* ar$uments& T"e functions are t"e same e3cept for t"e ar$ument types& 2ac" function returns a strin$ containin$ t"e ar$ument a*ues concatenated to$et"er& Missin$ ar$uments are represented by t"e *etter DMF in t"e strin$& A*t"ou$" t"e return a*ues from Test1pt and Test1pt1 s"ou*d be t"e same for t"e same ar$ument *ists, t"ey are not ,see 0i$ure 2M.& T"is is a bu$& TIP T"e )sMissin$ function returns incorrect resu*ts for ariab*es t"at are not of type Oariant %"en t"e missin$ ar$ument is fo**o%ed by a comma& Figure 27. "n rare cases) non43ariant optional arguments fail. "efault argument values 11o ersion 2&0 introduced defau*t a*ues for missin$ ar$uments& T"is a**o%s a defau*t a*ue to be specified if an optiona* ar$ument is missin$& 6ou must use t"e (ey%ords D1ption #ompatib*eF for defau*t a*ues to %or(& Option Co!patible Sub -e$aultExa!pleBOptional n a# Inteer6>77C REM I$ I#Mi##inBnC 3(en n 6 >77 )I *ill not (a:e to do t(i# an.!oreK Print n End Sub #...2. 6ecursi'e routines A recursie routine ca**s itse*f& #onsider ca*cu*atin$ t"e mat"ematica* function 0actoria* for positie inte$ers& T"e usua* definition is recursie& 57 Listing 31. Recursively generate factorial. Sub -o"actorial Print "Recur#i:e "actorial 6 " 4 Recur#i:e"actorialB?C Print "Iterati:e "actorial 6 " 4 Iterati:e"actorialB?C End Sub "unction Iterati:e"actorialBB.Oal n A# ,onC A# ,on -i! an#*er A# ,on an#*er 6 > -o W(ile n D > an#*er 6 an#*er * n n 6 n 9 > ,oop Iterati:e"actorial 6 an#*er End "unction ) 3(i# $inall. *or1# in :er#ion >&> "unction Recur#i:e"actorialBB.Oal n A# ,onC A# ,on Recur#i:e"actorial 6 > I$ n D > 3(en Recur#i:e"actorial 6 n * Recur#i:e"actorialBn9>C End "unction #omputers use a data structure ca**ed a stac(& At "ome, ) "ae a stac( of boo(s t"at ) %ant to read& ;"en ) receie a ne% boo(, ) p*ace it on top of t"e stac(& ;"en ) "ae time to read, ) ta(e t"e top boo( from t"e stac(& T"is is simi*ar to t"e data structure t"at a computer uses: a section of memory in a computer for temporary stora$e in %"ic" t"e *ast item stored is t"e first retrieed& Stac(s are usua**y used %"en a computer ca**s a routine and passes ar$uments& A typica* procedure fo**o%s: 1& 'us" t"e current run *ocation onto t"e stac(& 2& 'us" eac" ar$ument onto t"e stac(& 3& #a** t"e desired function or subroutine& !& T"e ca**ed routine uses t"e ar$uments from t"e stac(& A& T"e ca**ed routine fre8uent*y uses t"e stac( to store its o%n ariab*es& 6& T"e ca**ed routine remoes t"e ar$uments from t"e stac(& M& T"e ca**ed routine remoes and saes t"e ca**erGs *ocation from t"e stac(& @& )f t"e ca**ed routine is a function, t"e return a*ue is p*aced on t"e stac(& B& T"e ca**ed routine returns to t"e ca**er from t"e saed *ocation on t"e stac(& 10& )f t"e ca**ed routine is a function, t"e return a*ue is ta(en from t"e stac(& A*t"ou$" arious optimiCations are used, t"ere is a*%ays some oer"ead associated %it" ca**in$ subroutines and functions& T"ere is oer"ead in runnin$ time and in t"e memory re8uired& T"e recursie ersion of 0actoria* continua**y ca**s itse*f& ;"i*e ca*cu*atin$ t"e factoria* of four, t"ere is one point at %"ic" t"e stac( contains information for ca**s for !, 3, 2, and 1& 0or some functions L t"e 0ibonacci series, for e3amp*e L t"is ca** be"aior may be pro"ibitie, and a non9recursie a*$orit"m s"ou*d be used instead& 58 3.$. /cope of variables4 subroutines4 and functions T"e idea of scope dea*s %it" t"e *ifetime and isibi*ity of a ariab*e, subroutine, or function in 11o +asic& T"e scope depends on t"e *ocation of t"e dec*aration, and t"e (ey%ords 'ub*ic, 'riate, Static, and J*oba*& Dim is e8uia*ent to 'riate, but ariab*es are 'riate on*y if #ompatibi*ityMode,True. is used& #./.1. !ocal 'ariables defined in a subroutine or function Oariab*es dec*ared inside a subroutine or function are ca**ed *oca* ariab*es& )t is a*so common*y said t"at a ariab*e is *oca* to a routine if t"e ariab*e is dec*ared inside t"at routine& 6ou can dec*are a ariab*e inside a subroutine or function by usin$ t"e Dim (ey%ord& Oariab*es defined inside a routine are isib*e on*y inside t"at routine& )t is not possib*e to direct*y access a ariab*e defined inside a routine from outside t"e routine& Eo%eer, it is possib*e to access a ariab*e defined outside any routine L for e3amp*e, in a modu*e "eader L from inside a routine& ;"en a ariab*e or routine name is encountered inside a routine, 11o +asic starts *oo(in$ for t"e ariab*e or routine in t"e fo**o%in$ order: current routine, modu*e, *ibrary, and ot"er open *ibraries& )n ot"er %ords, it starts inside and %or(s its %ay out& Oariab*es defined in a routine are created and initia*iCed eac" time t"e routine is entered& T"e ariab*es are destroyed eery time t"e routine is e3ited because t"e routine is finis"ed& Leain$ t"e routine to ca** anot"er routine does not cause t"e ariab*es to be reinitia*iCed& 5se t"e (ey%ord Static to c"an$e a ariab*eGs creation and destruction times to t"e ca**in$ macroGs start and finis" times, respectie*y& A*t"ou$" t"e ariab*e is isib*e on*y in t"e routine containin$ t"e ariab*e, t"e ariab*e is initia*iCed once %"en t"e macro starts runnin$, and t"e ariab*eVs a*ues are retained t"rou$" mu*tip*e ca**s to t"e same routine& )n ot"er %ords, you start %it" no macro runnin$& T"e first time t"at a subroutine or function t"at contains a static ariab*e is ca**ed, t"e static ariab*es contain initia* a*ues based on t"eir types& T"e static ariab*es retain t"eir a*ues bet%een ca**s as *on$ as t"e macro as a %"o*e did not stop runnin$& T"e (ey%ord Static uses t"e same synta3 as t"e (ey%ord Dim, and is a*id on*y inside a subroutine or function& Listin$ 32 ca**s a routine t"at uses a static ariab*e& Listing 32. *tatic e.ample. Sub Exa!pleStatic Exa!pleStaticWor1erBC Exa!pleStaticWor1erBC End Sub Sub Exa!pleStaticWor1er Static iStatic> A# Inteer -i! iHonStatic A# Inteer
iHonStatic 6 iHonStatic W > iStatic> 6 iStatic> W > M#box "iHonStatic 6 " 4 iHonStatic 4 CHRFB>7C 45 "iStatic> 6 " 4 iStatic> End Sub #./.2. 5ariables defined in a module T"e Dim, J*oba*, 'ub*ic, or 'riate statements are used to dec*are ariab*es in a modu*e "eader& J*oba*, 'ub*ic, and 'riate use t"e same synta3 as t"e Dim statement, but t"ey canGt dec*are ariab*es inside a subroutine or function& 2ac" ariab*e type "as a different *ife cyc*e, as summariCed in Tab*e 1!& 59 T"e (ey%ords Static, 'ub*ic, 'riate, and J*oba* are not used as modifiers to t"e (ey%ord Dim7 t"ey are used instead of t"e (ey%ord Dim& A*t"ou$" it is sometimes necessary to define a ariab*e in a modu*e "eader, you s"ou*d aoid it if possib*e& Oariab*es defined in t"e "eader can be seen in ot"er modu*es t"at donGt e3pect t"em& )tGs difficu*t to determine %"y t"e compi*er c*aims t"at a ariab*e is a*ready defined if it is defined in anot"er *ibrary or modu*e& 2en %orse, t%o %or(in$ *ibraries may stop %or(in$ because of namin$ conf*icts& Table 14. Life cycle of a variable defined in a module header. Key"ord Initiali#ed Dies Scope J*oba* #ompi*e time #ompi*e time A** modu*es and *ibraries& 'ub*ic Macro start Macro finis" Dec*arin$ *ibrary container& Dim Macro start Macro finis" Dec*arin$ *ibrary container& 'riate Macro start Macro finis" Dec*arin$ modu*e& 5lobal 5se J*oba* to dec*are a ariab*e t"at is aai*ab*e to eery modu*e in eery *ibrary& T"e *ibrary containin$ t"e J*oba* ariab*e must be *oaded for t"e ariab*e to be isib*e& ;"en a *ibrary is *oaded, it is automatica**y compi*ed and made ready for use7 t"is is %"en a J*oba* ariab*e is initia*iCed& #"an$es made to a J*oba* ariab*e are seen by eery modu*e and are persisted een after t"e macro is finis"ed& J*oba* ariab*es are reset %"en t"e containin$ *ibrary is compi*ed& 23itin$ and restartin$ 1pen1ffice&or$ causes a** *ibraries to be compi*ed and a** J*oba* ariab*es to be initia*iCed& Modifyin$ t"e modu*e containin$ t"e J*oba* definition a*so forces t"e modu*e to be recompi*ed& Jlobal iHu!berO$3i!e#Run Oariab*es dec*ared J*oba* are simi*ar to ariab*es dec*ared Static, but Static %or(s on*y for *oca* ariab*es, and J*oba* %or(s on*y for ariab*es dec*ared in t"e "eader& 3ublic 5se 'ub*ic to dec*are a ariab*e t"at is isib*e to a** modu*es in t"e dec*arin$ *ibrary container& 1utside t"e dec*arin$ *ibrary container, t"e pub*ic ariab*es arenGt isib*e& 'ub*ic ariab*es are initia*iCed eery time a macro runs& An app*ication *ibrary is a *ibrary t"at is dec*ared in t"e D1pen1ffice&or$F *ibrary container& T"is is aai*ab*e %"en 11o is runnin$, is stored in its o%n directory, and eery document can ie% it& Document9*ee* *ibraries are stored in 11o documents& T"e *ibraries are saed as part of t"e document and are not isib*e outside t"e document& 'ub*ic ariab*es dec*ared in an app*ication *ibrary are isib*e in eery 11o document9*ee* *ibrary& 'ub*ic ariab*es dec*ared in a *ibrary contained in an 11o document are not isib*e in app*ication9*ee* *ibraries& Dec*arin$ a 'ub*ic ariab*e in a document *ibrary effectie*y "ides a 'ub*ic ariab*e dec*ared in an app*ication *ibrary& Simp*y stated ,see Tab*e 1A., if you dec*are a 'ub*ic ariab*e in a document, it is isib*e on*y in t"e document and it %i** "ide a 'ub*ic ariab*e %it" t"e same name dec*ared outside t"e document& A 'ub*ic ariab*e dec*ared in t"e app*ication is isib*e eery%"ere L un*ess a ariab*e dec*aration %it" more *oca* scope ta(es priority oer t"e dec*aration %it" more $*oba* scope& Public o-ialo A# ObNect 60 Table 15. he scope of a 9ublic variable depends on where it is declared. Declaration Location Scope App*ication Oisib*e eery%"ere& Document Oisib*e on*y in t"e dec*arin$ document& App*ication and Document Macros in t"e document are unab*e to see t"e app*ication9*ee* ariab*e& 3rivate or "im 5se 'riate or Dim to dec*are a ariab*e in a modu*e t"at s"ou*d not be isib*e in anot"er modu*e& 'riate ariab*es, *i(e 'ub*ic ariab*es, are initia*iCed eery time a macro runs& A sin$*e ariab*e name may be used by t%o different modu*es as t"eir o%n ariab*e if t"e ariab*e is dec*ared 'riate& Pri:ate o-ialo A# Oariant Dec*arin$ a ariab*e usin$ Dim is e8uia*ent to dec*arin$ a ariab*e as 'riate& 'riate ariab*es are on*y priate, "o%eer, on*y %it" #ompatibi*ityMode,True.& 1ption #ompatib*e "as no affect on priate ariab*es& A 'riate ariab*e is isib*e outside t"e dec*arin$ modu*e un*ess #ompatibi*ityMode,True. is used& To see for yourse*f, create t%o modu*es L Modu*e1 and Modu*e2 L in t"e same *ibrary& )n Modu*e1, add t"e dec*aration D'riate pri=ar As )nte$erF& Macros in Modu*e2 can use t"e ariab*e Dpri=arF& 2en if Modu*e2 is *ocated in a different *ibrary in t"e same document, t"e ariab*e Dpri=arF is isib*e and usab*e& )f #ompatibi*ityMode,True. is used, "o%eer, t"en t"e priate ariab*e is no *on$er isib*e outside of t"e dec*arin$ modu*e& )n Modu*e1, dec*are a ariab*e D'riate pri=ar As Doub*eF& A ariab*e of t"e same name is dec*ared in Modu*e2, but it is an )nte$er ariab*e& 2ac" modu*e sees its o%n 'riate ariab*e& #"an$in$ t"ese t%o ariab*es to "ae 'ub*ic scope rat"er t"an 'riate introduces an u$*y situation7 on*y one of t"ese is isib*e and usab*e, but you donGt (no% %"ic" one it is %it"out performin$ a test& Assi$n t"e a*ue !&M to t"e ariab*e, and see if it is an )nte$er or a Doub*e& 3.&. Operators An operator is a symbo* t"at denotes or performs a mat"ematica* or *o$ica* operation& An operator, *i(e a function, returns a resu*t& 0or e3amp*e, t"e N operator adds t%o numbers& T"e ar$uments to t"e operator are ca**ed operands& 1perators are assi$ned a precedence& An operator %it" a precedence of 1 is said to "ae a "i$" precedence *ee*7 it is, after a**, number 1T TIP ;"i*e typesettin$ mat"ematica* e8uations, t"e minus si$n ,]. is represented usin$ t"e 5nicode c"aracter 5N2212& ;it" 11o +asic, "o%eer, AS#)) code !A ,9. must be used instead& )n 11o +asic ,see Tab*e 16., operators are ea*uated from *eft to ri$"t %it" t"e restriction t"at an operator %it" a "i$"er precedence is used before an operator %it" a *o%er precedence& 0or e3amp*e, 1 N 2 \ 3 ea*uates to M because mu*tip*ication "as "i$"er precedence t"an addition& 'arent"eses may be used to modify t"e order of ea*uation& 0or e3amp*e, ,1N2. \ 3 ea*uates to B because t"e e3pression inside t"e parent"eses is ea*uated first& 61 Table 16. Operators supported by OpenOffice.org !asic. Precedence Operator Type Description 1 41T 5nary Lo$ica* or bit9%ise 41T 1 9 5nary Leadin$ minus si$n, ne$ation 1 N 5nary Leadin$ p*us si$n 2 ^ +inary 4umerica* e3ponentiation& Standard mat"ematica* precedence %ou*d "ae e3ponentiation "i$"er t"an ne$ation& 3 \ +inary 4umerica* mu*tip*ication 3 - +inary 4umerica* diision ! M1D +inary 4umerica* remainder after diision A S +inary )nte$er diision 6 9 +inary 4umerica* subtraction 6 N +inary 4umerica* addition and strin$ concatenation M Q +inary Strin$ concatenation @ )S +inary Do bot" operands reference t"e same ob/ect> @ ? +inary 28ua*s @ [ +inary Less t"an @ R +inary Jreater t"an @ [? +inary Less t"an or e8ua* to @ R? +inary Jreater t"an or e8ua* to @ [R +inary 4ot e8ua* B A4D +inary +it9%ise for numerics and *o$ica* for +oo*ean B 1R +inary +it9%ise for numerics and *o$ica* for +oo*ean B I1R +inary 23c*usie 1R, bit9%ise for numerics and *o$ica* for +oo*ean B 2_O +inary 28uia*ence, bit9%ise for numerics and *o$ica* for +oo*ean B )M' +inary )mp*ication bit9%ise for numerics and *o$ica* for +oo*ean& TIP 11o 'recedence does not fo**o% standard mat"ematica* ru*es7 for e3amp*e, ne$ation s"ou*d "ae a *o%er precedence t"an e3ponentiation so 91^2 s"ou*d be 91, not 1& Oisua* +asic uses a different precedence for operators L for e3amp*e, numerica* e3ponentiation and ne$ation are s%itc"ed, as are inte$er diision and remainder after diision& T"e %ord DbinaryF means somet"in$ made of or based on t%o t"in$s& D5naryF means somet"in$ made of or based on one t"in$& A binary operator, not to be confused %it" a binary number, is p*aced bet%een t%o operands& 0or e3amp*e, t"e addition operator uses t%o operands %it" 1N2& )n 11o +asic, binary operators are a*%ays ea*uated from *eft to ri$"t based on operator precedence& A unary operator re8uires one operand t"at is p*aced direct*y to t"e ri$"t of t"e operator& 0or e3amp*e, 9 ,1 N 3.& +y necessity, a series of unary operators are ea*uated ri$"t to *eft& 0or e3amp*e, N 9 ,1N3. must ea*uate t"e ri$"tmost ne$ation operator first& 62 #.0.1. Mathematical and string operators Mat"ematica* operators can be used %it" a** numerica* data types& ;"en operands of different types are mi3ed, a conersion is made to minimiCe t"e *oss of precision& 0or e3amp*e, 1 N 3&!!3 causes a conersion to a f*oatin$9point number rat"er t"an a conersion to an )nte$er& )f t"e first operand is a number and t"e second operand is a strin$, t"e strin$ is conerted to a number& )f t"e strin$ does not contain a a*id numerica* a*ue, a Cero is returned and no error is $enerated& Assi$nin$ a strin$ direct*y to a numeric ariab*e, "o%eer, a*%ays assi$ns t"e a*ue Cero and no errors are $enerated& Listing 33. *trings are automatically converted to numbers when re8uired. -i! i A# Inteer i 6 "abc" )A##inin a #trin *it( no nu!ber# .ield# 8ero not an error Print i )7 i 6 "%abc" )A##in# %= auto!aticall. con:ert# a# it can& Print i )% Print ? W "abc" )? 11o +asic tries to automatica**y conert types& 4o errors are $enerated %"en a strin$ is used %"ere a number is re8uired& T"is is discussed in dept" *ater& )nar' plus 678 and minus 698 11o +asic a**o%s unary operators to "ae spaces bet%een t"e operator and t"e operand ,see Tab*e B.& 5nary operators a*so "ae t"e "i$"est precedence and are ea*uated from ri$"t to *eft& A *eadin$ p*us si$n is ar$uab*y use*ess L it emp"asiCes t"at a constant is not ne$atie but is ot"er%ise effectie*y i$nored& A *eadin$ minus si$n indicates numeric ne$ation& E:ponentiation 6;8 4umerica* e3ponentiation supports inte$er and f*oatin$9point e3ponents& T"e e3ponentiation operator can operate on a ne$atie number on*y if t"e e3ponent is an inte$er& re#ult 6 nu!berZexponent A positie inte$er e3ponent "as a conceptua**y simp*e representation& T"e number is mu*tip*ied by itse*f e3ponent times& 0or e3amp*e, 2^! ? 2 \ 2 \ 2 \ 2& 1& 11o does not fo**o% standard mat"ematica* ru*es for e3ponentiation: 2& 23ponentiation "as a *o%er precedence t"an ne$ation, so 91^2 incorrect*y ea*uates to 1& 11o +asic ea*uates mu*tip*e e3ponents ,2^3^!. *eft to ri$"t ,,2^3.^!., %"i*e standard mat"ematica* precedence ea*uates ri$"t to *eft& ,2^,3^!..& Listing 34. #emonstrate e.ponentiation. Sub Exa!pleExponent -i! #F # 6 "'Z% 6 " 4 'Z% REM '*'*' 6 Q # 6 # 4 CHRFB>7C 4 "%Z' 6 " 4 %Z' REM % *% 6 @ # 6 # 4 CHRFB>7C 4 "9%Z' 6 " 4 9%Z' REM B9%C * B9%C 6 @ # 6 # 4 CHRFB>7C 4 "'Z%Z' 6 " 4 'Z%Z' REM 'Z%Z' 6 QZ' 6 A? # 6 # 4 CHRFB>7C 4 "?Z7&< 6 " 4 ?Z&< REM ' # 6 # 4 CHRFB>7C 4 "?Z97&< 6 " 4 ?Z9&< REM &< # 6 # 4 CHRFB>7C 4 "9>Z' 6 " 4 9>Z' REM > # 6 # 4 CHRFB>7C 4 "9B>Z'C 6 " 4 9B>Z'C REM 9> 63 M#Box # End Sub Figure 28. Using the e.ponentiation operator. Multiplication 6<8 and "ivision 6=8 Mu*tip*ication and diision "ae t"e same precedence& Listing 35. #emonstrate multiplication and division. Sub Exa!pleMult-i: Print "'*% 6 " 4 '*% REM A Print "?+'&7 6 " 4 ?+'&7 REM ' Print "9%+' 6 " 4 9%+' REM 9>&< Print "?*%+' 6 " 4 ?*%+' REM A End Sub %emainder after division 6MO"8 T"e M1D operator is a*so ca**ed Dremainder after diision&F 0or e3amp*e, A M1D 2 is 1 because A diided by 2 is 2 %it" a remainder of 1& A** operands are rounded to )nte$er a*ues before t"e operation is performed& Listing 36. #efinition of the MO# operator for integer operands . and y. x MO- . 6 x 9 B. * Bx\.CC Listing 37. #emonstrate mod operator. REM x MO- . can al#o be *ritten a# REM CIntBxC 9 BCIntB.C * BCIntBxC\CIntB.CCC REM CInt i# u#ed becau#e t(e nu!ber# !u#t be rounded REM be$ore t(e operation# are per$or!ed& Sub Exa!pleMO- -i! xBC= .BC= #F= iG xBC 6 Arra. B?= ><= A= A&?= A&<= 9><= ><= 9><C .BC 6 Arra. B><= A= %= %= %= Q= 9Q= 9QC "or i 6 ,BoundBxBCC 3o 0BoundBxBCC # 6 # 4 xBiC 4 " MO- " 4 .BiC 4 " 6 " 4 BxBiC MO- .BiCC 4 CHRFB>7C Hext M#Box #= 7= "MO- operator" End Sub 64 Figure 29. Using the MO# operator. TIP T"e operands for M1D are rounded to )nte$er a*ues before t"e diision is done& !nteger division 6>8 Re$u*ar diision e3pects to diide a Doub*e by a Doub*e, and it returns a Doub*e as an ans%er& 0or e3amp*e, M&0 - !&0 is 1&MA& )nte$er diision, on t"e ot"er "and, e3pects to diide t%o )nte$ers, and it returns an )nte$er as an ans%er& 0or e3amp*e, M&2 S !&3 conerts t"e operands to M S ! and t"en returns 1& T"e numeric constant operands used %it" t"e )nte$er diision operator are truncated to )nte$er a*ues, and t"en )nte$er diision is performed& T"e resu*t is a truncated resu*t, not a rounded resu*t& Listin$ 3@ compares t"e difference bet%een )nte$er diision and re$u*ar diision& Listing 38. #emonstrate integer division. Sub Exa!pleInt-i: -i! $ A# -ouble -i! #F $ 6 <&@ # 6 "<+' 6 " 4 <+' REM '&< # 6 # 4 CHRFB>7C 4 "<\' 6 " 4 <\' REM ' # 6 # 4 CHRFB>7C 4 "<+% 6 " 4 <+% REM >&AAAAAAAA2 # 6 # 4 CHRFB>7C 4 "<\% 6 " 4 <\% REM > # 6 # 4 CHRFB>7C 4 "<+? 6 " 4 <+? REM >&'< # 6 # 4 CHRFB>7C 4 "<\? 6 " 4 <\? REM > # 6 # 4 CHRFB>7C 4 "9<+' 6 " 4 9<+' REM 9'&< # 6 # 4 CHRFB>7C 4 "9<\' 6 " 4 9<\' REM 9' # 6 # 4 CHRFB>7C 4 "9<+% 6 " 4 9<+% REM 9>&AAAAAAAA2 # 6 # 4 CHRFB>7C 4 "9<\% 6 " 4 9<\% REM 9> # 6 # 4 CHRFB>7C 4 "9<+? 6 " 4 9<+? REM 9>&'< # 6 # 4 CHRFB>7C 4 "9<\? 6 " 4 9<\? REM 9> # 6 # 4 CHRFB>7C 4 ">2+A 6 " 4 >2+A REM '&Q%%%%%%%%%%%%% # 6 # 4 CHRFB>7C 4 ">2\A 6 " 4 >2\A REM ' # 6 # 4 CHRFB>7C 4 ">2+<&@ 6 " 4 >2+<&@ REM '&QQ>%<<@%''7%%@ # 6 # 4 CHRFB>7C 4 ">2\< 6 " 4 >2\< REM % # 6 # 4 CHRFB>7C 4 ">2\<&@ 6 " 4 >2\<&@ REM % becau#e <&@ *a# truncated to <& # 6 # 4 CHRFB>7C 4 ">2\$ 6 " 4 >2\$ REM ' becau#e $ *a# rounded up to A& # 6 # 4 CHRFB>7C 4 ">2\B>>&@+'C 6 " 4 >2\B>>&@+'C REM % becau#e >>&@+' truncated to <& M#Box # End Sub 65 Figure 30. "nteger division. ;it" inte$er diision, constant numeric operands are truncated to )nte$er a*ues before t"e diision is done& ;"en ariab*es are part of an operand, t"e operandVs resu*t is rounded, ot"er%ise truncated& 2ddition 6784 subtraction 6984 and string concatenation 6? and 78 Addition and subtraction "ae t"e same precedence, %"ic" is "i$"er t"an t"e strin$ concatenation operator& #are must be ta(en %"i*e addin$ numerica* a*ues because t"e p*us operator can a*so si$nify strin$ concatenation& ;"en t"e first operand for t"e p*us operator is a number, and t"e second is a strin$7 t"e strin$ is conerted to a number& ;"en t"e first operand for t"e p*us operator is a strin$, and t"e second is a number7 t"e number is conerted to a strin$& Print >'% W "%" REM >'A BHu!ericC Print ">'%" W % REM >'%% BStrinC T"e strin$ operator tries to conert t"e operands to strin$s if at *east one operand is a strin$& Print >'% 4 "%" REM >'%% BStrinC Print ">'%" 4 % REM >'%% BStrinC Print >'% 4 % REM 0#e at lea#t one #trin or it *ill not *or1K Mi3in$ strin$ manipu*ations and numerica* manipu*ations may *ead to confusin$ resu*ts, especia**y because strin$ concatenation %it" t"e Q operator "as *o%er precedence t"an t"e N operator& Print >'% W "%" 4 ? )>'A? -o addition t(en con:ert to Strin Print >'% 4 "%" W ? )>'%%? -o addition $ir#t but $ir#t operand i# Strin Print >'% 4 % W "?" )>'%2 -o addition $ir#t but $ir#t operand i# Inteer #.0.2. !ogical and bit71ise operators 2ac" *o$ica* operator as(s a simp*e 8uestion and proides a True or 0a*se ans%er& 0or e3amp*e, is it true t"at ,you "ae money. A4D ,you %ant to purc"ase my boo(.> T"ese types of operations are simp*e and are 66 fre8uent*y used in 11o +asic& Less fre8uent*y used, and proided for comp*eteness to (eep t"e computin$ professiona*s "appy, are t"e bit9%ise operators& +it9%ise operators are not difficu*t, but if you donGt understand t"em, it isnGt *i(e*y to affect your usa$e of 11o +asic& A *o$ica* operator is usua**y t"ou$"t to operate on True and 0a*se a*ues& )n 11o +asic, *o$ica* operators a*so perform bit9%ise operations on )nte$er a*ues& T"is means t"at eac" bit of t"e first operand is compared to t"e correspondin$ bit in t"e second operand to form t"e correspondin$ bit in t"e resu*t& 0or e3amp*e, t"e binary operands 01 and 10 use t"e 0 from 01 and t"e 1 from 10 to produce t"e first bit of t"e resu*t& T"e unusua* t"in$ about *o$ica* and bit9%ise binary operators in 11o +asic is t"at t"eir precedence is t"e same& )n ot"er *an$ua$es, A4D typica**y "as $reater precedence t"an 1R& Tab*e 1M i**ustrates t"e *o$ica* and bit9%ise operators supported by 11o& True and 0a*se represent *o$ica* a*ues, and 0 and 1 represent bit a*ues& Table 17. ruth table for logical and bit4wise operators. x y x $%D y x O& y x 'O& y x E(V y x I)P y True True True True 0a*se True True True 0a*se 0a*se True True 0a*se 0a*se 0a*se True 0a*se True True 0a*se True 0a*se 0a*se 0a*se 0a*se 0a*se True True 1100 1010 1000 1110 0110 1001 1011 )nterna**y, t"e *o$ica* operators cast t"eir operands to type Lon$& An une3pected side effect is t"at a f*oatin$9 point operand is conerted to a Lon$, %"ic" mi$"t cause numerica* oerf*o%& T"e conersion from a f*oatin$9point number to a *on$ inte$er number is done by roundin$ t"e a*ue, not by truncatin$& T"e a*ues c"osen for True ,91. and 0a*se ,0. a**o% t"is to %or(, but t"e return type %it" t%o +oo*ean operands is sti** sometimes of type Lon$& Listing 39. Logical operands are of type long integer. Sub ,oicalOperand#Are,on# -i! := b> A# Boolean= b' A# Boolean b> 6 3rue : b' 6 "al#e : 6 Bb> OR b'C Print 3.peHa!eB:C REM ,on becau#e operand# are con:erted to ,on& Print : REM 9> becau#e t(e return t.pe i# ,on& Print Bb' OR "9>"C REM 9> becau#e "9>" i# con:erted to a ,on& End Sub 0or some *o$ica* e3pressions, not a** operands need to be ea*uated& 0or e3amp*e, t"e e3pression ,0a*se A4D True. is (no%n to be 0a*se by *oo(in$ at t"e first operand and t"e operator A4D& T"is is (no%n as Ds"ort9circuit ea*uation&F Sad*y, t"is isnGt aai*ab*e in 11o +asic7 instead, a** operands are ea*uated& TIP 11o +asic does not support s"ort9circuit ea*uation, so ,3 [R 0 A4D y-3 R 3. causes a diision9by9Cero error %"en 3 is Cero& T"e bit9%ise operators are a** i**ustrated t"e same %ay& T%o arrays are fi**ed %it" +oo*ean a*ues and t%o inte$ers are $ien an )nte$er a*ue& xiG 6 >' : .iG 6 >7 67 xBC 6 Arra.B3rue= 3rue= "al#e= "al#eC .BC 6 Arra.B3rue= "al#e= 3rue= "al#eC T"e decima* number 12 is represented in base 2 as 1100, %"ic" corresponds to t"e a*ues in 3,.& T"e decima* number 10 is represented in base 2 as 1010, %"ic" corresponds to t"e a*ue in y,.& T"e operator is t"en app*ied to D3,0. op y,0.F, D3,1. op y,1.F, D3,2. op y,2.F, D3,3. op y,3.F, and D3i op yiF& T"e resu*t is disp*ayed in a messa$e bo3& T"e inte$ers are disp*ayed as base 2 to emp"asiCe t"at a bit9%ise operation is performed& Listin$ !0 demonstrates "o% an inte$er is conerted to a stream of bits& T"is uses many tec"ni8ues t"at are discussed *ater in t"is c"apter& Listing 40. /onvert an integer to binary. Sub 3e#tInto3oBinar. -i! #F -i! nG -i! xG x 6 InputBoxB"Enter an inteer"C I$ x ED 7 3(en n 6 ,oBAb#BxCC + ,oB'C W > I$ Bx E 7C 3(en n 6 n W ? End I$ El#e n 6 > End I$ print "# 6 " 4 Int3oBinar.StrinBx= nC End Sub REM Con:ert an Inteer :alue to a #trin o$ bit# REM x i# t(e inteer to con:ert REM n i# t(e nu!ber o$ bit# to con:ert REM 3(i# *ould be ea#ier i$ I could #(i$t out t(e lo*e#t *(ile REM retainin t(e #in bit o$ t(e nu!ber= but I cannot& REM I e!ulate t(i# b. di:idin b. t*o= but t(i# $ail# $or neati:e REM nu!ber#& 3o a:oid t(i# proble!= i$ t(e nu!ber i# neati:e REM I $lip all o$ t(e bit#= *(ic( !a1e# it a po#iti:e nu!ber and REM t(en I build an in:erted an#*er "unction Int3oBinar.StrinBB.Oal xG= B.Oal nGC A# Strin -i! b7F )Bit 7 Bt(e ri(t !o#t bitC $or po#iti:e nu!ber#& -i! b>F )Bit > $or po#iti:e nu!ber#& I$ Bx D6 7C 3(en )Hot neati:e #o t(e alorit(! *ill *or1& b> 6 ">" : b7 6 "7" )0#e t(e #tandard bit :alue#& El#e )A neati:e nu!ber #o x 6 HO3 x )$lip all o$ t(e bit#& b> 6 "7" : b7 6 ">" )In:ert bit 7 and in:ert bit >& End I$ -i! #F )Accu!ulate bit# a# a #trin in #F& -o W(ile n D 7 )n i# t(e nu!ber o$ bit# to return& I$ Bx AH- >C 6 > 3(en )AH- *it( > to $ind bit 7 Bt(e ri(t !o#t bitC& # 6 b>F 4 # )Bit > #et #o add a > Bi$ x *a# neati:e add 7C& El#e # 6 b7F 4 # )Bit > clear #o add a 7 Bi$ x *a# neati:e add >C& End I$ x 6 x\' )Inteer di:i#ion b. '& 68 n 6 n 9 > )-ecre!ent n b. >= Nu#t $ini#(ed a bit& ,oop )Bac1 to t(e top o$ t(e W(ile& Int3oBinar.Strin 6 # )A##in t(e return :alue to t(e "unction& End "unction 2@" 'erform a *o$ica* A4D operation on +oo*ean a*ues, and a bit9%ise A4D on numerica* a*ues& #onsider t"e p"rase, D6ou can $o to t"e moie if you "ae money A4D if you "ae transportation&F +ot" conditions must be true before you are ab*e to $o to t"e moie& )f bot" operands are True, t"en t"e resu*t is True7 ot"er%ise t"e resu*t is 0a*se& Listing 41. Operator -N#. Sub Exa!pleOpAH- -i! #F= xBC= .BC= iG= xiG= .iG xiG 6 >' : .iG 6 >7 xBC 6 Arra.B3rue= 3rue= "al#e= "al#eC .BC 6 Arra.B3rue= "al#e= 3rue= "al#eC "or i 6 ,BoundBxBCC 3o 0BoundBxBCC # 6 # 4 xBiC 4 " AH- " 4 .BiC 4 " 6 " 4 CBoolBxBiC AH- .BiCC 4 CHRFB>7C Hext # 6 # 4 Int3oBinar.StrinBxi= ?C 4 " AH- " 4 Int3oBinar.StrinB.i= ?C 45 " 6 " 4 Int3oBinar.StrinBxi AH- .i= ?C 4 CHRFB>7C M#Box #= 7= "Operator AH- exa!ple" End Sub Figure 31. Using the -N# operator. O% 'erform a *o$ica* 1R operation on +oo*ean a*ues, and a bit9%ise 1R on numerica* a*ues& #onsider t"e p"rase, D6ou can purc"ase t"at if you "ae cas" 1R your friend "as cas"&F )t does not matter %"o "as cas"& )f eit"er operand is True, t"en t"e resu*t is True7 ot"er%ise t"e resu*t is 0a*se& Listing 42. Operator OR. Sub Exa!pleOpOR -i! #F= xBC= .BC= iG= xiG= .iG xiG 6 >' : .iG 6 >7 xBC 6 Arra.B3rue= 3rue= "al#e= "al#eC .BC 6 Arra.B3rue= "al#e= 3rue= "al#eC "or i 6 ,BoundBxBCC 3o 0BoundBxBCC # 6 # 4 xBiC 4 " OR " 4 .BiC 4 " 6 " 4 CBoolBxBiC OR .BiCC 4 CHRFB>7C Hext # 6 # 4 Int3oBinar.StrinBxi= ?C 4 " OR " 4 Int3oBinar.StrinB.i= ?C 45 " 6 " 4 Int3oBinar.StrinBxi OR .i= ?C 4 CHRFB>7C 69 M#Box #= 7= "Operator OR exa!ple" End Sub Figure 32. Using the OR operator. AO% T"e I1R operator is ca**ed De3c*usie orF7 t"is is a 8uestion of non9e8uia*ence& T"e resu*t is True if t"e operands "ae different a*ues& T"e resu*t is 0a*se if bot" operands "ae t"e same a*ue& A *o$ica* I1R operation is performed on +oo*ean a*ues, and a bit9%ise I1R is performed on numerica* a*ues& Listing 43. Operator :OR. Sub Exa!pleOp/OR -i! #F= xBC= .BC= iG= xiG= .iG xiG 6 >' : .iG 6 >7 xBC 6 Arra.B3rue= 3rue= "al#e= "al#eC .BC 6 Arra.B3rue= "al#e= 3rue= "al#eC "or i 6 ,BoundBxBCC 3o 0BoundBxBCC # 6 # 4 xBiC 4 " /OR " 4 .BiC 4 " 6 " 4 CBoolBxBiC /OR .BiCC 4 CHRFB>7C Hext # 6 # 4 Int3oBinar.StrinBxi= ?C 4 " /OR " 4 Int3oBinar.StrinB.i= ?C 45 " 6 " 4 Int3oBinar.StrinBxi /OR .i= ?C 4 CHRFB>7C M#Box #= 7= "Operator /OR exa!ple" End Sub Figure 33. Using the :OR operator. EB- T"e 2_O operator is a 8uestion of e8uia*ence: Are t"e t%o operands t"e same> A *o$ica* 2_O operation is performed for +oo*ean a*ues, and a bit9%ise 2_O on numbers& )f bot" operands "ae t"e same a*ue, t"e resu*t is True& )f t"e operands donGt "ae t"e same a*ue, t"e resu*t is 0a*se& Listing 44. Operator $;3. Sub Exa!pleOpE[O -i! #F= xBC= .BC= iG= xiG= .iG xiG 6 >' : .iG 6 >7 70 xBC 6 Arra.B3rue= 3rue= "al#e= "al#eC .BC 6 Arra.B3rue= "al#e= 3rue= "al#eC "or i 6 ,BoundBxBCC 3o 0BoundBxBCC # 6 # 4 xBiC 4 " E[O " 4 .BiC 4 " 6 " 4 CBoolBxBiC E[O .BiCC 4 CHRFB>7C Hext # 6 # 4 Int3oBinar.StrinBxi= ?C 4 " E[O " 4 Int3oBinar.StrinB.i= ?C 45 " 6 " 4 Int3oBinar.StrinBxi E[O .i= ?C 4 CHRFB>7C M#Box #= 7= "Operator E[O exa!ple" End Sub Figure 34. Using the $;3 operator. !M3 T"e )M' operator performs a *o$ica* imp*ication& A *o$ica* )M' operation is performed on +oo*ean a*ues, and a bit9%ise )M' on numbers& As t"e name imp*ies, D3 )M' yF as(s if t"e statement t"at D3 imp*ies yF is a true statement& To "e*p understand *o$ica* imp*ication, define 3 and y as fo**o%s: x 6 3(e #1. i# cloud. . 6 3(e #un i# not :i#ible I$ x 3(en . )f bot" 3 and y are true L t"e s(y is c*oudy and t"e sun is not isib*e L t"e statement can be considered true& T"is statement ma(es no c*aim about y if 3 is not true& )n ot"er %ords, if t"e s(y is not c*oudy, t"is statement does not imp*y t"at t"e sun is, or is not, isib*e& 0or e3amp*e, it mi$"t be a c*ear ni$"t, or ,*i(e a $ood computer $ee(. you mi$"t be inside a room %it"out any %indo%s& T"is e3p*ains %"y t"e entire statement is a*%ays considered a*id %"en 3 is fa*se& 0ina**y, if 3 is true and y is not, t"e entire statement is considered fa*se& )f t"e s(y is c*oudy, and t"e sun is isib*e, t"e statement cannot possib*y be correct7 a c*oudy day cou*d not imp*y t"at t"e sun is isib*e& Listing 45. Operator "M9. Sub Exa!pleOpIMP -i! #F= xBC= .BC= iG= xiG= .iG xiG 6 >' : .iG 6 >7 xBC 6 Arra.B3rue= 3rue= "al#e= "al#eC .BC 6 Arra.B3rue= "al#e= 3rue= "al#eC "or i 6 ,BoundBxBCC 3o 0BoundBxBCC # 6 # 4 xBiC 4 " IMP " 4 .BiC 4 " 6 " 4 CBoolBxBiC IMP .BiCC 4 CHRFB>7C Hext # 6 # 4 Int3oBinar.StrinBxi= ?C 4 " IMP " 4 Int3oBinar.StrinB.i= ?C 45 " 6 " 4 Int3oBinar.StrinBxi IMP .i= ?C 4 CHRFB>7C M#Box #= 7= "Operator IMP exa!ple" End Sub 71 Figure 35. Using the "M9 operator. @O0 T"e 41T operator performs a *o$ica* 41T operation on +oo*ean a*ues, and a bit9%ise 41T on numerica* a*ues& T"is means t"at D4ot TrueF is 0a*se and D4ot 0a*seF is True& 0or bit9%ise operations, a 1 becomes a 0 and a 0 becomes a 1& Print HO3 3rue REM 7= *(ic( i# "al#e Print HO3 "al#e REM 9>= *(ic( i# 3rue Print HO3 ' REM 9%= *(ic( too1 t(e bit# 77>7 to >>7> #.0.#. Comparison operators T"e comparison operators %or( %it" numerica*, Date, +oo*ean, and Strin$ data types& Print ' 6 Q+? AH- 7 E >+% AH- ' D > )9>63rue Print ? E6 ?&7 AH- > D6 7 AH- > ED 7 )9>63rue Strin$ comparisons are based on t"eir interna* representations as numbers and are case sensitie& T"e *etter DAF is *ess t"an t"e *etter D+F& T"e uppercase c"aracters are *ess t"an t"e *o%ercase *etters& -i! aF= bF= cF aF 6 "A" : bF 6 "B" : cF 6 "B" Print aF E bF )3rue Print bF 6 cF )3rue Print cF E6 aF )"al#e Stran$e prob*ems occur %"en a** of t"e operands are strin$ constants& )f at *east one operand is a ariab*e, t"e e3pected resu*ts are ac"ieed& T"is is *i(e*y re*ated to "o% t"e operands are reco$niCed and conerted for use& Print "A" E "B" )76"al#e= t(i# i# not correct Print "B" E "A" )9>63rue= t(i# i# not correct Print % 6 "%" )"al#e= but t(i# c(ane# i$ a :ariable i# u#ed ;"en ariab*es are used rat"er t"an strin$ constants, t"e numerica* a*ues are conerted to strin$ types for t"e comparison& -i! aF= iG= tF aF 6 "A" : tF 6 "%" : iG 6 % Print aF E "B" )3rue= Strin co!pare Print "B" E aF )"al#e= Strin co!pare Print iG 6 "%" )3rue= Strin co!pare Print iG 6 "W%" )"al#e= Strin co!pare Print % 6 tF )3rue= Strin co!pare Print iG E "'" )"al#e= Strin co!pare Print iG D "''" )3rue= Strin co!pare 72 TIP ;"en comparin$ operands of different types, especia**y %"en mi3in$ numeric and strin$ types, it is safer to e3p*icit*y perform a type conersion& 2it"er conert t"e strin$ to a number, or t"e number to a strin$& T"e functions to do t"is are discussed *ater& 11o reco$niCes t"e Oisua* +asic statement 1ption #ompare ` +inary a Te3tb, but as of 11o ersion 3&20, t"e statement sti** does not"in$& T"e current be"aior is a binary comparison of strin$s& 3.(. Clow control 0*o% contro* is about decidin$ %"ic" *ine of code runs ne3t& #a**in$ a subroutine or function is a simp*e form of unconditiona* f*o% contro*& More comp*icated f*o% contro* ino*es branc"in$ and *oopin$& 0*o% contro* a**o%s macros to "ae comp*icated be"aior t"at c"an$es based on t"e current data& +ranc"in$ statements cause t"e pro$ram f*o% to c"an$e& #a**in$ a subroutine or function is an unconditiona* branc"& 11o +asic supports conditiona* branc"in$ statements suc" as Dif 3, t"en do yF& Loopin$ statements cause t"e pro$ram to repeat sections of code& Loopin$ statements a**o% for a section to be repeated a specific number of times or unti* a specific De3itF condition "as been ac"ieed& #.2.1. (efine a label as a 4ump target Some f*o% contro* statements, suc" as JoSub, JoTo, and 1n 2rror, re8uire a *abe* to mar( a point in t"e code& Labe* names are sub/ect to t"e same ru*es as ariab*e names& Labe* names are immediate*y fo**o%ed by a co*on& Remember t"at a co*on is a*so used as a statement separator t"at a**o%s mu*tip*e statements to occupy t"e same *ine& Space bet%een t"e *abe* name and t"e co*on causes t"e co*on to be used as a statement separator, %"ic" means t"e *abe* %onGt be defined& T"e fo**o%in$ *ines a** represent a*id 11o +asic code& E#tate!ent#D iG 6 < : 8 6 ; W ?&22 M.Cool,abel: E!ore #tate!ent#D Mu!p3aret: E!ore #tate!ent#D REM no #pace bet*een label and colon TIP )nsertin$ a space bet%een a *abe* and t"e co*on causes t"e co*on to be used as a statement separator, and t"e *abe* is not defined& #.2.2. Goub T"e JoSub statement causes e3ecution to /ump to a defined *abe* in t"e current routine& )t isnGt possib*e to /ump outside of t"e current routine& ;"en t"e Return statement is reac"ed, e3ecution continues from t"e point of t"e ori$ina* ca**& A Return statement %it" no preious JoSub produces a run9time error& )n ot"er %ords, Return is not a substitute for 23it Sub or 23it 0unction& )t is $enera**y assumed t"at functions and subroutines produce more understandab*e code t"an JoSub and JoTo& TIP JoSub is a persistent remnant from o*d +AS)# dia*ects, retained for compatibi*ity& JoSub is stron$*y discoura$ed because it tends to produce unreadab*e code& 5se a subroutine or function instead& )n fact, Oisua* +asic &42T no *on$er supports t"e JoSub (ey%ord& 73 Listing 46. $.ample <o*ub. Sub Exa!pleJoSub -i! i A# Inteer JoSub ,ine' REM Mu!p to line ' t(en return= i i# > JoSub X,ine >Y REM Mu!p to line > t(en return= i i# ' M#Box "i 6 " W i= 7= "JoSub Exa!ple" REM i i# no* ' Exit Sub REM ,ea:e t(e current #ubroutine& X,ine >Y: REM t(i# label (a# a #pace in it i 6 i W > REM Add one to i Return REM return to t(e callin location ,ine': REM t(i# label i# !ore t.pical= no #pace# i 6 > REM Set i to > Return REM return to t(e callin location End Sub #.2.#. GoTo T"e JoTo statement causes e3ecution to /ump to a defined *abe* in t"e current routine& )t isnGt possib*e to /ump outside of t"e current routine& 5n*i(e t"e JoSub statement, t"e JoTo statement doesnGt (no% from %"ere it came& JoTo is a persistent remnant from o*d +AS)# dia*ects, retained for compatibi*ity& JoTo is stron$*y discoura$ed because it tends to produce unreadab*e code& 5se a subroutine or function instead& Listing 47. $.ample <oo. Sub Exa!pleJo3o -i! i A# Inteer Jo3o ,ine' REM O1a.= t(i# loo1# ea#. enou( ,ine>: REM but I a! beco!in con$u#ed i 6 i W > REM I *i#( t(at Jo3o *a# not u#ed Jo3o 3(eEnd REM 3(i# i# cra8.= !a1e# !e t(in1 o$ #pa(etti= ,ine': REM 3anled #trand# oin in and out\ #pa(etti code& i 6 > REM I$ .ou (a:e to do it= .ou probabl. Jo3o ,ine> REM did #o!et(in poorl.& 3(eEnd: REM -o not u#e Jo3o& M#Box "i 6 " W i= 7= "Jo3o Exa!ple" End Sub #.2.$. On GoTo and On Goub T"ese statements cause t"e e3ecution to branc" to a *abe* based on a numeric e3pression 4& )f 4 is Cero, no branc"in$ occurs& T"e numeric e3pression 4 must be in t"e ran$e of 0 t"rou$" 2AA& T"is is sometimes ca**ed a Dcomputed $oto,F because a computation is used to direct t"e pro$ram f*o%& )t isnGt possib*e to /ump outside of t"e current subroutine& Syntax: On H JoSub ,abel>X= ,abel'X= ,abel%X=&&&YYY Syntax: On H Jo3o ,abel>X= ,abel'X= ,abel%X=&&&YYY To reiterate "o% t"is %or(s, if 4 ? 1 t"en branc" to Labe* 1, if 4 ? 2 t"en branc" to Labe* 2&&& )f 4 is *ess t"an 1 or if 4 is $reater t"an t"e number of *abe*s, t"en t"e branc" is not ta(en7 it is simp*y i$nored& Listing 48. $.ample On <oo. Sub Exa!pleOnJo3o -i! i A# Inteer -i! # A# Strin 74 i 6 > On iW> JoSub Sub>= Sub' # 6 # 4 C(rB>%C On i Jo3o ,ine>= ,ine' REM 3(e exit cau#e# u# to exit i$ *e do not continue execution Exit Sub Sub>: # 6 # 4 "In Sub >" : Return Sub': # 6 # 4 "In Sub '" : Return ,ine>: # 6 # 4 "At ,abel >" : Jo3o 3(eEnd ,ine': # 6 # 4 "At ,abel '" 3(eEnd: M#Box #= 7= "On Jo3o Exa!ple" End Sub #.2.,. If Then Else T"e )f construct is used to e3ecute a b*oc( of code based on an e3pression& A*t"ou$" you can use JoTo or JoSub to /ump out of an )f b*oc(, you cannot /ump into an )f b*oc(& T"e simp*est )f statement "as t"e fo**o%in$ form: I$ Condition 3(en State!ent T"e condition can be any e3pression t"at eit"er ea*uates to L or is conertib*e to L True or 0a*se& 5se a s*i$"t*y more comp*icated ersion to contro* more t"an a sin$*e statement& I$ Condition 3(en State!entbloc1 XEl#eI$ Condition 3(enY State!entbloc1 XEl#eY State!entbloc1 End I$ )f t"e first condition ea*uates to True, t"e first b*oc( runs& T"e 2*se)f statement a**o%s mu*tip*e )f statements to be tested in se8uence& T"e statement b*oc( for t"e first true condition runs& T"e 2*se statement b*oc( runs if no ot"er condition ea*uates to True& Listing 49. $.ample "f. Sub Exa!pleI$ -i! iG iG 6 ? I$ i 6 ? 3(en Print "i i# $our" I$ i ED % 3(en Print "i i# not t(ree" End I$ I$ i E > 3(en Print "i i# le## t(an >" el#ei$ i 6 > 3(en Print "i i# >" el#ei$ i 6 ' 3(en 75 Print "i i# '" el#e Print "i i# reater t(an '" End I$ End Sub )f statements can be nested& I$ i ED % 3HEH I$ 1 6 ? 3(en Print "1 i# $our" I$ N 6 2 3(en Print "N i# #e:en" End I$ End I$ #.2... IIf T"e ))f ,D)mmediate )fF. function returns one of t%o a*ues based on a conditiona* e3pression& Syntax: obNect 6 II$ BCondition= 3rueExpre##ion= "al#eExpre##ionC T"is is ery simi*ar to t"e fo**o%in$ code: I$ Condition 3(en obNect 6 3rueExpre##ion El#e obNect 6 "al#eExpre##ion End I$ T"is %or(s as a $reat sin$*e9*ine )f9T"en92*se statement& !ax5ae 6 II$BNo(n#5ae D bill#5ae= No(n#5ae= bill#5aeC #.2./. Choose T"e #"oose statement se*ects from a *ist of a*ues based on an inde3& Syntax: obN 6 C(oo#e Bexpre##ion= Select5>X= Select5'= &&& X=Select5nYYC T"e #"oose statement returns a nu** if t"e e3pression is *ess t"an 1 or $reater t"an t"e number of se*ection ar$uments& #"oose returns Dse*ect=1F if t"e e3pression ea*uates to 1, and Dse*ect=2F if t"e e3pression ea*uates to 2& T"e resu*t is simi*ar to storin$ t"e se*ections in an array %it" a *o%er bound of 1 and t"en inde3in$ into t"e array& Listing 50. - division4by4zero error occurs even though (,6i4=7 should be returned. iG 6 % Print C(oo#e BiG= >+BiW>C= >+Bi9>C= >+Bi9'C= >+Bi9%CC Se*ections can be e3pressions and t"ey can contain function ca**s& 2ery function is ca**ed and eery e3pression is ea*uated in t"e ar$ument *ist for t"e ca** to t"e #"oose statement& T"e code in Listin$ A0 causes a diision9by9Cero error because eery ar$ument is ea*uated, not /ust t"e ar$ument t"at %i** be returned& Listin$ A1 ca**s t"e functions #"oose1, #"oose2, and #"oose3& Listing 51. $.ample /hoose statement. Sub Exa!pleC(oo#e Print C(oo#eB'= "One"= "3*o"= "3(ree"C )3*o Print C(oo#eB'= C(oo#e>BC= C(oo#e'BC= C(oo#e%BCC )3*o 76 End Sub "unction C(oo#e>FBC Print "I a! in C(oo#e>" C(oo#e> 6 "One" End "unction "unction C(oo#e'FBC Print "I a! in C(oo#e'" C(oo#e' 6 "3*o" End "unction "unction C(oo#e%FBC Print "I a! in C(oo#e%" C(oo#e% 6 "3(ree" End "unction TIP A** ar$uments in a #"oose statement are ea*uated& )f functions are used in t"e ar$uments for #"oose, t"ey are a** ca**ed& #.2.0. elect Case T"e Se*ect #ase statement is simi*ar to an )f statement %it" mu*tip*e 2*se )f b*oc(s& A sin$*e9condition e3pression is specified and t"is is compared a$ainst mu*tip*e a*ues for a matc" as fo**o%s: Select Ca#e condition5expre##ion Ca#e ca#e5expre##ion> State!entBloc1> Ca#e ca#e5expre##ion' State!entBloc1' Ca#e El#e State!entBloc1% End Select T"e condition=e3pression is compared in eac" #ase statement& T"e first statement b*oc( to matc" is e3ecuted& T"e optiona* #ase 2*se b*oc( runs if no condition matc"es& )t is not an error if not"in$ matc"es and no #ase 2*se b*oc( is present& Case e:pressions T"e conditiona* e3pression is ea*uated once and t"en it is compared to eac" case e3pression unti* a matc" is found& A case e3pression is usua**y a constant, suc" as D#ase !F or D#ase Z"e**oZF& Select Ca#e ' Ca#e > Print "One" Ca#e % Print "3(ree" End Select 6ou can specify mu*tip*e a*ues by separatin$ t"em %it" commas: DCa#e %= <= 2F& T"e (ey%ord 3o c"ec(s a ran$e of a*ues L for e3amp*e, DCa#e < 3o >7F& 1pen9ended ran$es are c"ec(ed as DCa#e E >7F or as DCa#e IS E >7F& TIP T"e #ase )S statement is different t"an t"e )S operator t"at decides if t%o ob/ects are t"e same& 77 2ery #ase statement %ritten D#ase op e3pressionF is s"ort"and for %ritin$ D#ase )S op e3pressionF& T"e form D#ase e3pressionF is s"ort"and for DCa#e IS 6 expre##ionF& 0or e3amp*e, DCa#e D6 <F is e8uia*ent to DCa#e IS D6 <F, and DCa#e >W%F is e8uia*ent to DCa#e IS 6 >W%F& Select Ca#e i Ca#e >= %= < Print "i i# one= t(ree= or $i:e" Ca#e A 3o >7 Print "i i# a :alue $ro! A t(rou( >7" Ca#e E 9>7 Print "i i# le## t(an 9>7" Ca#e IS D >7 Print "i i# reater t(an >7" Ca#e El#e Print "Ho idea *(at i i#" End Select A #ase statement can contain a *ist of e3pressions separated by commas& 2ac" e3pression can inc*ude an open9ended ran$e& 2ac" e3pression can use t"e statement #ase )S ,see Listin$ A2.& Listing 52. he keyword "* is optional. Select Ca#e iG Ca#e A= I# 6 2= I# 6 Q= I# D ><= I# E 7 Print "" 4 i 4 " !atc(ed" Ca#e El#e Print "" 4 i 4 " i# out o$ rane" End Select !f Case statements are eas'4 wh' are the' freDuentl' incorrectE ) fre8uent*y see incorrect e3amp*es of #ase statements& )tGs instructie to see %"at is repeated*y done incorrect*y& #onsider t"e simp*e e3amp*es in Tab*e 1@& T"e *ast e3amp*es are %ritten correct*y in Tab*e 20& Table 18. /ase statements are fre8uently written incorrectly. Example Valid Description Select Ca#e i Ca#e ' #orrect T"e #ase e3pression 2 is ea*uated as t%o& T%o is compared to i& Select Ca#e i Ca#e I# 6 ' #orrect T"e #ase e3pression 2 is ea*uated as t%o& T%o is compared to i& Select Ca#e i Ca#e I# D 2 #orrect T"e e3pression M is ea*uated as seen& Seen is compared to i& Select Ca#e i Ca#e ?= 2= @ #orrect T"e conditiona* e3pression i is compared indiidua**y to !, M, and B& Select Ca#e x Ca#e >&% 3O <&2 #orrect 6ou can specify a ran$e and use f*oatin$9point numbers& Select Ca#e i Ca#e i 6 ' )ncorrect T"e #ase e3pression ,i?2. is ea*uated as True or 0a*se& True or 0a*se is compared to i& T"is is reduced to D)S ? ,i?2.F& Select Ca#e i Ca#e iE' OR iD@ )ncorrect T"e #ase e3pression ,i[2 1R B[i. is ea*uated as True or 0a*se& True or 0a*se is compared to i& T"is is reduced to D)S ? ,i[2 1R B[i.F& Select Ca#e iG Ca#e iGD' AH- iGE>7 )ncorrect T"e #ase e3pression ,iR2 A4D i [ 10. is ea*uated as True or 0a*se& True or 0a*se is compared to i& T"is is reduced to D)S ? ,iR2 A4D i[10.F& 78 Example Valid Description Select Ca#e iG Ca#e ISDQ And iE>> )ncorrect A$ain, True and 0a*se are compared to i& T"is is reduced to D)S R ,@ A4D i[11.F& T"e precedence ru*es cause t"is to be reduced to D)S R ,@ A4D ,i[11..F& T"is is usua**y not %"atGs intended& Select Ca#e iG Ca#e ISDQ And ISE>> )ncorrect #ompi*e error& T"e (ey%ord )S must immediate*y fo**o% #ase& ) "ae seen 11o e3amp*es %it" incorrect e3amp*es suc" as DCa#e i D ' AH- i E >7F& T"is fai*s& DonGt be*iee it een t"ou$" you see it in print& 5nderstand %"y t"is fai*s and you "ae mastered #ase statements& T"e ne3t to t"e *ast incorrect e3amp*e in Tab*e 1@ demonstrates t"e most common error t"at ) see %it" #ase e3pressions& Listin$ A3 considers t"e case %"en i is *ess t"an 11, and t"e case %"en i is $reater t"an or e8ua* to 11& To put it simp*y, ISDQ AH- iE>> "as t"e #ase statement comparin$ t"e a*ue of i to t"e resu*t of a +oo*ean e3pression, %"ic" can be on*y 0 or 91& T"e bi$ difficu*ty %it" #ase statements is t"at t"ey *oo( *i(e )f statements, %"ic" are *oo(in$ for a True or 0a*se, but #ase statements are *oo(in$ for a particu*ar a*ue a$ainst %"ic" to matc" t"e conditiona*, and 0 or 91 is not "e*pfu*& #onsider t"e second case in Listin$ A3, i D6 >>& T"e operator [ "as "i$"er precedence t"an t"e operator AH-, so it is ea*uated first& T"e e3pression iE>> ea*uates to 0a*se ,because ) assumed t"at iD6>>.& 0a*se is interna**y represented as 0& Pero "as no bits set, so Q AH- 7 ea*uates to Cero& 0or a*ues of i $reater t"an or e8ua* to 11, t"e entire e3pression is e8uia*ent to DIS D 7F& )n ot"er %ords, for i 6 ?<, t"is #ase statement is incorrect*y accepted& A simi*ar ar$ument for a*ues of i *ess t"an 11, *eft as an e3ercise for t"e reader, demonstrates t"at t"e #ase statement is e8uia*ent to DCa#e IS D QF& T"erefore, a*ues of i *ess t"an 11 are correct*y ea*uated, but a*ues of i $reater t"an or e8ua* to 11 are not& Listing 53. >/ase "* ? 0 -N# i @ ((A reduces incorrectly. IS D BQ AH- i E >>C 6D IS D BQ AH- 9>C 6D IS D Q )A##u!e i E >> i# correct& IS D BQ AH- i E >>C 6D IS D BQ AH- 7C 6D IS D 7 )A##u!e i D6 >> i# un*anted& 1riting correct Case e:pressions After you *earn a fe% simp*e e3amp*es, itGs easy to %rite correct #ase e3pressions& Tab*e 1B abstract*y enumerates t"e arieties, and Listin$ AM concrete*y demonstrates t"e arieties& Table 19. *imple /ase varieties. Example Description Ca#e IS operator expre##ion T"is is bot" t"e simp*est case and t"e most difficu*t case& )f t"e e3pression is a constant, it is easy to understand& )f t"e e3pression is more comp*icated, t"e on*y difficu*t part is bui*din$ t"e e3pression& Ca#e expre##ion T"is is a reduction of D#ase )S operator e3pressionF %"en t"e operator c"ec(s for e8ua*ity& Ca#e expre##ion 3O expre##ion #"ec( an inc*usie ran$e& T"is is usua**y done correct*y& Ca#e expre##ion= expre##ion= 2ac" e3pression is compared& T"is is usua**y done correct*y& 79 0or t"e difficu*t cases, it suffices to produce an e3pression t"at ea*uates to t"e #ase condition e3pression if it is correct, and anyt"in$ e*se if it is not& )n ot"er %ords, for Se*ect #ase !, t"e e3pression must ea*uate to ! for t"e statement b*oc( to run& Listing 54. "f . is a *tring value) this will work for any !oolean e.pression. Select Ca#e x Ca#e II"BBoolean expre##ion= x= x4">"C ) A##u!e# t(at x i# a #trin )n Listin$ A!, 3 is returned if t"e +oo*ean e3pression is True& T"e e3pression 3?3 is True, so t"e #ase statement passes& )f t"e +oo*ean e3pression is 0a*se, 3QZ1Z is returned& T"is is not t"e same strin$ as 3, so t"e #ase statement %i** not pass& A simi*ar met"od is used for numerica* a*ues& Listing 55. "f . is a numerical value) this will work for any !oolean e.pression. Select Ca#e x Ca#e II"BBoolean expre##ion= x= xW>C ) A##u!e# t(at x i# nu!eric )n Listin$ AA, 3 is returned if t"e +oo*ean e3pression is True& T"e e3pression 3?3 is True, so t"e #ase statement passes& )f t"e +oo*ean e3pression is 0a*se, 3N1 is returned& 0or numerica* a*ues, 3?3N1 is not True, so t"e #ase statement %i** not pass& T"ere is a possibi*ity of numerica* oerf*o%, but in $enera* t"is %or(s& A bri**iant and more e*e$ant so*ution for numerica* a*ues is proided by +ernard Marce**y, a member of t"e 11o 0renc" trans*ation pro/ect& Ca#e x /OR HO3 BBoolean Expre##ionC T"is assumes t"at t"e +oo*ean e3pression returns True ,91. if it s"ou*d pass and 0a*se ,0. if it s"ou*d not& Listing 56. his code uses :OR and NO in a /ase statement. x /OR HO3B3rueC 6 x /OR HO3B9>C 6 x /OR 7 6 x x /OR HO3B"al#eC 6 x /OR HO3B 7C 6 x /OR 9> ED x After my initia* confusion, ) rea*iCed "o% bri**iant t"is rea**y is& T"ere are no prob*ems %it" oerf*o% and it %or(s for a** )nte$er a*ues of 3& Do not simp*ify t"is to t"e incorrect reduction D3 A4D ,+oo*ean e3pression.F because it fai*s if 3 is 0& Listing 57. *elect /ase e.ample. Sub Exa!pleSelectCa#e -i! iG i 6 IntBB'7 * RndC 9'C )Rnd enerate# a rando! nu!ber bet*een 8ero and one Select Ca#e iG Ca#e 7 Print "" 4 i 4 " i# Vero" Ca#e > 3o < Print "" 4 i 4 " i# a nu!ber $ro! > t(rou( <" Ca#e A= 2= Q Print "" 4 i 4 " i# t(e nu!ber A= 2= or Q" Ca#e II$Bi D Q And i E >>= i= iW>C Print "" 4 i 4 " i# reater t(an Q and le## t(an >>" Ca#e iG /OR HO3BiG D >7 AH- iG E >AC Print "" 4 i 4 " i# reater t(an >7 and le## t(an >A" Ca#e El#e Print "" 4 i 4 " i# out o$ rane 7 to ><" End Select End Sub 80 23amp*eSe*ect#ase in Listin$ AM $enerates a random inte$er from 92 t"rou$" 1@ eac" time it runs& Run t"is repeated*y to see eac" #ase statement used& 2ac" of t"e cases cou*d "ae used t"e ))0 construct& 4o% t"at )Ge e3p*ained t"e different met"ods to dea* %it" ran$es, itGs time to reea*uate t"e incorrect cases in Tab*e 1@& T"e so*utions in Tab*e 20 are not t"e on*y possib*e so*utions, but t"ey use some of t"e so*utions presented& Table 20. "ncorrect e.amples from able (0 B now corrected. Incorrect Correct Description Select Ca#e i Ca#e i 6 ' Select Ca#e i Ca#e ' T"e ariab*e i is compared to 2& Select Ca#e i Ca#e i 6 ' Select Ca#e i Ca#e IS 6 ' T"e ariab*e i is compared to 2& Select Ca#e i Ca#e iE' OR iD@ Select Ca#e i Ca#e II$BiE' OR iD@= i= iW>C T"is %or(s een if i is not an inte$er& Select Ca#e iG Ca#e iGD' AH- iGE>7 Select Ca#e iG Ca#e % 3O @ iX is an inte$er so t"e ran$e is from 3 t"rou$" B& Select Ca#e iG Ca#e ISDQ And iE>> Select Ca#e iG Ca#e i /OR HO3BiDQ AH- iE >>C T"is %or(s because iX is an inte$er& #.2.2. 8hile ... 8end 5se t"e ;"i*e &&&;end statement to repeat a b*oc( of statements %"i*e a condition is true& T"is construct "as *imitations t"at do not e3ist %it" t"e Do ;"i*e &&& Loop construct and offers no particu*ar benefits& T"e ;"i*e &&& ;end statement does not support an 23it statement& 6ou cannot use JoTo to e3it a ;"i*e &&& ;end statement& W(ile Condition State!entBloc1 Wend Oisua* +asic &42T does not support t"e (ey%ord ;end& T"is is anot"er reason to use t"e Do ;"i*e &&& Loop instead& #.2.13. (o ... !oop T"e Loop construct "as different forms and is used to continue e3ecutin$ a b*oc( of code %"i*e, or unti*, a condition is true& T"e most common form c"ec(s t"e condition before t"e *oop starts, and repeated*y e3ecutes a b*oc( of code as *on$ as t"e condition is true& )f t"e initia* condition is fa*se, t"e *oop is neer e3ecuted& -o W(ile condition Bloc1 XExit -oY Bloc1 ,oop A simi*ar, but muc" *ess common form, repeated*y e3ecutes t"e code as *on$ as t"e condition is fa*se& )n ot"er %ords, t"e code is e3ecuted unti* t"e condition becomes true& )f t"e condition ea*uates to true immediate*y, t"e *oop neer runs& -o 0ntil condition Bloc1 81 XExit -oY Bloc1 ,oop 6ou can p*ace t"e c"ec( at t"e end of t"e *oop, in %"ic" case t"e b*oc( of code is e3ecuted at *east once& ;it" t"e fo**o%in$ construct, t"e *oop runs at *east once and t"en repeated*y runs as *on$ as t"e condition is true: -o Bloc1 XExit -oY Bloc1 ,oop W(ile condition To e3ecute t"e *oop at *east once and t"en continue as *on$ as t"e condition is fa*se, use t"e fo**o%in$ construct: -o Bloc1 XExit -oY Bloc1 ,oop 0ntil condition E:it the "o .oop T"e 23it Do statement causes an immediate e3it from t"e *oop& T"e 23it Do statement is a*id on*y %it"in a Do &&& Loop& 'ro$ram e3ecution continues %it" t"e statement t"at fo**o%s t"e innermost Loop statement& T"e subroutine 23amp*eDo in Listin$ A@ demonstrates a Do ;"i*e Loop by searc"in$ an array for a number& Listing 58. #o Loop e.ample. Sub Exa!ple-o -i! aBC= iG= xG aBC 6 Arra.B'= ?= A= Q= >7= >'= >?= >A= >Q= '7= ''= '?= 'A= 'Q= %7C x 6 IntB%' * RndC REM rando! inteer bet*een 7 and %' i 6 ,BoundBaBCC REM i i# t(e lo*er bound o$ t(e arra.& -o W(ile aBiC ED x REM *(ile aBiC i# not e;ual to x i 6 i W > REM Incre!ent i I$ i D 0BoundBaBCC 3(en Exit -o REM I$ i i# too lare= t(en exit ,oop REM ,oop bac1 to t(e -o W(ile I$ i E6 0BoundBaBCC 3(en REM I$ i i# not too lare t(en $ound x M#Box ""ound " 4 x 4 " at location " 4 i= 7= "Exa!ple -o" El#e M#Box "Could not $ind " 4 x 4 " in t(e arra."= 7= "Exa!ple -o" End I$ End Sub 1hich "o .oop should ! useE 11o +asic supports four ariants of t"e Do Loop construct& 2ac" ariant "as a particu*ar purpose and time for use& T"e most common prob*em is t"at t"e *oop runs one time too fe% or one time too many because t"e conditiona* e3pression %as incorrect*y p*aced at t"e %ron$ *ocation& ;"en decidin$ %"ere to p*ace t"e conditiona* e3pression of a Do Loop, as( yourse*f t"is 8uestion: DMust t"e *oop a*%ays run at *east once>F )f t"e ans%er is no, t"e conditiona* e3pression must be at t"e top& T"is %i** preent t"e code in t"e *oop from runnin$ if t"e conditiona* e3pression fai*s& #onsider, for e3amp*e, 82 printin$ a** of t"e e*ements in an array of un(no%n siCe& T"e array mi$"t contain no e*ements at a**, in %"ic" case t"e code in t"e *oop s"ou*dnGt run ,see Tab*e 21.& Table 21. 'hile and Until loops are very similar. (o 8hile (o 9ntil iG 6 ,BoundBaBCC -o W(ile iG E6 0BoundBaBCC Print aBiGC iG 6 iG W > ,oop iG 6 ,BoundBaBCC -o 0ntil iG D 0BoundBaBCC Print aBiGC iG 6 iG W > ,oop )n eac" case in Tab*e 21, if t"e array is empty, t"e *oop neer runs& +efore t"e condition is ea*uated, iX is set to t"e *o%er bound of t"e array& )n eac" case, t"e *oop continues to run %"i*e iX is not *ar$er t"an t"e upper bound& #onsider t"e difference bet%een a ;"i*e *oop and an 5nti* *oop %it" a simp*e e3amp*e& ;"i*e t"e car "as $as, you may drie it& 5nti* t"e car does not "ae $as, you may drie it& T"e primary difference bet%een t"e ;"i*e and t"e 5nti* is t"e %ord 41T& Tendin$ more to%ard 11o +asic, ) can %rite D5nti* 41T ,t"e car "as $as.&F T"e c"oice bet%een ;"i*e and 5nti* is usua**y based on %"ic" one you can %rite %it"out t"e 41T& )f t"e *oop s"ou*d run at *east once, moe t"e conditiona* e3pression to t"e end of t"e Do Loop& #onsider re8uestin$ user input unti* a a*id a*ue "as been entered& T"e most natura* c"oice is to p*ace t"e conditiona* e3pression at t"e end& -i! #F= x A# -ouble -o #F 6 InputBoxB"Enter a nu!ber $ro! > t(rou( <"C x 6 C-blB#FC )Con:ert t(e #trin to a -ouble ,oop 0ntil x D6 > AH- x E6 < T"e *oop must run at *east once so t"at at *east one number is entered& T"e *oop repeats unti* a a*id a*ue is entered& As an e3ercise, consider "o% to %rite t"is as a ;"i*e *oop& #.2.11. +or ... -ext T"e 0or &&& 4e3t statement repeats a b*oc( of statements a specified number of times& "or counter6#tart 3o end XStep #tepOalueY #tate!ent bloc1> XExit "orY #tate!ent bloc1' Hext XcounterY T"e numeric DcounterF is initia**y assi$ned t"e DstartF a*ue& ;"en t"e pro$ram reac"es t"e 4e3t statement, t"e counter is incremented by t"e DstepF a*ue, or incremented by one if a DstepF a*ue is not specified& )f t"e DcounterF is sti** *ess t"an or e8ua* to t"e DendF a*ue, t"e statement b*oc(s run& An e8uia*ent Do ;"i*e Loop fo**o%s: counter 6 #tart -o W(ile counter E6 end #tate!ent bloc1> XExit -oY #tate!ent bloc1' 83 counter 6 counter W #tep ,oop T"e DcounterF is optiona* on t"e D4e3tF statement, and it automatica**y refers to t"e most recent D0orF statement& "or i 6 > 3o ? Step ' Print i ) Print# > t(en % Hext i ) 3(e i in t(i# #tate!ent i# optional& T"e 23it 0or statement *eaes t"e 0or statement immediate*y& T"e most recent 0or statement is e3ited& Listin$ AB demonstrates t"is %it" a sortin$ routine& An array is fi**ed %it" random inte$ers, and t"en sorted usin$ t%o nested *oops& T"is tec"ni8ue is ca**ed a Dmodified bubb*e sort&F 0irst, i1uter is set to t"e *ast number in t"e array& T"e inner *oop, usin$ i)nner, compares eery number to t"e one after it& )f t"e first number is *ar$er t"an t"e second number, t"e t%o numbers are s%apped& T"e second number is t"en compared to t"e t"ird number& After t"e inner *oop is finis"ed, t"e *ar$est number is $uaranteed to be at t"e *ast position in t"e array& 4e3t, i1uter is decremented by 1& T"e inner *oop t"is time i$nores t"e *ast number in t"e array, and compares eery number to t"e one after it& At t"e end of t"e inner *oop, t"e second9"i$"est number is second from t"e end& ;it" eac" iteration, one more number is moed into position& )f no numbers are e3c"an$ed, t"e *ist is sorted& Listing 59. Modified bubble sort. Sub Exa!ple"orHextSort -i! iEntr.B>7C A# Inteer -i! iOuter A# Inteer= iInner A# Inteer= i3e!p A# Inteer -i! bSo!et(inC(aned A# Boolean ) "ill t(e arra. *it( inteer# bet*een 9>7 and >7 "or iOuter 6 ,BoundBiEntr.BCC 3o 0boundBiEntr.BCC iEntr.BiOuterC 6 IntBB'7 * RndC 9>7C Hext iOuter ) iOuter run# $ro! t(e (i(e#t ite! to t(e lo*e#t "or iOuter 6 0BoundBiEntr.BCC 3o ,BoundBiEntr.BCC Step 9> )A##u!e t(at t(e arra. i# alread. #orted and #ee i$ t(i# i# incorrect bSo!et(inC(aned 6 "al#e "or iInner 6 ,BoundBiEntr.BCC 3o iOuter9> I$ iEntr.BiInnerC D iEntr.BiInnerW>C 3(en i3e!p 6 iEntr.BiInnerC iEntr.BiInnerC 6 iEntr.BiInnerW>C iEntr.BiInnerW>C 6 i3e!p bSo!et(inC(aned 6 3rue End I$ Hext iInner )I$ t(e arra. i# alread. #orted t(en #top loopinK I$ Hot bSo!et(inC(aned 3(en Exit "or Hext iOuter -i! #F "or iOuter 6 ,BoundBiEntr.BCC 3o 0boundBiEntr.BCC 84 # 6 # 4 iOuter 4 " : " 4 iEntr.BiOuterC 4 CHRFB>7C Hext iOuter M#Box #= 7= "Sorted Arra." End Sub #.2.12. Exit ub and Exit +unction T"e 23it Sub statement e3its a subroutine, and t"e 23it 0unction statement e3its a function& T"e routine is e3ited immediate*y& T"e macro continues runnin$ at t"e statement fo**o%in$ t"e statement t"at ca**ed t"e current routine& T"ese statements %or( on*y to e3it t"e current*y runnin$ routine, and t"ey are a*id on*y in t"eir respectie types& 0or e3amp*e, you canGt use 23it Sub in a function& 3.1+. Error handling using On Error 2rrors are usua**y p*aced into t"ree Dcate$oriesF L compi*e time, run time, and *o$ic& #ompi*e9time errors are typica**y synta3 errors suc" as missin$ doub*e 8uotation mar(s t"at preent your macro from compi*in$& #ompi*e9time errors are t"e easiest to dea* %it" because t"ey are found immediate*y and t"e )D2 s"o%s you %"ic" *ine caused t"e prob*em& Run9time errors compi*e proper*y but cause an error %"en t"e macro runs& 0or e3amp*e, diidin$ by a ariab*e t"at at some point ea*uates to Cero %i** cause a run9time error& T"e t"ird type, *o$ic errors, are mista(es in t"e business *o$ic of t"e pro$ram: T"ey compi*e and run o(ay, but $enerate t"e %ron$ ans%ers& T"eyGre t"e %orst (ind because you "ae to find t"em yourse*f L t"e computer %onGt "e*p you at a**& T"is section is about run9time errors: "o% to dea* %it" t"em and "o% to correct t"em& An error "and*er is a piece of code t"at runs %"en an error occurs& T"e defau*t error "and*er disp*ays an error messa$e and stops t"e macro& 11o +asic proides a mec"anism to modify t"is be"aior ,see Tab*e 22.& T"e first form, 1n 2rror Resume 4e3t, te**s 11o to i$nore a** errors: 4o matter %"at "appens, (eep runnin$ and pretend eeryt"in$ is fine& T"e second form, 1n 2rror JoTo 0, te**s 11o to stop usin$ t"e current error "and*er& )$norin$ error "and*er scope issues, as e3p*ained *ater, t"in( of 1n 2rror JoTo 0 as restorin$ t"e defau*t met"od of "and*in$ errors: Stop runnin$ and disp*ay an error messa$e& T"e fina* form, 1n 2rror JoTo Labe*4ame, a**o%s you to define code to "and*e errors t"e %ay t"at you %ant& T"is is ca**ed Dsettin$ up an error "and*er&F Table 22. *upported On $rror forms. !orm *sa+e On Error Re#u!e Hext )$nore errors and continue runnin$ at t"e ne3t *ine in t"e macro& On Error Jo3o 7 #ance* t"e current error "and*er& On Error Jo3o ,abelHa!e Transfer contro* to t"e specified *abe*& ;"en an error occurs, t"e code t"at %as runnin$ stops runnin$, and contro* is transferred to t"e current error "and*er& T"e error "and*ers use t"e functions in Tab*e 23 to determine t"e cause and *ocation of t"e error& Oisua* +asic uses an 2rror ob/ect and does not support t"e functions in Tab*e 23& 85 Table 23. $rror4related variables and functions. !nction *se #O2rr #onert an e3pression to an error ob/ect& 2r* )nte$er *ine number of t"e *ast error& 2rr )nte$er error number of t"e *ast error& 2rror 2rror messa$e of t"e *ast error& A** error "and*ers must be dec*ared in a routine and are *oca* to t"e containin$ subroutine or function& ;"en an error occurs, 11o +asic starts %or(in$ bac(%ard t"rou$" t"e ca** stac( unti* it finds an error "and*er& )f it doesnGt find an error "and*er, it uses t"e defau*t "and*er& T"e defau*t "and*er prints an error messa$e and "a*ts t"e pro$ram& T"e error information, suc" as 2r*, indicates t"e *ine number in t"e current routine t"at caused t"e error& 0or e3amp*e, if t"e current routine ca**s t"e function b,. at *ine 3! and an error occurs in b,., t"e error is reported as occurrin$ at *ine 3!& Listin$ 60 contains an e3amp*e of t"is, and 0i$ure 36 s"o%s t"e ca** stac(& Anot"er e3amp*e is s"o%n in Listin$ 6!& Listing 60. Use $rl to get the line number. x 6 x W > )A##u!e t(at t(i# i# line %% Call bBC )Error in bBC or #o!et(in bBC call# Bline %?C Exit Sub ),ea:e t(e #ubroutine ErrorHandler: )Ho ot(er (andler# bet*een (ere and t(e error Print "error at " 4 Erl )Print# line %? Figure 36. 'alk the call stack to find a handler. 6ou cannot catc" errors t"at occur in a DLL& #"ec( t"e return code from t"e ca**ed DLL instead& #.13.1. C5Err 5se #O2rr ,as mentioned in Tab*e 23. to create an 11o specific interna* data type t"at represents an error& ) "ae neer seen t"is done, but it can be usefu* for a ery robust function& #O2rr returns an interna* 11o type t"at s"ou*d be assi$ned to a ariant ariab*e& ;"y> 1& 5se OarType to c"ec( t"e type of t"e returned a*ue& A OarType of 10 means t"at an error ob/ect %as returned ,see Tab*e @A.& 86 2& #O2rr accepts an inte$er, %"ic" represents t"e interna* error code t"at occurred& T"e interna* error ob/ect casts to an inte$er and returns t"at interna* error code& T"e fo**o%in$ e3amp*e demonstrates #O2rr& Listing 61. Using /3$rr Sub CallHotVero -i! xOar A# Oariant -i! xInt A# Inteer -i! i A# Inteer -i! # A# Strin "or i 6 9> 3o > xInt 6 HotVeroBiC xOar 6 HotVeroBiC # 6 # 4 "HotVeroB" 4 i 4 "C 6 X" 4 xInt 4 "Y *(en a##ined to an Inteer" # 6 # 4 CHRFB>7C # 6 # 4 "HotVeroB" 4 i 4 "C 6 X" 4 xOar 4 "Y Oar3.pe6" 4 Oar3.peBxOarC # 6 # 4 CHRFB>7C Hext M#Box # End Sub "unction HotVeroBx A# InteerC I$ x ED 7 3(en HotVero 6 x El#e ) 2 i# an arbitrar. nu!ber !eanin not(in& HotVero 6 COErrB2C End I$ End "unction Figure 37. Return values using /3$rr. #.13.2. Ignore errors 1ith On Error 6esume -ext 2rror "and*in$, in some cases, means i$norin$ errors& T"e 1n 2rror Resume statement te**s 11o +asic t"at if a standard error occurs, it s"ou*d i$nore t"e error and resume runnin$ t"e code at t"e ne3t *ine in t"e macro ,see Listin$ 62.& T"e error information is c*eared, so it isnGt possib*e to c"ec( if an error occurred fo**o%in$ t"e statement& Listing 62. he error is cleared by the Resume Ne.t statement. Pri:ate 8eroG 87 #ub Exa!pleErrorRe#u!eHext On Error Re#u!e Hext Print >+VeroG I$ Err ED 7 3(en Print ErrorF 4 " at line " 4 Erl )Err *a# cleared End Sub #.13.#. Clear an error handler 1ith On Error GoTo 3 5se t"e statement 1n 2rror JoTo 0 to c*ear an insta**ed error "and*er& T"is is usua**y done inside an error "and*er or after t"e code t"at used one& )f an error occurs inside an error "and*er, it isnGt "and*ed and t"e macro stops& Listing 63. he error handler is cleared with the statement On $rror <oo C. Pri:ate 8eroG #ub Exa!pleErrorRe#u!eHext On Error Re#u!e Hext Print >+VeroG On Error Jo3o 7 &&& End Sub Some ersions of Oisua* +asic a*so support 1n 2rror JoTo 91, %"ic" is e8uia*ent to 1n 2rror JoTo 0& #.13.$. pecif" "our o1n error handler 1ith On Error GoTo !abel To specify your o%n error "and*er, use 1n 2rror JoTo Labe*& To define a *abe* in 11o +asic, type some te3t on a *ine by itse*f and fo**o% it %it" a co*on& Line *abe*s are no *on$er re8uired to be uni8ue7 t"ey must be uni8ue on*y %it"in eac" routine& T"is a**o%s for consistency in namin$ error9"and*in$ routines rat"er t"an creatin$ a uni8ue name for eery error "and*er ,see Listin$ 6! and 0i$ure 3@.& ;"en an error occurs, e3ecution is transferred to t"e *abe*& Listing 64. $rror &andling. Pri:ate 8eroG Pri:ate error5#F Sub Exa!pleMu!pErrorHandler On Error Jo3o ExErrorHandler Mu!pError> Mu!pError' Print >+VeroG M#Box error5#= 7= "Mu!p Error Handler" Exit Sub ExErrorHandler: error5# 6 error5# 4 "Error in MainMu!pErrorHandler at line " 4 ErlBC 45 " : " 4 ErrorBC 4 CHRFB>7C Re#u!e Hext End Sub Sub Mu!pError> REM Cau#e# a Nu!p to t(e (andler in Exa!pleMu!pErrorHandler& REM 3(e !ain error (andler indicate# t(at t(e error location i# REM at t(e call to Mu!pError> and not in Mu!pError>& Print >+8eroG error5# 6 error5# 4 "He.= I a! in Mu!pError>" 4 CHRFB>7C End Sub 88 Sub Mu!pError' On Error Jo3o ExErrorHandler Print >+8eroG Exit Sub ExErrorHandler: error5# 6 error5# 4 "Error in Mu!pError' at line " 4 ErlBC 45 " : " 4 ErrorBC 4 CHRFB>7C Re#u!e Hext End Sub Figure 38. he last error handler declared is used. A routine can contain seera* 1n 2rror statements& 2ac" 1n 2rror statement can treat errors different*y& T"e error "and*ers in Listin$ 6! a** used Resume 4e3t to i$nore t"e error and continue e3ecution at t"e *ine fo**o%in$ t"e error& 5sin$ mu*tip*e error "and*ers, it is possib*e to s(ip sections of code %"en an error occurs ,see Listin$ 6A.& TIP T"e 11o ersion 3&20 "e*p sti** incorrect*y states t"at error "and*in$ must occur at t"e start of a routine& Listing 65. *kip sections of code when an error occurs. On Error Jo3o Propertie#-one )Inore an. error# in t(i# #ection& aBC 6 etPropertie#BC )I$ unable to et propertie# t(en -i#pla.Stu$$BaBC= "Propertie#"C )an error *ill pre:ent ettin (ere& Propertie#-one: On Error Jo3o Met(od#-one )Inore an. error# in t(i# #ection& aBC 6 etMet(od#BC -i#pla.Stu$$BaBC= "Met(od#"C Met(od#-one: On Error Joto 7 )3urn o$$ current error (andler#& ;"en you %rite an error "and*er, you must decide "o% to "and*e errors& T"e functions in Tab*e 23 are used to dia$nose errors and to disp*ay or *o$ error messa$es& T"ere is a*so t"e 8uestion of f*o% contro*& Eere are some error9"and*in$ $uide*ines: Exit the subroutine or function using Exit Sub or Exit Function. Let the macro continue to run and ignore the error (see Listing 65). Use Resume Next to continue running the macro at the line following the error (see Listing 66 and Figure 39). Use Resume to run the same statement again. If the problem is not fixed, the error will occur again. This will cause an infinite loop. Use Resume LabelName to continue running at some specified location. 89 Listing 66. Resume ne.t error handler. Sub Exa!pleRe#u!eHandler -i! #F= 8G On Error Jo3o Handler> )Add a !e##ae= t(en re#u!e to Spot> # 6 "B7C >+8 6 " 4 >+8 4 CHRFB>7C )-i:ide b. 8ero= #o Nu!p to Handler> Spot>: )Jot (ere $ro! Handler> On Error Jo3o Handler' )Handler' u#e# re#u!e # 6 # 4 "B>C >+8 6 "4>+8 4 CHRFB>7C )"ail t(e $ir#t ti!e= *or1 t(e #econd On Error Jo3o Handler% )Handler% re#u!e# t(e next line 8 6 7 )Allo* $or di:i#ion b. 8ero aain # 6 # 4 "B'C >+8 6 "4>+8 4 CHRFB>7C )"ail and call Handler% M#Box #= 7= "Re#u!e Handler" Exit Sub Handler>: # 6 # 4 "Handler> called $ro! line " 4 ErlBC 4 CHRFB>7C Re#u!e Spot> Handler': # 6 # 4 "Handler' called $ro! line " 4 ErlBC 4 CHRFB>7C 8 6 > )"ix t(e error t(en do t(e line aain Re#u!e Handler%: # 6 # 4 "Handler% called $ro! line " 4 ErlBC 4 CHRFB>7C Re#u!e Hext End Sub Figure 39. he last error handler declared is used. TIP 2rrors t"at occur in an error "and*er are not "and*ed7 t"e macro /ust stops runnin$& #.13.,. Error handlers 1h" use them: ;"en ) run a macro and it cras"es, ) usua**y understand t"e sometimes cryptic error messa$es and reco$niCe "o% to dea* %it" t"em& ;"en ot"ers run my macros and an error occurs, ) usua**y "ear about it because t"ey donGt (no% "o% to "and*e it& T"is is a $ood indicator t"at ) "ae not used proper error "and*in$& 6ou do not "ae to %rite an error "and*er for eac" routine& )f t"e current routine doesnGt "ae an error "and*er, but t"e routine t"at ca**ed it does, t"e ca**erGs error "and*er is ca**ed& 0or e3amp*e, ima$ine t"at sub1 "as an error "and*er and it ca**s sub2 t"at does not& )f an error occurs in sub2, t"e error "and*er in sub1 is ca**ed& ;"en you use an error "and*er, you contro* "o% and %"en a user is notified of an error& 2rror "and*ers "ae uses ot"er t"an contro**in$ %"en a user is informed of an error& A proper*y used error "and*er can reduce t"e 90 siCe of your macro& #onsider, for e3amp*e, t"e mat"ematica* operations& )t is cumbersome to c"ec( eery mat"ematica* operation before it is used& I$ x ED 7 3(en . 6 8 + x I$ x D 7 3(en . 6 ,oBxC I$ iG E %'2A2 3(en iG 6 iG W > 2en %it" my paranoid code c"ec(in$ t"e ar$uments, ) mi$"t sti** "ae a numeric oerf*o%& 2en %orse, not"in$ is done if an error occurs, and processin$ continues as norma*& Sometimes you canGt c"ec( anyt"in$ to aoid t"e error& 0or e3amp*e, prior to 11o ersion 2&0, t"e DimArray function returned an ina*id empty array& T"e L+ound and 5+ound functions $enerate e3ceptions %it" t"ese ina*id empty arrays& 2rror "and*in$ %as used to safe*y $enerate t"e L+ound and 5+ound een if an error occured& #onsider t"e fo**o%in$ cases: The argument is not an array. In an empty array, UBound < LBound; -1 and 0, for example. There are no problems if the array is not an invalid empty array. Should the optional dimension be considered? T"e code in Listin$ 6M demonstrates a simp*e error "and*er t"at is ab*e to simp*y i$nore errors& T"e function returns True if t"e *o%er bound is *ess t"an or e8ua* to t"e upper bound L in ot"er %ords, if t"e array contains data& )f an error occurs, eit"er because t"e ar$ument is not an array or because t"is is an ina*id empty array, t"e *ine does not finis" runnin$ so t"e assi$nment neer ta(es p*ace& )f t"e assi$nment neer ta(es p*ace, t"e ori$ina* defau*t +oo*ean a*ue of 0a*se is used& T"is is t"e correct ans%er& ;ritin$ a safe upper9bound or *o%er9bound routine is *eft as an e3ercise for t"e reader L t"e safe ersions are not re8uired %it" t"e fi3ed 5+ound and L+ound functions re*eased %it" 11o 2&0& Listing 67. #etermine if an array has stuff. Sub Exa!pleArra.Ha#Stu$$ -i! aBC= bB%C= : Print Arra.Ha#Stu$$BaBCC )"al#e= becau#e e!pt. Print Arra.Ha#Stu$$B:C )"al#e= not an arra.= #o u#e error (andler Print Arra.Ha#Stu$$B-i!Arra.BCC )"al#e= bad arra.= #o error (andler called Print Arra.Ha#Stu$$B-i!Arra.B%CC)3rue= t(i# i# not e!pt. Print Arra.Ha#Stu$$BbBCC )3rue= t(i# i# not e!pt. End Sub "unction Arra.Ha#Stu$$B:C A# Boolean REM de$ault :alue $or a Boolean i# "al#e= #o t(e de$ault an#*er i# "al#e REM I$ an error occur#= t(en t(e #tate!ent ne:er co!plete#K REM 3(i# i# a ood ti!e to u#e On Error Re#u!e Hext On Error Re#u!e Hext Arra.Ha#Stu$$ 6 CBoolB,BoundB:C E6 0BoundB:CC End "unction An error "and*er can een be interactie& T"e code in Listin$ 6@ attempts to copy a fi*e t"at doesnGt e3ist to a *ocation t"at doesnGt e3ist& 4eed*ess to say, an error is $enerated& An error messa$e is disp*ayed and t"e user is as(ed if t"e copy s"ou*d be tried a$ain& T"e user is $ien an opportunity to correct any errors and continue& 91 Listing 68. /opy a file. Sub Exa!pleCop.A"ileBC Cop.A"ileB"+I+do+not+exi#t&txt"= "+neit(er+do+I&txt"C End Sub Sub Cop.A"ileBSrcF= -e#tFC On Error Jo3o BadCop.: )Set up t(e error (andler 3r.Aain: "ileCop.BSrcF= -e#tFC )Jenerate t(e error
All-one: )I$ no error= t(en continue (ere Exit Sub )Re#u!e to t(e All-one label $ro! t(e (andler
BadCop.: )-i#pla. an error dialo -i! rcG )A#1 i$ #(ould tr. aain rcG 6 M#BoxB""ailed to cop. $ro! " 4 SrcF 4 " to " 4 -e#tF 4 " becau#e: "45 CHRFB>7C 4 ErrorBC 4 " at line " 4 Erl 4 CHRFB>7C 45 "3r. aainU"= B? OR %'C= "Error Cop.in"C I$ rcG 6 A 3(en )Pe#= tr. t(e co!!and aain Re#u!e End I$ I$ rcG 6 2 3(en )Ho Re#u!e All-one )Jo to t(e All-one label End I$ End Sub 3.11. Conclusion +ui*din$ any si$nificant 11o macro re8uires understandin$ t"e synta3 of 11o +asic& T"is c"apter coered t"e (ey e*ements: The syntax of a macro determines valid and invalid constructs. The logic of a macro determines what the macro does. Flow control directs the macro as it runs. Error handling directs the macro when it does something unexpected. A comp*ete, %e**9constructed macro t"at accomp*is"es any si$nificant function %i** most *i(e*y use a** of t"ese c"aracteristics of 11o pro$rammin$& T"e specific e*ements %it"in 11o t"at one uses to bui*d a specific pro$ram depend on t"e app*ication, t"e desired *o$ica* be"aior of t"e pro$ram, and t"e best /ud$ment of t"e pro$rammer& 1ne ma/or part of successfu* pro$rammin$ is dee*opin$ t"e e3perience to app*y t"e ideas of t"is c"apter in t"e most effectie %ay& 92 $. -umerical 6outines T"is c"apter introduces t"e subroutines and functions supported by 1pen1ffice&or$ +asic t"at are re*ated to numbers L inc*udin$ mat"ematica* functions, conersion routines, formattin$ numbers as a strin$, and random numbers& T"is c"apter a*so discusses a*ternate number bases& 4umerica* subroutines and functions are routines t"at perform mat"ematica* operations& )f you use spreads"eets, you may a*ready be fami*iar %it" mat"ematica* functions suc" as Sum, %"ic" adds $roups of numbers to$et"er, or een )RR, %"ic" ca*cu*ates t"e interna* rate of return of an inestment& T"e numerica* routines supported by 11o +asic ,see Tab*e 2!. are simp*er in nature, typica**y operatin$ on on*y one or t%o ar$uments rat"er t"an an entire $roup of numbers& Table 24. *ubroutines and functions related to numbers and numerical operations. !nction Description A+S,number. T"e abso*ute a*ue of a specified number& AT4,number. T"e an$*e, in radians, %"ose tan$ent is t"e specified number in t"e ran$e of 9'i-2 t"rou$" 'i-2& #+yte,e3pression. Round t"e Strin$ or numeric e3pression to a +yte& ##ur,e3pression. #onert t"e e3pression to a #urrency type& #Db*,e3pression. #onert a Strin$ or numeric e3pression to a Doub*e& #Dec,e3pression. Jenerate a Decima* type7 imp*emented on*y on ;indo%s& #)nt,e3pression. Round t"e Strin$ or numeric e3pression to t"e nearest )nte$er& #Ln$,e3pression. Round t"e Strin$ or numeric e3pression to t"e nearest Lon$& #1S,number. T"e cosine of t"e specified an$*e& #Sn$,e3pression. #onert a Strin$ or numeric e3pression to a Sin$*e& 23p,number. T"e base of natura* *o$arit"ms raised to a po%er& 0i3,number. #"op off t"e decima* portion& 0ormat,ob/, format. 0ancy formattin$, discussed in #"apter 6, DStrin$ Routines&F Ee3,n. Return t"e "e3adecima* representation of a number as a Strin$& )nt,number. Round t"e number to%ard ne$atie infinity& Lo$,number. T"e *o$arit"m of a number& )n Oisua* +asic &42T t"is met"od can be oer*oaded to return eit"er t"e natura* ,base e. *o$arit"m or t"e *o$arit"m of a specified base& 1ct,number. Return t"e octa* representation of a number as a Strin$& RandomiCe,num. )nitia*iCe t"e random number $enerator& )f num is ommitted, uses t"e system timer& Rnd Return a random number as a Doub*e from 0 t"rou$" 1& S$n,number. )nte$er a*ue indicatin$ t"e si$n of a number& S)4,number. T"e sine of an an$*e& S8r,number. T"e s8uare root of a number& Str,number. #onert a number to a Strin$ %it" no *oca*iCation& TA4,number. T"e tan$ent of an an$*e& Oa*,str. #onert a Strin$ to a Doub*e& T"is is ery to*erant to non9numeric te3t& 93 T"e mat"ematica* functions presented in t"is c"apter are %e**9(no%n and understood by mat"ematicians, en$ineers, and ot"ers %"o *oo( for e3cuses to use ca*cu*us in eeryday *ife& )f t"at is not you L if, per"aps, you do not consider t"e s*ide ru*e to be t"e coo*est t"in$ since s*iced bread L donGt panic %"en t"e coera$e starts to become mat"ematica* in nature& ) "ae tried to ma(e t"e information accessib*e %"i*e sti** proidin$ t"e in9dept" information for t"ose %"o re8uire it& T"e routines are topica**y $rouped into sections so you can s(ip sections t"at you (no% t"at you %onGt use& T"e numerica* routines perform operations on numerica* data& 11o +asic tries to conert ar$uments to an appropriate type before performin$ an operation& )t is safer to e3p*icit*y conert data types usin$ conersion functions, as presented in t"is c"apter, t"an to re*y on t"e defau*t be"aior& ;"en an )nte$er ar$ument is re8uired and a f*oatin$9point number is proided, t"e defau*t be"aior is to round t"e number& 0or e3amp*e, D16&@ M1D MF rounds 16&@ to 1M before performin$ t"e operation& T"e )nte$er diision operator, "o%eer, truncates t"e operands& 0or e3amp*e, D'rint ! S 0&BBBF truncates 0&BBB to 0, causin$ a diision9by9Cero error& TIP Tab*e 2! contains subroutines and functions, not operators suc" as M1D, N, and S& 1perators %ere coered in #"apter 3, Lan$ua$e #onstructs& 4.1. 0rigonometric functions Tri$onometry is t"e study of t"e properties of trian$*es and tri$onometric functions and of t"eir app*ications& Discussions of tri$onometric functions usua**y refer to ri$"t trian$*es, %"ic" "ae one an$*e of B0 de$rees ,see 0i$ure !0.& T"ere is a set of defined re*ations"ips amon$ t"e tri$onometric functions, t"e *en$t"s of t"e sides of a ri$"t trian$*e, and t"e correspondin$ an$*es in t"e trian$*e& ;"en you (no% t"ese re*ations"ips, you can use t"e tri$onometric functions to so*e tri$onometric prob*ems& A practica* prob*em t"at uses tri$onometry is to estimate oneGs distance from a po*e or to%er of (no%n "ei$"t& +y measurin$ t"e obsered an$*e from t"e $round to t"e top of t"e po*e, and (no%in$ t"e "ei$"t of t"e po*e, your distance from t"at po*e is t"e "ei$"t of t"e po*e diided by t"e tan$ent of t"e measured an$*e& T"is princip*e can be app*ied to $o*f, sai*in$, or "i(in$, to estimate distance from a fi3ed point of interest ,t"e $o*f f*a$, for e3amp*e, or a radio transmission to%er.& T"e principa* tri$onometric functions are sine, cosine, and tan$ent& 2ac" is defined as t"e ratio bet%een t%o sides of a ri$"t trian$*e& T"e a*ues of t"ese functions for any a*ue of t"e an$*e, 3, correspond to t"e ratios of t"e *en$t"s of t"e sides of t"e ri$"t trian$*e containin$ t"at an$*e, 3& 0or a $ien an$*e, t"e tri$onometric functions fi3 t"e *en$t"s of t"e sides of t"e ri$"t trian$*e& Li(e%ise, (no%in$ t"e *en$t"s of any t%o sides of t"e ri$"t trian$*e a**o%s one to compute t"e a*ue of t"e an$*e usin$ one of t"e inerse tri$onometric functions& 11o +asic uses radians as t"e unit of measure for an$*es7 "o%eer, most non9scientists t"in( in de$rees& An an$*e t"at is B0 de$rees, suc" as t"e corner of a s8uare, is 'i-2 radians& TIP T"e bui*t9in constant 'i is appro3imate*y 3&1!1AB26A3A@BMB323@A& 'i is a fundamenta* constant %ide*y used in scientific ca*cu*ations, and is defined as t"e ratio of t"e circumference of a circ*e to its diameter& T"e sum of t"e an$*es in any trian$*e L inc*udin$ a ri$"t trian$*e L is 1@0 de$rees, or 'i radians& A tremendous amount of e*e$ant and practica* mat"ematica* met"ods resu*t from t"is connection bet%een a trian$*e and a circ*e& A** descriptions of periodic motion bui*d on t"is foundation, ma(in$ tri$onometry a fundamenta* and ery usefu* set of mat"ematica* too*s& 5sin$ t"e re*ations"ip bet%een de$rees and radians, it is easy to conert bet%een radians and de$ree measurements of an$*es& 94 deree# 6 Bradian# * >Q7C + Pi radian# 6 Bderee# * PiC + >Q7 To ca*cu*ate t"e sine of a !A9de$ree an$*e, you must first conert t"e an$*e from de$rees to radians& EereGs t"e conersion: radian# 6 B?<] * PiC + >Q7 6 Pi + ? 6 %&>?><@'A<? + ? 6 7&2Q<%@Q>A%%@Q 6ou can use t"is a*ue direct*y in t"e tri$onometric function S)4& Print SIHB7&2Q<%@Q>A%%@QC ) &272>7A2Q>>QQ To determine t"e an$*e %"ose tan$ent is 0&AMM3A026B1@B, use t"e arctan$ent function& T"e returned a*ue is in radians, so t"is a*ue must be conerted bac( to de$rees& Print A3HB7&<22%<7'A@>Q@C * >Q7 + Pi )'@&@@@@@@@@@@2%> TIP Roundin$ errors, as discussed *ater, affect t"ese e3amp*es& ;it" infinite precision, t"e preious e3amp*e %ou*d resu*t in an ans%er of 30 de$rees rat"er t"an 2B&BBBBBBBBBBM31& T"e ans%er is rou$"*y 30 de$rees& T"e trian$*e in 0i$ure !0 is used to "e*p e3p*ain t"e tri$onometric functions& Figure 40. - right triangle has one angle at 1C degrees. Table 25. rigonometric functions supported by OOo !asic. OOo Basic VB VB ,%ET &etrn Vale AT4 AT4 Mat"&Atan T"e an$*e, in radians, %"ose tan$ent is t"e specified number in t"e ran$e of 9'i-2 t"rou$" 'i-2& #1S #1S Mat"&#os T"e cosine of t"e specified an$*e& S)4 S)4 Mat"&Sin T"e sine of an an$*e& TA4 TA4 Mat"&Tan T"e tan$ent of an an$*e& T"e tri$onometric functions supported by 11o +asic are s"o%n in Tab*e 2A and i**ustrated usin$ t"e ri$"t trian$*e in 0i$ure !0& T"e sin$*e ar$ument e3pression is conerted to a doub*e9precision number before t"e function is performed& 95 COS(x) = Adjacent Leg / Hypotenuse SIN(x) = Opposite Leg / Hypotenuse TAN(x) = Opposite Leg / Adjacent Leg = SIN(x) / COS(x) ATN(Opposite Leg / Adjacent Leg) = x T"e code in Listin$ 6B so*es a series of $eometry prob*ems usin$ t"e tri$onometric functions& T"e code assumes a ri$"t trian$*e, as s"o%n in 0i$ure !0, %it" an opposite *e$ of *en$t" 3, and an ad/acent *e$ of *en$t" !& T"e tan$ent is easi*y ca*cu*ated as 3-! and t"e AT4 function is used to determine t"e an$*e& A fe% ot"er ca*cu*ations are performed, suc" as determinin$ t"e *en$t" of t"e "ypotenuse usin$ bot" t"e S)4 and t"e #1S functions& A*so see 0i$ure !1& Listing 69. $.amplerigonometric Sub Exa!ple3riono!etric -i! Oppo#ite,e A# -ouble -i! AdNacent,e A# -ouble -i! H.potenu#e A# -ouble -i! AnleInRadian# A# -ouble -i! AnleIn-eree# A# -ouble -i! # A# Strin Oppo#ite,e 6 % AdNacent,e 6 ? AnleInRadian# 6 A3HB%+?C AnleIn-eree# 6 AnleInRadian# * >Q7 + Pi # 6 "Oppo#ite ,e 6 " 4 Oppo#ite,e 4 CHRFB>7C 45 "AdNacent ,e 6 " 4 AdNacent,e 4 CHRFB>7C 45 "Anle in deree# $ro! A3H 6 " 4 AnleIn-eree# 4 CHRFB>7C 45 "H.potenu#e $ro! COS 6 " 4 AdNacent,e+COSBAnleInRadian#C 4 CHRFB>7C 45 "H.potenu#e $ro! SIH 6 " 4 Oppo#ite,e+SIHBAnleInRadian#C 4 CHRFB>7C 45 "Oppo#ite ,e $ro! 3AH 6 " 4 AdNacent,e * 3AHBAnleInRadian#C M#Box #= 7= "3riono!etric "unction#" End Sub Figure 41. Use the trigonometric functions to solve problems with triangles. 4.2. %ounding errors and precision 4umerica* ca*cu*ations performed on eit"er a computer or ca*cu*ator are performed %it" on*y a finite number of di$its7 t"is introduces roundin$ errors& T"is isnGt a prob*em %it" inte$er numbers& T"e number 1-3 is represented in decima* form as 0&33333333, but t"ere needs to be an infinite number of t"rees fo**o%in$ t"e decima* point& ;it" four di$its of precision, t"is is %ritten as 0&3333& T"is introduces inaccuracies in t"e representation and t"e resu*tin$ ca*cu*ations& 96 >+% W >+% W >+% 6 %+% 6 > )3(e exact an#*er i# > 7&%%%% W 7&%%%% W 7&%%%% 6 7&@@@@ )3(e $inite preci#ion an#*er= o$$ a bit T"e simp*e macro in Listin$ M0 demonstrates t"is prob*em& T"e a*ue 0&2 is repeated*y added to t"e ariab*e num unti* t"e a*ue is e8ua* to A& )f infinite precision %ere used, or if t"e number 0&2 %ere e3act*y represented inside t"e computer, t"e *oop %ou*d stop %it" t"e ariab*e num containin$ t"e a*ue A& T"e ariab*e neer precise*y e8ua*s t"e a*ue A, "o%eer, so t"e *oop neer stops& T"e a*ue A is printed, but t"is is on*y because t"e 'rint statement rounds !&BBBBBBB to t"e a*ue A %"en it prints t"e number& Listing 70. Rounding errors and finite precision prevent this from stopping. -i! nu! A# Sinle -o nu! 6 nu! W 7&' I$ nu! D ?&< 3(en Print nu! )print# ?&A= ?&Q= <= <&>@@@@@&&& ,oop 0ntil nu! 6 <&7 Print nu! #omputers use comp*e3 roundin$ a*$orit"ms in an attempt to reduce t"e impact of finite precision L finite precision means t"at a finite number of di$its and stora$e are used to represent a number& A*t"ou$" t"is "e*ps, Listin$ M0 c*ear*y demonstrates t"at t"e interna* comp*e3 roundin$ a*$orit"ms do not so*e t"e prob*em& ;"en you compare t%o f*oatin$9point numbers to see if t"ey are e8ua*, it is safer to compare t"em to a ran$e of a*ues& T"e code in Listin$ M1 stops %"en t"e ariab*e is $reater t"an or e8ua* to A& Listing 71. -void rounding errors by using ?D 6greater than or e8ual to7. -i! nu! A# Sinle -o nu! 6 nu! W 7&' ,oop 0ntil nu! D6 <&7 Print nu! )<&>@@@@@ T"e code in Listin$ M1 %or(s to some e3tent, but you probab*y %ant t"e *oop to e3it %"en t"e ariab*e num is !&BBBBBBB rat"er t"an %"en it is A&1BBBBB& 6ou can do t"is by c"ec(in$ to see if t%o numbers are c*ose rat"er t"an e8ua*& T"e bi$ 8uestion is, Eo% c*ose must t%o numbers be before t"ey are considered e8ua*> 6ou can usua**y ma(e a simp*e $uess based on %"at you (no% about t"e prob*em& Sin$*e9precision ariab*es can represent about ei$"t di$its of precision& Doub*e9precision ariab*es can represent about 16 di$its of precision& DonGt try to demand more precision from t"e ariab*es t"an t"ey support& T"e code in Listin$ M1 uses sin$*e9precision ariab*es so you can e3pect rou$"*y seen di$its of precision& T"e code in Listin$ M2 prints t"e difference bet%een A and num B notice t"at about si3 di$its are correct& Listing 72. /ompare the variable to a range. -i! nu! A# Sinle -o nu! 6 nu! W 7&' ,oop 0ntil ?&@@@@@ E nu! AH- nu! E <&7777> Print < 9 nu! )?&2AQ%2><Q'7%>'<E972 6 7&777777?2AQ%2><Q'7%>'< T"e A+S function returns t"e abso*ute a*ue of a number& 6ou can use it to simp*ify t"e process of c"ec(in$ to see "o% c*ose one number is to anot"er& I$ ABSBnu! 9 <C E 7&7777> 3(en 5sin$ A+S and subtraction indicates "o% c*ose t%o numbers are to eac" ot"er, but it may not be sufficient& 0or e3amp*e, *i$"t trae*s at about 2BB,MB2,!A@ meters eac" second& T"is number contains nine di$its& A sin$*e9precision number is accurate to about seen di$its& See Listin$ M3& 97 Listing 73. *ingle4precision variables have only seven or eight digits of accuracy. -i! c> A# Sinle )Scienti#t# u#uall. u#e t(e letter c to repre#ent -i! c' A# Sinle )t(e #peed o$ li(t& c> 6 '@@2@'?<Q )Speed o$ li(t in !eter# per #econd to nine diit# c' 6 c> W >A )Add >A to t(e #peed o$ li(t I$ c> 6 c' 3(en )3(e#e are e;ual becau#e onl. t(e $ir#t #e:en Print "E;ual" )or ei(t diit# are #ini$icant End I$ T"e code in Listin$ M3 adds 16 to t"e speed of *i$"t, but t"is does not c"an$e t"e a*ue& T"is is because on*y t"e first seen or ei$"t di$its are si$nificant& T"e code in Listin$ M! uses a number t"at is sma**er in ma$nitude but uses t"e same number of di$its& Addin$ 1 to t"e number %ou*d c"an$e a si$nificant di$it, but addin$ a sma**er number sti** *eaes t"e numbers e8ua*& Listing 74. *ingle4precision variables have only seven or eight digits of accuracy. -i! c> A# Sinle )Scienti#t# u#uall. u#e t(e letter c to repre#ent -i! c' A# Sinle )t(e #peed o$ li(t& c> 6 '@@&2@'?<Q )3(i# i# nine diit# but it i# not t(e #peed o$ li(t c' 6 c> W &77777>A )Mu#t add a #!aller nu!ber $or t(e! to #till be e;ual I$ c> 6 c' 3(en )3(e#e are e;ual becau#e onl. t(e $ir#t #e:en Print "E;ual" )or ei(t diit# are #ini$icant End I$ 0*oatin$9point numbers can "ae different ma$nitudes L ma$nitude refers to t"e siCe of t"e number L and it doesnGt si$nificant*y affect t"e number of di$its t"at are re*eant& To c"ec( if t%o numbers are about t"e same a*ue, *ar$e numbers can differ by a $reater amount t"an sma** numbers& T"e $reatest a**o%ed difference is dependent upon t"e ma$nitude ,siCe. of t"e numbers7 a mat"ematician ca**s t"is t"e Dre*atie error&F See Listin$ MA& Listing 75. /ompare two numbers. REM 3(i# u#e# n> a# t(e pri!ar. nu!ber o$ intere#t REM n' i# co!pared to n> in a relati:e *a. REM rel5di$$ i# t(e de#ired relati:e di$$erence REM rel5di$$ i# a##u!ed non9neati:e "unction AreSa!eHu!berBn>= n'= rel5di$$C A# Boolean AreSa!eHu!ber 6 "al#e )A##u!e t(at t(e. are di$$erent I$ n> ED 7 3(en )Cannot di:ide b. n> i$ it i# 8ero I$ ABSBBn>9n'C+n>C E6 rel5di$$ 3(en )-i:ide di$$erence b. n> $or relati:e AreSa!eHu!ber 6 3rue )co!pari#on& End I$ )I$ n>= t(e nu!ber o$ intere#t= i# El#eI$ ABSBn'C E6 rel5di$$ 3(en )8ero= t(en co!pare n' $or #i8e& AreSa!eHu!ber 6 3rue End I$ End "unction T"e code in Listin$ MA diides t"e difference of t%o numbers by one of t"e numbers& T"e code in Listin$ M6 c"ec(s numbers of different siCes to see if t"ey are t"e same number& Listing 76. est if same number. Sub C(ec1Sa!eHu!ber -i! #> A# Sinle -i! #' A# Sinle 98 Print AreSa!eHu!berB'@@2@'?<Q= '@@2@7777= >e9<C )3rue: $i:e diit# #a!e Print AreSa!eHu!berB'@@2@'?<Q= '@@277777= >e9<C )"al#e: $our diit# #a!e #> 6 '@@2@'?<Q )#> a##ined di$$erent :alue #' 6 '@@2@'??Q )t(an #' but #a!e nu!ber& Print AreSa!eHu!berB#>= #'= 7&7C )3rue: Sa!e nu!ber in #inle preci#ion& Print AreSa!eHu!berB'@@&2@'?<Q= '@@&2@7777= >e9<C)3rue: $i:e diit# #a!e Print AreSa!eHu!berB'&@@2@'?<Q= '&@@277777= >e9<C)"al#e: $our diit# #a!e End Sub A *ar$e 8uantity of *iterature and researc" is aai*ab*e on t"e ne$atie issues associated %it" f*oatin$9point numbers& A comp*ete discussion is t"erefore %e** beyond t"e scope of t"is boo(& )n $enera* usa$e, t"e prob*ems typica**y arenGt t"at troub*esome, but, %"en t"ey arise, t"ey can be most perp*e3in$ if you arenGt a%are of t"e issues& 4.3. Mathematical functions T"e mat"ematica* functions in 11o +asic ta(e a numeric ar$ument& A** of t"e standard types are conerted to a Doub*e before t"ey are used& Strin$s may inc*ude "e3adecima* and octa* numbers& T"e functions are t"e same as t"ose aai*ab*e in Oisua* +asic ,see Tab*e 26.& Table 26. Mathematical functions supported by OOo !asic. OOo Basic VB VB ,%ET &etrn Vale A+S A+S Mat"&Abs T"e abso*ute a*ue of a specified number& 23p 23p Mat"&23p T"e base of natura* *o$arit"ms raised to a po%er& Lo$ Lo$ Mat"&Lo$ T"e *o$arit"m of a number& )n O+ &42T you can oer*oad t"is met"od to return eit"er t"e natura* ,base e. *o$arit"m or t"at of a specified base& S$n S$n Mat"&Si$n )nte$er a*ue indicatin$ t"e si$n of a number& S8r S8r Mat"&S8rt T"e s8uare root of a number& 5se t"e A+S function to determine t"e abso*ute a*ue of a number, %"ic" you can t"in( of as simp*y t"ro%in$ a%ay t"e *eadin$ N or 9 si$n from t"e front of t"e number& T"e $eometrica* definition of A+S,3. is t"e distance from 3 to 0 a*on$ a strai$"t *ine& ABSB'%&%%C 6 '%&%% ABSB9%C 6 % ABSB"9>"C 6 > )Hotice t(at t(e #trin :alue "9>" i# con:erted to a -ouble 5se t"e S$n function to determine t"e si$n of a number& An inte$er %it" t"e a*ue 91, 0, or 1 is returned if t"e number is ne$atie, Cero, or positie& SnB9%2&?C 6 9> SnB7C 6 7 SnB"?"C 6 > T"e s8uare root of B is 3, because 3 mu*tip*ied by 3 is B& 5se t"e S8r function to $et t"e s8uare root of a number& T"e S8r function canGt ca*cu*ate t"e s8uare root of a ne$atie number L attemptin$ to do so causes a run9time error& S;rB>77C 6 >7 S;rB>AC 6 ? S;rB'C 6 >&?>?'>%<A'%2> 99 Lo$arit"ms %ere deised by Ko"n 4apier, %"o *ied from 1AA0 t"rou$" 161M& 4apier deised *o$arit"ms to simp*ify arit"metic ca*cu*ations, by substitutin$ addition and subtraction for mu*tip*ication and diision& Lo$arit"ms "ae t"e fo**o%in$ properties: ,oBx*.C 6 ,oBxC W ,oB.C ,oBx+.C 6 ,oBxC 9 ,oB.C ,oBxZ.C 6 . * ,oBxC T"e 23p function is t"e inerse of t"e Lo$ function& 0or e3amp*e, 23p,Lo$,!.. ? ! and Lo$,23p,2.. ? 2& +y desi$n, *o$arit"ms turn mu*tip*ication prob*ems into addition prob*ems& T"is a**o%s t"e use of *o$arit"ms as t"ey %ere ori$ina**y desi$ned& Print ExpB,oB>'C W ,oB%CC )%A 6 >' * % Print ExpB,oB>'C 9 ,oB%CC ) ? 6 >' + % Lo$arit"ms are defined by t"e e8uation y?b^3& )t is t"en said t"at t"e *o$arit"m, base b, of y is 3& 0or e3amp*e, t"e *o$arit"m base 10, 10^2 ? 100 so t"e *o$arit"m, base 10, of 100 is 2& T"e natura* *o$arit"m, %it" a base appro3imated by e?2&M1@2@1@2@!AB0!A23A36, is fre8uent*y used because it "as some nice mat"ematica* properties& T"is is ca**ed t"e Dnatura* *o$arit"mF and is used in 11o +asic& Oisua* +asic &42T a**o%s you to ca*cu*ate *o$arit"ms of ot"er bases& T"is is easi*y done usin$ t"e formu*a t"at t"e *o$arit"m base b is $ien by Lo$,3.-Lo$,b., re$ard*ess of t"e base of t"e *o$arit"m t"at is used& Lo$arit"ms are not as usefu* as a $enera* s"ortcut for ca*cu*ations today, %"en *ots of computin$ po%er is aai*ab*e& Eo%eer, t"e *o$arit"mic re*ations"ip describes t"e be"aior of many natura* p"enomena& 0or e3amp*e, t"e $ro%t" of popu*ations is often described usin$ *o$arit"ms, because $eometric $ro%t" e3pressed on a *o$arit"mic $rap" disp*ays as a strai$"t *ine& 23ponentia*s and *o$arit"ms are a*so used e3tensie*y in en$ineerin$ computations t"at describe t"e dynamic be"aior of e*ectrica*, mec"anica*, and c"emica* systems& T"e macro in Listin$ MM ca*cu*ates t"e *o$arit"m of t"e number 3 ,first ar$ument. to t"e specified base b ,second ar$ument.& 0or e3amp*e, use Lo$+ase,@, 2. to ca*cu*ate t"e *o$, base 2, of @ ,t"e ans%er is 3.& Listing 77. Log!ase. "unction ,oBa#eBx= bC A# -ouble ,oBa#e 6 ,oBxC + ,oBbC End "unction 4.4. @umeric conversions 11o +asic tries to conert ar$uments to an appropriate type before performin$ an operation& Eo%eer, it is safer to e3p*icit*y conert data types usin$ conersion functions, as presented in t"is c"apter, t"an to re*y on t"e defau*t be"aior, %"ic" may not be %"at you %ant& ;"en an )nte$er ar$ument is re8uired and a f*oatin$9 point number is proided, t"e defau*t be"aior is to round t"e number& 0or e3amp*e, 16&@ M1D M rounds 16&@ to 1M before performin$ t"e operation& T"e )nte$er diision operator, "o%eer, truncates t"e operands& 0or e3amp*e, D'rint ! S 0&BBBF truncates 0&BBB to 0, causin$ a diision9by9Cero error& T"ere are many different met"ods and functions to conert to numeric types& T"e primary conersion functions conert numbers represented as strin$s based on t"e computerGs *oca*e& T"e conersion functions in Tab*e 2M conert any strin$ or numeric e3pression to a number& Strin$ e3pressions containin$ "e3adecima* or octa* numbers must represent t"em usin$ t"e standard 11o +asic notation& 0or e3amp*e, t"e "e3adecima* number 2A must be represented as DQE2AF& 100 Table 27. /onvert to a numerical type. !nction Type Description #+yte,e3pression. +yte Round t"e Strin$ or numeric e3pression to a +yte& ##ur,e3pression. #urrency #onert t"e Strin$ or numeric e3pression to a #urrency& T"e *oca*e settin$s are used for decima* separators and currency symbo*s& #Dec,e3pression. Decima* Jenerate a Decima* type7 imp*emented on*y on ;indo%s& #)nt,e3pression. )nte$er Round t"e Strin$ or numeric e3pression to t"e nearest )nte$er& #Ln$,e3pression. Lon$ Round t"e Strin$ or numeric e3pression to t"e nearest Lon$& #Db*,e3pression. Doub*e #onert a Strin$ or numeric e3pression to a Doub*e& #Sn$,e3pression. Sin$*e #onert a Strin$ or numeric e3pression to a Sin$*e& T"e functions t"at return a %"o*e number a** "ae simi*ar be"aior& 4umeric e3pressions are rounded rat"er t"an truncated& A strin$ e3pression t"at does not contain a number ea*uates to Cero& 1n*y t"e portion of t"e strin$ t"at contains a number is ea*uated, as s"o%n in Listin$ M@& Listing 78. /"nt and /Lng ignore non4numeric values. Print CIntB>'&'C ) >' Print C,nB">'&<"C ) >% Print CIntB"xx.."C ) 7 Print C,nB">'&>xx"C ) >' Print CIntB9>'&'C )9>' Print CIntB"9>'&<"C )9>% Print C,nB"9>'&<xx"C )9>% #Ln$ and #)nt "ae simi*ar, but not identica*, be"aior for different types of oerf*o% conditions& Decima* numbers in strin$s t"at are too *ar$e cause a run9time error& 0or e3amp*e, #)nt,Z!0000Z. and #Ln$,ZBBBBBBBBBBBBZ. cause a run9time error, but #Ln$,Z!0000Z. does not& #Ln$ neer causes an oerf*o% if a "e3adecima* or octa* number is too *ar$e7 it si*ent*y returns Cero %it"out comp*aint& #)nt, "o%eer, interprets "e3adecima* and octa* numbers as a Lon$ and t"en conerts t"em to an )nte$er& T"e resu*t is t"at a a*id Lon$ $enerates a run9time error %"en it is conerted to an )nte$er& A "e3adecima* a*ue t"at is too *ar$e to be a*id returns Cero %it" no comp*aints and t"en is cast to an )nte$er ,see Listin$ MB.& Listing 79. /"nt interprets the number as a Long) then converts to an "nteger. Print C,nB"4H""""""""""E"C )7 O:er$lo* on a ,on Print CIntB"4H""""""""""E"C )7 O:er$lo* on a ,on t(en con:ert to Inteer Print C,nB"4H""""E"C )>7?Q<2? Print CIntB"4H""""E"C )Run9ti!e error= con:ert to ,on t(en o:er$lo* T"e code in Listin$ @0 conerts numerous "e3adecima* numbers to a Lon$ usin$ #Ln$& See Tab*e 2@ for an e3p*anation of t"e output in Listin$ @0& Listing 80. $.ample/Lng'ith&e.. Sub Exa!pleC,nWit(Hex On Error Re#u!e Hext -i! #F= iG -i! :BC :BC 6 Arra.B"4H""= "4H"""= "4H""""= "4H"""""=5 "4H""""""= "4H"""""""= "4H""""""""= "4H"""""""""=5 101 "4H""""""""""=5 "4HE"= "4H"E"= "4H""E"= "4H"""E"=5 "4H""""E"= "4H"""""E"= "4H""""""E"= "4H"""""""E"=5 "4H""""""""E"C "or i 6 ,BoundB:BCC 3o 0BoundB:BCC # 6 # 4 i 4 " C,nB" 4 :BiC 4 "C 6 " # 6 # 4 C,nB:BiCC # 6 # 4 CHRFB>7C Hext M#Box # End Sub Table 28. Output from Listing 0C with e.planatory te.t. Inpt CLn+ Explanation 0 1A #orrect "e3adecima* a*ue& 00 2AA #orrect "e3adecima* a*ue& 000 !0BA #orrect "e3adecima* a*ue& 0000 6AA3A #orrect "e3adecima* a*ue& 00000 10!@AMA #orrect "e3adecima* a*ue& 000000 16MMM21A #orrect "e3adecima* a*ue& 0000000 26@!3A!AA #orrect "e3adecima* a*ue& 00000000 >> S"ou*d return 91, but may cause a run time error on 6!9bit ersions& 000000000 0 1erf*o% returns Cero7 t"is is nine "e3adecima* di$its& 2 1! #orrect "e3adecima* a*ue& 02 2A! #orrect "e3adecima* a*ue& 002 !0B! #orrect "e3adecima* a*ue& 0002 6AA3! #orrect "e3adecima* a*ue& 00002 10!@AM! #orrect "e3adecima* a*ue& 000002 16MMM21! #orrect "e3adecima* a*ue& 0000002 26@!3A!A! #orrect "e3adecima* a*ue& 00000002 2RR1R Run time error, used to return 92& 000000002 0 1erf*o% returns Cero7 t"is is nine "e3adecima* di$its& ;"en %ritin$ numbers, you donGt need to inc*ude *eadin$ Ceros& 0or e3amp*e, 3 and 003 are t"e same number& A Lon$ )nte$er can contain ei$"t "e3adecima* di$its& )f on*y four di$its are %ritten, you can assume t"ere are *eadin$ Ceros& ;"en t"e "e3adecima* number is too *ar$e for a Lon$, a Cero is returned& T"e ne$atie numbers are /ust as easi*y e3p*ained& T"e computerGs interna* binary representation of a ne$atie number "as t"e first bit set& T"e "e3adecima* di$its @, B, A, +, #, D, 2, and 0 a** "ae t"e "i$" bit set %"en represented as a binary number& )f t"e first "e3adecima* di$it "as t"e "i$" bit set, t"e returned Lon$ is ne$atie& A "e3adecima* number is positie if it contains fe%er t"an ei$"t "e3adecima* di$its, and it is ne$atie if it contains ei$"t "e3adecima* di$its and t"e first di$it is @, B, A, +, #, D, 2, or 0& ;e**, t"is used to be true& 102 TIP )n 6!9bit ersions of 11o, #Ln$ $enerate an error for ne$atie numbers represented as Ee3adecima*T Eopefu**y t"is %i** be fi3ed& Eere are t%o tests t"at ) e3pect to print 91& 4ote: ) *aste tested %it" 11o ersion 3&3&0 and L1 3&!&1 R#3& print 4H"""""""" print C,nB"4H"""""""""C ) Jenerate# an error T"e #+yte function "as t"e same be"aior as #)nt and #Ln$, a*beit %it" a fe% caeats& T"e return type, +yte, is interpreted as a c"aracter un*ess it is e3p*icit*y conerted to a number& A +yte is a S"ort )nte$er t"at uses on*y ei$"t bits rat"er t"an t"e 16 used by an )nte$er& Print CB.teB"A<"C )A (a# ASCII :alue A< Print CIntBCB.teB"A<xx"CC )A< directl. con:erted to a nu!ber& TIP An inte$er in O+ &42T is e8uia*ent to an 11o +asic Lon$& O+ uses different roundin$ ru*es& 4umbers are rounded to t"e nearest een number %"en t"e decima* point is e3act*y 0&A7 t"is is ca**ed )222 roundin$& T"e functions t"at return a f*oatin$9point number a** "ae simi*ar be"aior& 4umeric e3pressions are conerted to t"e c*osest representab*e a*ue& Strin$s t"at contain non9numeric components $enerate a run9 time error& 0or e3amp*e, #Db*,D13&!e233F. causes a run9time error& #Db* and #Sn$ bot" $enerate a run9 time error for "e3adecima* and octa* numbers t"at are too *ar$e& Listing 81. /*ng and /#bl handle string input. Print C-blB>'&'C ) >'&' Print CSnB">'&<<e>"C ) >'<&< Print C-blB"9>'&'e9>"C)9>&'' Print CSnB"9>'&<"C )9>'&< Print C-blB"xx.."C ) run9ti!e error Print CSnB">'&>xx"C ) run9ti!e error T"e functions #Db* and #Sn$ bot" fai* for strin$ input t"at contains non9numeric data7 t"e Oa* function does not& 5se t"e Oa* function to conert a strin$ to a Doub*e t"at may contain ot"er c"aracters& T"e Oa* function *oo(s at eac" c"aracter in t"e strin$, i$norin$ spaces, tabs, and ne% *ines, stoppin$ at t"e first c"aracter t"at isnGt part of a number& Symbo*s and c"aracters often considered to be parts of numeric a*ues, suc" as do**ar si$ns and commas, are not reco$niCed& T"e function does, "o%eer, reco$niCe octa* and "e3adecima* numbers prefi3ed by Q1 ,for octa*. and QE ,for "e3adecima*.& T"e Oa* function treats spaces different*y t"an ot"er functions treat spaces7 for e3amp*e, Oa*,D 12 3!F. returns t"e number 123!7 #Db* and #Sn$ $enerate a run9time error, and #)nt returns 12 for t"e same input& Listing 82. reatment of spaces is different. Sub Hu!#Are-i$$erent On Error Jo3o ErrorHandler: -i! #F # 6 "OalB"" >' %?""C 6 " # 6 # 4 OalB" >' %?"C # 6 # 4 CHRFB>7C 4 "CIntB"" >' %?""C 6 " # 6 # 4 CIntB" >' %?"C # 6 # 4 CHRFB>7C 4 "C,nB"" >' %?""C 6 " # 6 # 4 C,nB" >' %?"C # 6 # 4 CHRFB>7C 4 "CSnB"" >' %?""C 6 " # 6 # 4 CSnB" >' %?"C 103 # 6 # 4 CHRFB>7C 4 "C-blB"" >' %?""C 6 " # 6 # 4 C-blB" >' %?"C M#Box # Exit Sub ErrorHandler: # 6 # 4 " Error: " 4 Error Re#u!e Hext End Sub TIP T"e Oa* function does not use *oca*iCation %"i*e conertin$ a number so t"e on*y reco$niCed decima* separator is t"e period7 t"e comma can be used as a $roup separator but is not a*id to t"e ri$"t of t"e decima*& 5se #Db* or #Ln$ to conert numbers based on t"e current *oca*e& )n case you for$ot, t"e *oca*e is anot"er %ay to refer to t"e settin$s t"at affect formattin$ based on a specific country& See Listin$ @3& Listing 83. he 3al function is the inverse of the *tr function. Sub Exa!pleOal Print OalB" >' %?"C )>'%? Print OalB">' W %?"C )>' Print OalB"9>&'%e?"C )9>'%77 Print OalB" 4"""C )7 Print OalB" 4H"""C )'<< Print OalB"4H"""""C )9> Print OalB"4H"""E"C )9' Print OalB"4H%"""E"C )9'= .e#= it reall. con:ert# t(i# to 9' Print OalB"4H""""""""""""""C )9> End Sub As of ersion 1&1&1, t"e be"aior of t"e Oa* function %"i*e reco$niCin$ "e3adecima* or octa* numbers is stran$e enou$" t"at ) ca** it a bu$& )nterna**y, "e3adecima* and octa* numbers are conerted to a 329bit Lon$ )nte$er and t"en t"e *east si$nificant 16 bits are conerted to an )nte$er& T"is e3p*ains %"y in Listin$ @3 t"e number E30002 is conerted to 92, because on*y t"e *east si$nificant 16 bits are reco$niCed L in case you for$ot, t"is means t"e ri$"tmost four "e3adecima* di$its& T"is stran$e be"aior is demonstrated in Listin$ @!& T"e output is e3p*ained in Tab*e 2B& Listing 84. $.ample3al'ith&e.. Sub Exa!pleOalWit(Hex -i! #F= iG -i! l A# ,on -i! :BC :BC 6 Arra.B"4H""= "4H"""= "4H""""= "4H"""""=5 "4H""""""= "4H"""""""= "4H""""""""= "4H"""""""""=5 "4H""""""""""=5 "4HE"= "4H"E"= "4H""E"= "4H"""E"=5 "4H""""E"= "4H"""""E"= "4H""""""E"= "4H"""""""E"=5 "4H""""""""E"= "4H>>>>>>>>>"= "4H>>>>"C "or i 6 ,BoundB:BCC 3o 0BoundB:BCC # 6 # 4 "OalB" 4 :BiC 4 "C 6 " 4 OalB:BiCC 4 CHRFB>7C Hext )3(i# *or1ed in OOo '&x= but= it ) $ail# in OOo %&'&> )l 6 "4H" 4 HexB9'C # 6 # 4 CHRFB>7C 4 "HexB9>C 6 " 4 HexB9>C 4 CHRFB>7C 104 # 6 # 4 "HexB9'C 6 " 4 HexB9'C 4 CHRFB>7C )# 6 # 4 "l 6 4H" 4 HexB9'C 4 " 66D " 4 l 4 CHRFB>7C M#Box # End Sub Table 29. Output from Listing 02 with e.planatory te.t. Inpt Otpt Explanation 0 1A Ee3adecima* 0 is 1A& 00 2AA Ee3adecima* 00 is 2AA& 000 !0BA Ee3adecima* 000 is !0BA& 0000 91 Ee3adecima* 0000 is 91 for a 169bit ,t%o9byte. inte$er& 00000 91 1n*y t"e ri$"tmost t%o bytes ,four c"aracters. are reco$niCed& 2 1! Ee3adecima* 2 is 1!& 02 2A! Ee3adecima* 02 is 2A!& 002 !0B! Ee3adecima* 002 is !0B!& 0002 92 Ee3adecima* 0002 is 92 for a 169bit ,t%o9byte. inte$er& 00002 92 1n*y t"e ri$"tmost t%o bytes are reco$niCed& 000002 92 1n*y t"e ri$"tmost t%o bytes are reco$niCed& 0000002 92 1n*y t"e ri$"tmost t%o bytes are reco$niCed& 00000002 92 1n*y t"e ri$"tmost t%o bytes are reco$niCed& E000000002 92 1n*y t"e ri$"tmost t%o bytes are reco$niCed& 111111111 !63B #orrect a*ue, ri$"t most t%o bytes on*y& 1111 !63B #orrect a*ue Oa* conerts "e3adecima* numbers, but, it on*y uses t"e ri$"tmost t%o bytes& 5se t"e functions #+yte, #)nt, #Ln$, #Sn$, and #Db* to conert a number, strin$, or e3pression to a specific numeric type& 5se t"e functions )nt and 0i3 to remoe t"e decima* portion and return a Doub*e& A strin$ e3pression t"at does not contain a number ea*uates to Cero& 1n*y t"e portion of t"e strin$ t"at contains a number is ea*uated& See Tab*e 30& Table 30. Remove the decimal portion of a floating4point number. !nction Type Description )nt Doub*e Round t"e number to%ard ne$atie infinity& 0i3 Doub*e #"op off t"e decima* portion& T"e functions )nt and 0i3 differ on*y in t"eir treatment of ne$atie numbers& 0i3 a*%ays discards t"e decima*, %"ic" is e8uia*ent to roundin$ to%ard Cero& )nt, on t"e ot"er "and, rounds to%ard ne$atie infinity& )n ot"er %ords, D)nt,12&3.F is 12 and D)nt,912&3.F is 913& Print IntB>'&'C ) >' Print "ixB>'&'C ) >' Print IntB">'&<"C ) >' Print "ixB">'&<"C ) >' 105 Print IntB"xx.."C ) 7 Print "ixB"xx.."C ) 7 Print IntB9>'&?C )9>% Print "ixB9>'&?C )9>' Print "ixB"9>'&>xx"C)9>' Print IntB"9>'&>xx"C)9>% T"e ##ur function conerts a numerica* e3pression to a currency ob/ect& Oisua* +asic &42T remoed support for t"e ##ur function as %e** as t"e #urrency data type& 11o +asic sti** supports t"e #urrency data type& 4.. @umber to string conversions Strin$ conersion functions, s"o%n in Tab*e 31, c"an$e non9strin$ data into strin$s& )n 11o, te3t is stored as 5nicode ersion 2&0 a*ues, proidin$ $ood support for mu*tip*e *an$ua$es& 2ac" Strin$ ariab*e can "o*d up to 6A,A3A c"aracters& Table 31. *tring conversion functions. !nction Description Str #onert from a number to a Strin$ %it" no *oca*iCation& #Str #onert anyt"in$ to a Strin$& 4umbers and dates are formatted based on *oca*e& Ee3 Return t"e "e3adecima* representation of a number as a Strin$& 1ct Return t"e octa* representation of a number as a Strin$& 4.#. /imple formatting 5se t"e #Str function to $enera**y conert any type to a Strin$& T"e returned a*ue is dependent upon t"e input data type& +oo*ean a*ues conert to t"e te3t DTrueF or D0a*se&F Dates conert to t"e s"ort date format used by t"e system& 4umbers are conerted to a strin$ representation of t"e number& See Listin$ @A& Listing 85. Output from /*tr is locale specificE this is $nglish 6U*-7. -i! n A# ,on= d A# -ouble= b A# Boolean n 6 @@@@@@@@@ : d 6 E/PB>&7C : b 6 "al#e Print "/" 4 CStrBbC )/"al#e Print "/" 4 CStrBnC )/@@@@@@@@@ Print "/" 4 CStrBdC )/'&2>Q'Q>Q'Q?<@7? Print "/" 4 CStrBHo*C)/7A+7@+'7>7 '7:'?:'? Bal!o#t exactl. 2 .ear# a$ter > #t editionC T"e #Str function performs simp*e number formattin$ %it" (no%*ed$e of t"e current *oca*e& Simp*e conersion of a number to a strin$ is done %it" Str& A*t"ou$" t"e Str function is desi$ned to dea* specifica**y %it" numeric a*ues, t"e output is ery simi*ar to #Str& ;"en t"e Str function conerts a number to a strin$, a *eadin$ space is a*%ays inc*uded for t"e si$n of t"e number& A ne$atie number inc*udes t"e minus si$n, and no *eadin$ empty space is present& A non9ne$atie number, on t"e ot"er "and, inc*udes a *eadin$ empty space& T"e output of Str is not *oca*e specific7 a period is a*%ays used as t"e decima* separator& See Listin$ @6& Listing 86. Output from *tr is not dependent upon locale. -i! n A# ,on= d A# -ouble= b A# Boolean n 6 @@@@@@@@@ : d 6 E/PB>&7C : b 6 "al#e Print "/" 4 StrBbC )/"al#e 106 Print "/" 4 StrBnC )/ @@@@@@@@@ Print "/" 4 StrBdC )/ '&2>Q'Q>Q'Q?<@7? Print "/" 4 StrBHo*C)/7A+7@+'7>7 '7:'Q:?Q Bal!o#t exactl. 2 .ear# a$ter > #t editionC T"e output from t"e code in Listin$ @A and Listin$ @6 is t"e same e3cept for a *eadin$ space in front of t"e non9ne$atie numbers& )f you run t"e code usin$ a different *oca*e, suc" as Jermany, t"e output c"an$es for Listin$ @A but not Listin$ @6& TIP T"ere is *itt*e reason to use Str rat"er t"an #Str& Str may run a bit faster, but #Str (no%s about your current *oca*e& To demonstrate t"at #Str is *oca*e specific, ) c"an$ed my *oca*e to Jerman ,Jermany. and t"en ran t"e code in Listin$ @A a$ain& Listin$ @M s"o%s t"at t"e decima* is no% e3pressed as a comma and t"at t"e date is no% e3pressed as MM&DD&6666& Listing 87. Output from /*tr is locale specificE this is <erman 6<ermany7. -i! n A# ,on= d A# -ouble= b A# Boolean n 6 @@@@@@@@@ : d 6 E/PB>&7C : b 6 "al#e Print "/" 4 CStrBbC )/"al#e Print "/" 4 CStrBnC )/@@@@@@@@@ Print "/" 4 CStrBdC )/'=2>Q'Q>Q'Q?<@7? Print "/" 4 CStrBHo*C)/>?&7Q&'7>7 '7:%@:?@ 4.$. Other number bases4 he:adecimal4 octal4 and binar' 11o +asic proides t"e functions Ee3 and 1ct to conert a number to "e3adecima* and octa*& 4o natie support is proided for a conersion to and from binary& 6ou canGt direct*y use t"e output from Ee3 and 1ct to conert t"e strin$ bac( to a number because it is missin$ t"e *eadin$ DQEF and DQ1F& Print HexB??2C )>B" Print CIntB"4H" 4 HexB2?2CC )2?2 Print OctBQ22C )><<< Print CIntB"4O" 4 OctB'>%CC )'>% T"e source code for #"apter 2 contains t"e function )ntTo+inaryStrin$, %"ic" conerts an inte$er to a binary number in t"e 1perators modu*e in t"e source code fi*e S#02&s3%& T"e function is ery f*e3ib*e but it isnGt particu*ar*y fast& A faster routine usin$ t"e Ee3 function is s"o%n in Listin$ @@& Listing 88. "nto!inary*tring. "unction Int3oBinar.StrinBB.Oal x A# ,onC A# Strin -i! #Hex A# Strin -i! #Bin A# Strin -i! i A# Inteer #Hex 6 HexBxC "or i6> 3o ,enB#HexC Select Ca#e MidB#Hex= i= >C Ca#e "7" #Bin 6 #Bin 4 "7777" Ca#e ">" #Bin 6 #Bin 4 "777>" Ca#e "'" #Bin 6 #Bin 4 "77>7" Ca#e "%" 107 #Bin 6 #Bin 4 "77>>" Ca#e "?" #Bin 6 #Bin 4 "7>77" Ca#e "<" #Bin 6 #Bin 4 "7>7>" Ca#e "A" #Bin 6 #Bin 4 "7>>7" Ca#e "2" #Bin 6 #Bin 4 "7>>>" Ca#e "Q" #Bin 6 #Bin 4 ">777" Ca#e "@" #Bin 6 #Bin 4 ">77>" Ca#e "A" #Bin 6 #Bin 4 ">7>7" Ca#e "B" #Bin 6 #Bin 4 ">7>>" Ca#e "C" #Bin 6 #Bin 4 ">>77" Ca#e "-" #Bin 6 #Bin 4 ">>7>" Ca#e "E" #Bin 6 #Bin 4 ">>>7" Ca#e """ #Bin 6 #Bin 4 ">>>>" End Select Hext Int3oBinar.Strin 6 #Bin End "unction T"e code in Listin$ @@ may be *on$, but itGs ery simp*e& T"ere is a corre*ation bet%een "e3adecima* di$its and binary di$its7 eac" "e3adecima* di$it is composed of four binary di$its& T"is re*ations"ip does not e3ist for base 10 numbers& T"e number is conerted to a "e3adecima* number usin$ t"e Ee3 function& 2ac" "e3adecima* di$it is conerted to t"e correspondin$ binary di$its& To conert a binary number in Strin$ form bac( to an )nte$er, use t"e code in Listin$ @B& TIP T"is routine fai*s %it" ne$atie numbers because #Ln$,. 11o 3&3&0 fai*s %it" Ee3 numbers representin$ ne$atie *on$ a*ues& Listing 89. !inary*tringoLong. "unction Binar.Strin3o,onB#FC A# ,on -i! #Hex A# Strin -i! #Bin A# Strin -i! i A# Inteer -i! n,e$tO:er A# Inteer -i! n A# Inteer
n 6 ,enB#FC n,e$tO:er 6 n MO- ? I$ n,e$tO:er D 7 3(en #Hex 6 S!allBin3oHexB,e$tB#F= n,e$tO:erCC End I$ 108 "or i6n,e$tO:er W > 3o n Step ? #Hex 6 #Hex 4 S!allBin3oHexBMidB#F= i= ?CC Hext Binar.Strin3o,on 6 C,nB"4H" 4 #HexC End "unction "unction S!allBin3oHexB#FC A# Strin I$ ,enB#FC E ? 3(en #F 6 StrinB?9,enB#FC= "7"C 4 #F Select Ca#e #F Ca#e "7777" S!allBin3oHex 6 "7" Ca#e "777>" S!allBin3oHex 6 ">" Ca#e "77>7" S!allBin3oHex 6 "'" Ca#e "77>>" S!allBin3oHex 6 "%" Ca#e "7>77" S!allBin3oHex 6 "?" Ca#e "7>7>" S!allBin3oHex 6 "<" Ca#e "7>>7" S!allBin3oHex 6 "A" Ca#e "7>>>" S!allBin3oHex 6 "2" Ca#e ">777" S!allBin3oHex 6 "Q" Ca#e ">77>" S!allBin3oHex 6 "@" Ca#e ">7>7" S!allBin3oHex 6 "A" Ca#e ">7>>" S!allBin3oHex 6 "B" Ca#e ">>77" S!allBin3oHex 6 "C" Ca#e ">>7>" S!allBin3oHex 6 "-" Ca#e ">>>7" S!allBin3oHex 6 "E" Ca#e ">>>>" S!allBin3oHex 6 """ End Select End "unction To conert a binary strin$ to an )nte$er, t"e number is first conerted to a "e3adecima* number& A set of four binary di$its correspond to a sin$*e "e3adecima* di$it& T"e number is padded on t"e *eft %it" Ceros so t"at t"e strin$ can be bro(en up into b*oc(s of four binary di$its& 2ac" b*oc( of four binary di$its is conerted to a sin$*e "e3adecima* di$it& T"e #Ln$ function is t"en used to conert t"e "e3adecima* number to decima* form& T"e routine in Listin$ B0 demonstrates t"e use of t"ese functions7 a*so see 0i$ure !2& Listing 90. $.ample'holeNumber/onversions. Sub Exa!pleW(oleHu!berCon:er#ion# -i! # A# Strin 109 -i! n A# ,on -i! nA#HexF= nA#OctF= nA#BinF # 6 InputBoxB"Hu!ber to con:ert:"= ",on 3o Ot(er"= ">%Q@"C I$ I#HullB#C 3(en Exit Sub I$ ,enB3ri!B#CC 6 7 3(en Exit Sub n 6 C,nB3ri!B#CC )3ri! re!o:e# leadin and trailin #pace# nA#Hex 6 HexBnC nA#Oct 6 OctBnC nA#Bin 6 Int3oBinar.StrinBnC # 6 "Oriinal nu!ber 6 " 4 CStrBnC 4 CHRFB>7C 45 "HexB" 4 CStrBnC 4 "C 6 " 4 nA#Hex 4 CHRFB>7C 45 "OctB" 4 CStrBnC 4 "C 6 " 4 nA#Oct 4 CHRFB>7C 45 "Binar.B" 4 CStrBnC 4 "C 6 " 4 nA#Bin 45 " 66D " 4 Binar.Strin3o,onBnA#BinC M#BoxB#= 7= "W(ole Hu!ber Con:er#ion#"C End Sub Figure 42. /onvert a whole number to he.adecimal) octal) and binary. 4.&. %andom numbers 11o +asic $enerates f*oatin$9point random numbers ran$in$ from 0 t"rou$" 1& Random numbers $enerated by computers arenGt, in $enera*, random& An a*$orit"m is used t"at $enerates Drandom numbersF based on a preious random number& T"e first number on %"ic" a** ot"er random numbers are based is ca**ed t"e Dseed&F 6ou use t"e RandomiCe function to specify t"e seed a*ue& )f a a*ue is omitted, t"e RandomiCe function uses a a*ue obtained from t"e system timer& Specifyin$ t"e startin$ seed a**o%s you to test pro$rams and $enerate t"e same se8uence of random numbers eac" time& T"e Rnd function is used to $enerate t"e random numbers bet%een 0 and 1& T"e 11o "e*p c*aims t"at t"e Rnd function accepts an ar$ument7 ) c"ec(ed t"e source code for t"e Rnd function, %"ic" "as not c"an$ed from ersion 1&3 t"rou$" 3&2&1, and t"e ar$ument is i$nored& TIP T"e inc*uded "e*p fi*es incorrect*y c*aim t"at t"e Rnd function accepts an ar$ument t"at affects t"e be"aior& T"e ar$ument is, and a*%ays "as been, i$nored& Print RndBC )So!e nu!ber $ro! 7 t(rou( > Print RndBC )Anot(er nu!ber $ro! 7 t(rou( > T"e random number $enerated is some number from 0 t"rou$" 1& To obtain a different ran$e, perform a fe% mat"ematica* operations& 0or e3amp*e, mu*tip*yin$ a number bet%een 0 and 1 by 10 yie*ds a number bet%een 0 and 10& To use a ran$e t"at does not start at 0, add an appropriate offset& See Listin$ B1& Listing 91. Return a random number in a range. "unction RndRaneBlo*erBound A# -ouble= upperBound A# -oubleC A# -ouble RndRane 6 lo*erBound W RndBC * BupperBound 9 lo*erBoundC 110 End "unction 5se an appropriate function, suc" as #)nt or #Ln$, if you %ant a %"o*e number rat"er t"an a f*oatin$9point number& C,nBlo*erBound W RndBC * BupperBound 9 lo*erBoundCC ) "ad t%o functions t"at so*ed t"e same prob*em L determinin$ t"e J#D ,Jreatest #ommon Diisor. of t%o inte$ers L and ) %anted to (no% %"ic" %as faster& ) $enerated random inte$ers and ca**ed eac" routine a fe% t"ousand times& ;"i*e performin$ timin$ tests, itGs important to use t"e same data for eac" tria*& ) %as ab*e to use random numbers because t"e RandomiCe statement a**o%s me to $enerate t"e same random numbers eery time& Rando!i8eB'C )re#et t(e rando! nu!ber enerator to a 1no*n #tate t> 6 etS.#te!3ic1#BC "or i 6 7 3o %7777 n> 6 C,nB>7777 * RndBCC n' 6 C,nB>7777 * RndBCC call cd>Bn>= n'C Hext total5ti!e5> 6 etS.#te!3ic1#BC 9 t> Rando!i8eB'C )re#et t(e rando! nu!ber enerator to a 1no*n #tate t> 6 etS.#te!3ic1#BC "or i 6 7 3o %7777 n> 6 C,nB>7777 * RndBCC n' 6 C,nB>7777 * RndBCC call cd'Bn>= n'C Hext total5ti!e5' 6 etS.#te!3ic1#BC 9 t> 4.(. Conclusion T"e standard mat"ematica* functions in 1pen1ffice&or$ +asic contain fe% surprises& T"e conersion functions %or( %e**, %it" some idiosyncrasies %"i*e conertin$ strin$s to numbers& +e certain to c"oose a function t"at can "and*e t"e format and t"e ran$es used& Roundin$ is anot"er issue t"at re8uires specia* attention& A*t"ou$" t"e roundin$ be"aior is documented and consistent, different functions and operators cause roundin$ to occur different*y& 111 ,. )rra" 6outines T"is c"apter introduces t"e subroutines and functions supported by 11o +asic t"at are used to manipu*ate arrays& )t coers met"ods for manipu*atin$ arrays, creatin$ arrays %it" data, creatin$ arrays %it" no data, and c"an$in$ t"e dimension of arrays& T"is c"apter a*so presents met"ods to inspect array ariab*es& An array is a data structure in %"ic" simi*ar e*ements of data are arran$ed in an inde3ed structure L for e3amp*e, a co*umn of names or a tab*e of numbers& 11o +asic "as subroutines and functions t"at c"an$e array dimensions, inspect e3istin$ arrays, and conert bet%een arrays and sca*ar ,non9array. data types& T"e ma/ority of t"e routines *isted in Tab*e 32 re8uire an array ariab*e as t"e first ar$ument& Array ariab*es used as ar$uments to routines can be %ritten %it" trai*in$ parent"eses& 'arent"eses after t"e ariab*e are optiona*, but t"ey used to be re8uired ,see Listin$ B2.& TIP T"ere is no %ay to determine if a,. refers to an array or a function %"i*e readin$ code7 you must find %"ere t"e item in 8uestion is dec*ared& Listing 92. 9arentheses are not always re8uired but are always allowed. Sub AreArra.Paren#Re;uired -i! aB> 3o 'C )aBC i# declared *it( #peci$ied di!en#ion# -i! bBC )bBC i# declared a# an arra. *it(out #peci$ied di!en#ion# -i! c )c i# a :ariant and !a. re$erence an arra.& c 6 Arra.B>= 'C )c re$erence# a Oariant arra. Print I#Arra.BaBCC )3rue Print I#Arra.BbBCC )3rue Print I#Arra.BcBCC )3rue Print I#Arra.BaC )3rue Print I#Arra.BbC )3rue Print I#Arra.BcC )3rue End Sub Table 32. *ummary of subroutines and functions related to arrays. !nction Description Array,ar$s. Return a Oariant array t"at contains t"e ar$uments& DimArray,ar$s. Return an empty Oariant array& T"e ar$uments specify t"e dimension,s.& )sArray,ar. Return True if t"is ariab*e is an array, 0a*se ot"er%ise& Koin,array. Koin,array, de*imiter. #oncatenate t"e array e*ements separated by t"e optiona* strin$ de*imiter and return as a Strin$& T"e defau*t de*imiter is a sin$*e space& L+ound,array. L+ound,array, dimension. Return t"e *o%er bound of t"e array ar$ument& T"e optiona* dimension specifies %"ic" dimension to c"ec(& T"e first dimension is 1& ReDim c'resered ar,ar$s. cAs Typed #"an$e t"e dimension of an array usin$ t"e same synta3 as t"e D)M statement& T"e (ey%ord 'resere (eeps e3istin$ data intact& DAs TypeF is optiona*& Sp*it,str. Sp*it,str, de*imiter. Sp*it,str, de*imiter, n. Sp*it t"e strin$ ar$ument into an array of strin$s& T"e defau*t de*imiter is a space& T"e optiona* ar$ument n *imits t"e number of strin$s returned& 5+ound,array. 5+ound,array, dimension. Return t"e upper bound of t"e array ar$ument& T"e optiona* dimension specifies %"ic" dimension to c"ec(& T"e first dimension is 1& 112 T"e %ord DdimensionF is used to refer to arrays simi*ar*y to t"e %ay t"at DdimensionsF is used to refer to spatia* dimensions& 0or e3amp*e, an array %it" one dimension is *i(e a *ine7 you can set bo3es a*on$ t"e *ine t"at represent data& An array %it" t%o dimensions is *i(e a $rid %it" ro%s and co*umns of data& -i! aB%C A# Inteer )One9di!en#ional arra. -i! bB% 3o <C A# Strin )One9di!en#ional arra. -i! cB<= ?C A# Inteer )3*o9di!en#ional arra. -i! dB> 3o <= ?C A# Inteer )3*o9di!en#ional arra. .1. 2rra'68 Duic*l' builds a one9dimensional arra' with data 5se t"e Array function to 8uic(*y bui*d a Oariant array %it" data& T"e Array function returns a Oariant array t"at contains t"e ar$uments to t"e function& See Listin$ B3& T"is is an efficient met"od to create a Oariant array containin$ a predefined set of a*ues& 1ne entry in t"e array is created for eac" ar$ument& 5se t"e Array function to 8uic(*y $enerate an array t"at a*ready "as data& T"e fo**o%in$ code creates an array %it" fie e*ements, Cero t"rou$" four, and t"en indiidua**y initia*iCes eac" e*ement& -i! :B?C :B7C 6 ' : :B>C 6 "(elp": :B'C 6 Ho* : :B%C 6 3rue : :B?C 6 %&< T"is can be done in a muc" simp*er manner& #onstants can be used as ar$uments to functions& 6ou arenGt a*%ays forced to assi$n a a*ue to a ariab*e so t"at you can ca** a function& -i! :BC -i! "ir#tHa!eF : "ir#tHa!e 6 "Bob" :BC 6 Arra.B7= "(elp"= Ho*= 3rue= %&<C Print MoinBArra.B"(elp"= %= "Moe"= "ir#tna!eCC T"e ar$ument *ist is a comma9separated *ist of e3pressions, %"ic" can be of any type because eac" e*ement in t"e returned array is a ariant& Listing 93. he -rray function returns a 3ariant array. -i! :"ir#tHa!e# )A Oariant can re$erence an arra. -i! :Ae#BC )A Oariant arra. can re$erence an arra. :"ir#tHa!e# 6 Arra.B"3o!"= "Rob"C )Arra. contain# #trin# :Ae# 6 Arra.B>Q= "3en"C )Arra. contain# a nu!ber and a #trin Print :Ae#B7C )"ir#t ele!ent (a# t(e :alue >Q Oariant ariab*es can contain any type, inc*udin$ an array& ) fre8uent*y use ariant ariab*es %"en ) retriee a*ues from met"ods %"en )Gm not certain of t"e return type& ) t"en inspect t"e type and use it appropriate*y& T"is is a conenient use of t"e Oariant ariab*e type& +ecause a Oariant ariab*e can contain any type L inc*udin$ an array L eac" e*ement in a Oariant array can a*so contain an array& T"e code in Tab*e 33 demonstrates p*acin$ an array inside anot"er array& T"e code in eac" co*umn is rou$"*y e8uia*ent& TIP A*t"ou$" user defined structures cannot contain arrays, t"ey can contain a ariant, %"ic" can contain an array& 1ne adanta$e of Oariant arrays is t"at itGs possib*e to easi*y bui*d co**ections of information of different types& 0or e3amp*e, t"e item description ,Strin$., stoc(9trac(in$ )D ,)nte$er., and inoice amount ,Doub*e or #urrency. can readi*y be stored as ro%s in an array, %it" eac" type of data stored in a sin$*e ro% for eac" customer& T"is a**o%s array ro%s to be"ae more *i(e ro%s in a database& 1*der pro$rammin$ *an$ua$es re8uired use of separate*y dec*ared arrays for eac" data type, %it" added pro$rammin$ oer"ead of mana$in$ t"e use of mu*tip*e, re*ated arrays of data& 113 Table 33. - 3ariant can contain an array) so these accomplish the same thing. -i! :B>C :B7C 6 Arra.B>= '= %C :B>C 6 Arra.B"one"= "t*o"= "t(ree"C -i! :BC : 6 Arra.BArra.B>= '= %C=5 Arra.B"one"= "t*o"= "t(ree"CC )n 11o ersion 1&3, to address an array containin$ an array, you "ad to first e3tract t"e contained array, and t"en subscript t"e contained array& Muc" of my e3istin$ code %as %ritten based on t"is& Listing 94. /umbersome method to subscript an array in an array. : 6 Arra.BArra.B>= '= %C= Arra.B"one"= "t*o"= "t(ree"CC x 6 :B7C )3(i# i# :er. cu!ber#o!e& Print xB>C )Print# ' Some%"ere bet%een ersion 2&3 and 3&3, t"e obious so*ution %as introduced7 you can direct*y access t"e contained array& T"is is particu*ar*y usefu* %"i*e usin$ data arrays returned by #a*c containin$ ce** data& Listing 95. "n OOo F..) you no longer need to e.tract the contained array to use it. Sub Arra.InArra. -i! :BC : : 6 Arra.BArra.B>= '= %C= Arra.B"one"= "t*o"= "t(ree"CC Print :B7CB>C End Sub A*t"ou$" itGs easy to create an array inside of an array, itGs typica**y easier to use an array %it" mu*tip*e dimensions, as s"o%n in Listin$ B6& T"e Darray of arraysF construction is sometimes usefu*, if t"ere is an obious re*ations"ip %it" t"e natura* or$aniCation of t"e data& Jenera**y, it is best to se*ect a %ay to or$aniCe t"e data t"at "as t"e most direct, natura*, and memorab*e re*ations"ip to "o% it is produced, used, and manipu*ated& Listing 96. "t is easier to use multi4dimensioned arrays than arrays inside of arrays. -i! :B7 3o >= 7 3o 'C :B7= 7C 6 > : :B7= >C 6 ' : :B7= 'C 6 % :B>= 7C 6 "one" : :B>= >C 6 "t*o" : :B>= 'C 6 "t(ree" Print :B7= >C )print# ' A Oariant array can be assi$ned to any ot"er array, re$ard*ess of its dec*ared type& Assi$nin$ one array to anot"er causes one array to reference t"e ot"er7 t"ey become t"e same array& As mentioned ear*ier, t"is is a bad idea& T"is is considered a bu$ and it may not be a**o%ed in *ater ersions of 11o +asic& 5se t"e Array function and en/oy t"e f*e3ibi*ity, but assi$n t"e returned Oariant array to eit"er a Oariant or a Oariant array& Listing 97. -ssign an string array to an integer array. Sub BadArra.3.pe# -i! aB7 3o >C A# Inteer -i! bB7 3o >C A# Strin bB7C 6 "8ero": bB>C 6 "one" aBC 6 bBC Print aB7C End Sub 114 TIP Assi$nin$ a Oariant array to ariab*es dec*ared as a non9Oariant array is i**9adised& 0or e3amp*e, after an )nte$er array "as been assi$ned to reference a Oariant array, itGs possib*e to assi$n non9inte$er a*ues to e*ements in t"e array& References to t"e array %onGt return t"e e3pected a*ues due to t"e mismatc" bet%een )nte$er and Oariant data types& -i! aB7 3o ?C A# Inteer ) Create an arra. o$ Inteer#& aB'C 6 "3o!" ) A##in a #trin to an Inteer :ariable& Print aB'C ) 7= becau#e t(e #trin i# con:erted to 8ero& aBC 6 Arra.B?= "Bob"= 2C ) Arra. al*a.# return# a :ariant arra.& aB'C 6 "3o!" ) aBC i# no* a :ariant& Print aB'C ) 3o! .2. "im2rra' creates empt' multi9dimensional arra's T"e DimArray function creates and returns a dimensioned Oariant array& T"is a**o%s t"e dimensions of t"e array to be determined at run time& T"e ar$uments specify t"e dimensions of t"e array7 eac" ar$ument specifies one dimension& )f no ar$uments are present, an empty array is created& T"e primary use of t"e DimArray statement is to create an empty, dimensioned Oariant array& )f you (no% t"e siCe of t"e array t"at you %i** need, you can dec*are it %"en you dec*are t"e ariab*e& )f you donGt (no% t"e siCe, and if a Oariant array is acceptab*e, t"en you can create t"e empty, dimensioned array at run time& Listing 98. #im-rray returns a dimensioned 3ariant array that contains no data. iG 6 2 : 6 -i!Arra.B%*iGC )Sa!e a# -i! :B7 3o '>C : 6 -i!Arra.BiG= ?C )Sa!e a# -i! :B7 3o 2= 7 3o ?C T"e code in Listin$ B@ does not s"o% "o% t"e ariab*e is dec*ared& T"is %or(s e8ua**y %e** if is dec*ared as a Oariant, or a Oariant array& T"e ar$ument *ist is a comma9separated *ist of e3pressions& 2ac" e3pression is rounded to an inte$er and used to set t"e ran$e of one dimension of t"e returned array& -i! a A# Oariant -i! :BC -i! i A# Inteer i 6 ' a 6 -i!Arra.B%C )Sa!e a# -i! aB7 3o %C a 6 -i!Arra.B>Wi= '*iC )Sa!e a# -i! aB7 3o %= 7 3o ?C :BC 6 -i!Arra.B>C )Sa!e a# -i! :B7 3o >C :B7C 6 Arra.B>= '= %C )O( no= not t(i# aainK :B>C 6 Arra.B"one"= "t*o"= "t(ree"C )Pou can do it= but .uc1K : 6 -i!Arra.B>= 'C )Ho* t(at !a1e# !ore #en#eK :B7= 7C 6 > : :B7= >C 6 ' : :B7= 'C 6 % :B>= 7C 6 "one" : :B>= >C 6 "t*o" : :B>= 'C 6 "t(ree" Print :B7= >C )print# ' TIP 1ption +ase 1 "as no effect on t"e dimensions of t"e array returned by t"e DimArray function& 0or eac" dimension, t"e *o%er bound of t"e ran$e is a*%ays Cero and t"e upper bound is t"e rounded inte$er a*ue of t"e re*eant e3pression& 115 .3. Change the dimension of an arra' 5se ReDim to c"an$e t"e dimensions of an e3istin$ array by usin$ t"e same synta3 as t"e D)M statement& )ncreasin$ t"e dimension of an array %"i*e usin$ t"e (ey%ord 'resere preseres a** of t"e data, but decreasin$ t"e dimension causes data to be *ost by truncation& 5n*i(e some ariants of +AS)#, 11o +asic a**o%s a** dimensions of an array to be c"an$ed %"i*e a*so preserin$ data& T"e primary use of t"e ReDim statement is to c"an$e t"e dimension of an e3istin$ array& )f you (no% t"e siCe of t"e array t"at you %i** need, you can dec*are it %"en you dec*are t"e ariab*e& )f you donGt (no% t"e siCe a"ead of time, you can dec*are t"e array %it" any siCe, inc*udin$ as an empty array, and t"en c"an$e t"e dimension %"en you (no% it& -i! :BC A# Inteer -i! xB?C A# Inteer iG 6 2 Re-i! :B%*iGC A# Inteer )Sa!e a# -i! :B7 3o '>C A# Inteer& Re-i! xBiG= > 3o ?C A# Inteer )Sa!e a# -i! xB7 3o 2= > 3o ?C& T"e ReDim statement c"an$es t"e dimension of an e3istin$ array, een an empty one& ReDim specifies bot" t"e dimensions and t"e type& T"e type specified %it" t"e ReDim statement must matc" t"e type specified %"en t"e ariab*e is dec*ared& )f t"e types differ, youG** see t"e compi*e9time error DOariab*e a*ready defined&F -i! aBC A# Inteer )E!pt. Inteer Arra.& -i! :BQC )Oariant arra. *it( nine entrie#& Re-i! :BC ):BC i# a :alid e!pt. arra.& Re-i! aB' 3o ?= <C A# Inteer )aBC i# a t*o9di!en#ional arra.& T"e DimArray function creates and returns a dimensioned Oariant array t"at contains no data& T"is is not usefu* if you re8uire an array of a specific type, or if you simp*y need to c"an$e t"e dimensions of an e3istin$ array %"i*e preserin$ data& T"e ReDim statement c"an$es t"e dimensions of an e3istin$ array %it" t"e option of preserin$ e3istin$ data& 6ou can use t"e ReDim statement to c"an$e a dimensioned array to an empty array& T"e subroutine in Listin$ BB contains many e3amp*es of t"e ReDim statement usin$ t"e (ey%ord 'resere& 0i$ure !3 s"o%s t"e resu*ts of t"ese commands& Listing 99. Use Re#im with 9reserve to change dimension and preserve data. Sub Exa!pleRe-i!Pre#er:e -i! aB<C A# Inteer )A di!en#ioned arra.= 7 3o < -i! bBC )An e!pt. arra. o$ t.pe Oariant -i! cBC A# Inteer )An e!pt. arra. o$ t.pe Inteer -i! #F )3(e #trin t(at accu!ulate# t(e output text REM a i# di!en#ioned $ro! 7 to < *(ere aBiC 6 i aB7C 6 7 : aB>C 6 > : aB'C 6 ' : aB%C 6 % : aB?C 6 ? : aB<C 6 < #F 6 "aBC at #tart 6 " 4 MoinBaBCC 4 CHRFB>7C REM a i# di!en#ioned $ro! > to % *(ere aBiC 6 i Re-i! Pre#er:e aB> 3o %C A# Inteer #F 6 #F 4 "Re-i! Pre#er:e aB> 3o %C 6 " 4 MoinBaBCC 4 CHRFB>7C
M#Box #F= 7= "Re-i! Exa!ple#" End Sub Figure 43. Use Re#im to change the dimensions of an array. .4. 2rra' to /tring and bac* again Kust as itGs common to conert an array of a*ues into a sin$*e strin$ for disp*ay, it is a*so common to sp*it a strin$ into mu*tip*e pieces& 11o +asic proides t"ese abi*ities %it" t"e functions Koin and Sp*it& T"e first ar$ument to t"e Koin function is a one9dimensiona* array& Any ot"er dimension causes a run9time error& T"e e*ements in t"e array are concatenated %it" an optiona* de*imiter strin$ bet%een eac" e*ement& T"e defau*t de*imiter is a sin$*e space& MoinBArra.B>= '= %CC )> ' % u#in t(e de$ault deli!iter MoinBArra.B>= '= %C= "/"C )>/'/% #peci$.in a deli!iter 117 MoinBArra.B>= '= %C= ""C )>'% #peci$.in an e!pt. deli!iter T"e Sp*it function returns a Oariant array of strin$s, created by brea(in$ a strin$ into mu*tip*e strin$s based on a de*imiter& )n ot"er %ords, it parses a strin$ into pieces %it" one command& T"e de*imiter separates portions of t"e strin$& 0or e3amp*e, t"e de*imiter DI6F sp*its D12I611I622F into t"e strin$s ,D12F, D11F, D22F.& T"e de*imiter defau*ts to a space but can be any strin$ e3pression %it" *en$t" $reater t"an Cero& SplitB"> ' %"C )return Arra.B">"= "'"= "%"C #plit on " " SplitB">= '= %"= "= "C )return Arra.B">"= "'"= "%"C #plit on "= " T"e optiona* t"ird ar$ument is used to *imit t"e siCe of t"e returned array& T"is is used on*y to *imit t"e returned siCe and "as no effect if t"e returned siCe is *ess t"an t"e *imit& 0or e3amp*e, t"e ! in Sp*it,D1I2I3F, DIF, !. "as no effect because t"e returned array "as on*y t"ree e*ements& )f t"e siCe is *imited, "o%eer, t"e *ast e*ement in t"e array contains t"e remainder of t"e unparsed strin$& SplitB">= '= %"= "= "= 'C )return Arra.B">"= "'= %"C #plit on "= " TIP T"e second ar$ument to Sp*it is a strin$, so, 11o automatica**y conerts it to a strin$& T"e statement Sp*it,D0 1 2 3F, 2. conerts t"e 2 to a strin$ and uses it as t"e de*imiter& T"e returned array contains t%o e*ements, D0 1 F and D 3F& 6ou must specify t"e de*imiter if you %ant to specify t"e number of strin$s returned& T"e correct format is Sp*it,D0 1 2 3F, D F, 2.& T"e Sp*it function assumes t"at a strin$ comes before and after eac" de*imiter, een if t"e strin$ "as *en$t" Cero& SplitB"/>//'/"= "/"C 6 B""= ">"= ""= "'"= ""C T"e first returned strin$ is empty because t"e first ar$ument contains a *eadin$ de*imiter& T%o consecutie de*imiters produce an empty strin$ bet%een t"e D1F and t"e t"e D2F& 0ina**y, t"e trai*in$ strin$ is empty because t"ere is a trai*in$ de*imiter& T"e Sp*it function is a*most t"e inerse of t"e Koin function& T"e Koin function can use a Cero9*en$t" strin$ as t"e de*imiter, but t"e Sp*it function cannot& )f t"e /oined strin$ contains t"e de*imiter, sp*ittin$ t"e strin$ %i** produce a different set of strin$s& 0or e3amp*e, /oinin$ Da bF and DcF %it" a space produces Da b cF& Sp*ittin$ t"is %it" a space produces ,DaF, DbF, DcF., %"ic" is not t"e ori$ina* set of strin$s& ) spent a *ot of time %ritin$ and debu$$in$ a macro to parse t"rou$" a strin$ to remoe a** occurrences of t"e te3t DSb3F& 5sin$ Sp*it and Koin is si$nificant*y sma**er and faster: MoinBSplitB#= "Sbx"C= ""C .. 2rra' inspection functions T"e most fundamenta* t"in$ to as( about an array is %"et"er or not it rea**y is an array& T"e )sArray function returns True if t"e ar$ument is an array, and 0a*se ot"er%ise& 5se t"e L+ound and 5+ound functions to determine t"e *o%er and upper bounds of an array& An array is empty if t"e upper bound is *ess t"an t"e *o%er bound& T"e first ar$ument to L+ound and 5+ound is t"e array to c"ec(& T"e second optiona* ar$ument is an inte$er e3pression specifyin$ %"ic" dimension is returned& T"e defau*t a*ue is 1, %"ic" returns t"e *o%er bound of t"e first dimension& -i! aBC -i! bB' to %= 9< 3o <C Print ,BoundBaBCC ) 7 Print 0BoundBaBCC )9> becau#e t(e arra. i# e!pt. Print ,BoundBbBCC ) ' no optional #econd aru!ent #o de$ault# to > 118 Print ,BoundBbBC=>C ) ' optional #econd aru!ent #peci$ie# $ir#t di!en#ion Print 0BoundBbBC='C ) < )f t"e a*ue of t"e second ar$ument doesnGt contain a a*id a*ue, if itGs $reater t"an t"e number of dimensions, or if itGs *ess t"an 1, a run9time error occurs& Listing 100. *afeU!ound will not generate an error. "unction Sa$e0BoundB:= Optional nC A# Inteer Sa$e0Bound 6 9> )I$ an error occur#= t(i# i# alread. #et On Error Jo3o BadArra."ound )On error #1ip to t(e end I$ I#Mi##inBnC 3(en )Wa# t(e optional aru!ent u#edU Sa$e0Bound 6 0BoundB:C El#e Sa$e0Bound 6 0BoundB:= nC )Optional aru!ent i# pre#ent End I$ BadArra."ound: )Mu!p (ere on error On Error Jo3o 7 )3urn o$$ t(i# error (andler End "unction T"e macro in Listin$ 100 proper*y returns 91 if an error occurs& T"e proper a*ue is returned for ina*id empty arrays, but it a*so returns 91 if t"e first ar$ument isnGt an array or if t"e second ar$ument is simp*y too *ar$e& T"e Array)nfo function in Listin$ 101 uses a simi*ar tec"ni8ue to return array information about a ariab*e& A*so see 0i$ure !!& Listing 101. 9rint information about an array. REM I$ t(e $ir#t aru!ent i# an arra.= t(e di!en#ion# are deter!ined& REM Special care i# i:en to an e!pt. arra. t(at *a# created u#in -i!Arra. REM or Arra.& REM a : Oariable to c(ec1 REM #Ha!e : Ha!e o$ t(e :ariable $or a better loo1in #trin "unction arra.In$oBa= #Ha!eFC A# Strin REM "ir#t= :eri$. t(at: REM t(e :ariable i# not H0,,= an e!pt. ObNect REM t(e :ariable i# not EMP3P= an uninitiali8ed Oariant REM t(e :ariable i# an arra.& I$ I#HullBaC 3(en arra.In$o 6 "Oariable " 4 #Ha!e 4 " i# Hull" Exit "unction End I$ I$ I#E!pt.BaC 3(en arra.In$o 6 "Oariable " 4 #Ha!e 4 " i# E!pt." Exit "unction End I$ I$ Hot I#Arra.BaC 3(en arra.In$o 6 "Oariable " 4 #Ha!e 4 " i# not an arra." Exit "unction End I$ REM 3(e :ariable i# an arra.= #o et read. to *or1 -i! # A# Strin )Build t(e return :alue in # -i! iCur-i! A# Inteer )Current di!en#ion -i! iG= NG )Hold t(e ,Bound and 0Bound :alue# 119 On Error Jo3o Bad-i!en#ion )Set up t(e error (andler iCur-i! 6 > )Read. to c(ec1 t(e $ir#t di!en#ion REM Initial prett. return #trin # 6 "Arra. di!en#ioned a# " 4 #Ha!eF 4 "B"
-o W(ile 3rue ),oop $ore:er
i 6 ,BoundBaBC= iCur-i!C )Error i$ di!en#ion i# too lare or N 6 0BoundBaBC= iCur-i!C )i$ in:alid e!pt. arra.
I$ i D N 3(en Exit -o )I$ e!pt. arra. t(en et out
I$ iCur-i! D > 3(en # 6 # 4 "= " )Separate di!en#ion# *it( a co!!a # 6 # 4 i 4 " 3o " 4 N )Add in t(e current di!en#ion# iCur-i! 6 iCur-i! W > )C(ec1 t(e next di!en#ion ,oop
REM Onl. arri:e (ere i$ t(e arra. i# a :alid e!pt. arra.& REM Ot(er*i#e= an error occur# *(en t(e di!en#ion i# too REM lare and a Nu!p i# !ade to t(e error (andler REM Include t(e t.pe a# returned $ro! t(e 3.peHa!e $unction& REM 3(e t.pe na!e include# a trailin "BC" #o re!o:e t(i# # 6 # 4 "C A# " 4 ,e$tB3.peHa!eBaC= ,EHB3.peHa!eBaCC9'C arra.In$o 6 # Exit "unction
Bad-i!en#ion: REM 3urn o$$ t(e error (andler On Error Jo3o 7
REM Include t(e t.pe a# returned $ro! t(e 3.peHa!e $unction& REM 3(e t.pe na!e include# a trailin "BC" #o re!o:e t(i# # 6 # 4 "C A# " 4 ,e$tB3.peHa!eBaC= ,EHB3.peHa!eBaCC9'C
REM I$ errored out on t(e $ir#t di!en#ion t(en t(i# !u#t REM be an in:alid e!pt. arra.& I$ iCur-i! 6 > 3(en # 6 # 4 " *** IHOA,I- E!pt. Arra." arra.In$o 6 # End "unction Sub 0#eArra.In$o -i! i A# Inteer= : -i! iaB> 3o %C A# Inteer -i! #aBC A# Sinle -i! !B%= ?= 9? 3o 9>C
-i! # A# Strin # 6 # 4 arra.In$oBi= "i"C 4 CHRFB>7C )Hot an arra. # 6 # 4 arra.In$oB:= ":"C 4 CHRFB>7C )E!pt. :ariant # 6 # 4 arra.In$oB#aBC= "#a"C 4 CHRFB>7C )E!pt. arra. # 6 # 4 arra.In$oBArra.BC= "Arra."C 4 CHRFB>7C )BA- e!pt. arra. # 6 # 4 arra.In$oBiaBC= "ia"C 4 CHRFB>7C 120 # 6 # 4 arra.In$oB!BC= "!"C 4 CHRFB>7C M#Box #= 7= "Arra. In$o" End Sub Figure 44. Use proper error handling to determine the dimension of the array. An array %it" one dimension may "ae an upper bound t"at is *ess t"an t"e *o%er bound& T"is indicates t"at t"e array "as no a**ocated spots for data& T"is is different t"an an array t"at "as data *ocations a**ocated but no data "as been saed in t"em& 0or most data types, suc" as )nte$er, if space is a**ocated for an inte$er, t"en it "as a a*ue& -i! aB%C A# Inteer )3(i# arra. (a# $our inteer :alue#= t(e. are all 8ero -i! bB%C )3(i# arra. (a# $our Oariant#= t(e. are all E!pt. -i! cBC )3(i# arra. (a# one di!en#ion and no #pace 0bound E ,bound : 6 Arra.BC )3(i# arra. (a# 8ero di!en#ion#& .#. Conclusion Array "and*in$ in 11o +asic is ery f*e3ib*e& 6ou "ae t"e abi*ity to inspect arrays and to c"an$e t"eir dimensions& 5sin$ t"e Oariant type in 11o +asic proides a $reat dea* of f*e3ibi*ity for creatin$ co**ections of re*ated data of different types& Strin$s and arrays are re*ated7 strin$ arrays can be processed %it" Koin and Sp*it functions, permittin$ t"e creation of compact code t"at is ery po%erfu* for processin$ strin$ information& 121 .. (ate 6outines T"is c"apter introduces t"e subroutines and functions supported by 1pen1ffice&or$ +asic t"at are re*ated to dates L inc*udin$ functions to retriee t"e current date and time, manipu*ate dates and times, and perform timin$ functions& )t a*so discusses some potentia**y une3pected be"aior around 1ctober !, 1A@2, and a$ain around December 30, 1@BB& Date ariab*es contain bot" a date and a time a*ue& 11o +asic stores dates interna**y as a f*oatin$9point Doub*e& T"e portion of t"e number to t"e *eft of t"e decima* contains t"e date, and t"e fractiona* portion to t"e ri$"t of t"e decima* contains t"e time& 0or e3amp*e, addin$ 1 to a date a*ue adds one day to t"e date& Addin$ 1-2! to a date a*ue adds one "our to a date a*ue7 remember t"at t"ere are 2! "ours in a day& T"e date and time functions supported by 1pen1ffice&or$ are *isted in Tab*e 3!& Table 34. +unctions and subroutines related to dates and times. !nction Type Description #Date,e3pression. Date #onert a number or strin$ to a date& #Date0rom)so,strin$. Date #onert to a date from an )S1 @601 date representation& #DateTo)so,date. Strin$ #onert a date to an )S1 @601 date representation& Date,. Strin$ Return t"e current date as a strin$& DateAdd Date Add an intera* to a date& DateDiff )nte$er Returns t"e number of intera*s bet%een t%o dates& Date'art Oariant 1btain a specific part of a date a*ue& DateSeria*,yr, mnt", day. Date #reate a date from component pieces: 6ear, Mont", Day& DateOa*ue,date. Date 23tract t"e date from a date-time a*ue by truncatin$ t"e decima* portion& Day,date. )nte$er Return t"e day of t"e mont" as an )nte$er from a Date a*ue& 0ormatDateTime Strin$ 0ormat t"e date and time as a strin$& Re8uires 1ption#ompatib*e& JetSystemTic(s,. Lon$ Return t"e number of system tic(s as a Lon$& Eour,date. )nte$er Return t"e "our as an )nte$er from a Date a*ue& )sDate,a*ue. +oo*ean )s t"is ,a*ue, conerted to a strin$. a date> Minute,date. )nte$er Return t"e minute as an )nte$er from a Date a*ue& Mont",date. )nte$er Return t"e mont" as an )nte$er from a Date a*ue& Mont"4ame Strin$ Return t"e name of t"e mont" based on an inte$er ar$ument ,1912.& 4o%,. Date Return t"e current date and time as a Date ob/ect& Second,date. )nte$er Return t"e seconds as an )nte$er from a Date a*ue& Time,. Date Return t"e time as a Strin$ in t"e format EE:MM:SS& Timer,. Date Return t"e number of seconds since midni$"t as a Date& #ast t"is to a Lon$& TimeSeria*,"our, min, sec. Date #reate a date from component pieces: Eours, Minutes, Seconds& TimeOa*ue,DEE:MM:SSF. Date 23tract t"e time a*ue from a date7 a pure time a*ue bet%een 0 and 1& ;ee(Day,date. )nte$er Return t"e inte$er 1 t"rou$" M correspondin$ to Sunday t"rou$" Saturday& ;ee(day4ame Strin$ Return t"e day of t"e %ee( based on an inte$er ar$ument ,19M.& 6ear,date. )nte$er Return t"e year as an )nte$er from a Date a*ue& 122 #.1. %etrieve the current date and time 11o +asic "as functions to determine t"e current date and time: Date, Time, and 4o% ,described in Tab*e 3A.& T"e Date and Time functions return a strin$ %it" t"e current date and time, respectie*y& T"e strin$s are formatted based on t"e current *oca*e ,Tools Options !anguage Settings !anguages7 and t"en set t"e *oca*e.& T"e 4o% command returns a Date ob/ect t"at contains bot" t"e current date and t"e current time& TIP 4o% returns a Date ob/ect, %"ic" interna**y is stored as a Doub*e& T"e functions Date and Time bot" return a Strin$& Table 35. #ate and time functions in OOo !asic. !nction Description Date Return t"e current date as a Strin$& 4o% Return t"e current date and time as a Date ob/ect& Time Return t"e current time as a Strin$& 'rintin$ t"e date and time is easy& Print -ate Print 3i!e Print Ho* #.2. "ates4 numbers4 and strings 11o +asic reco$niCes dates in t%o different strin$ formats& T"e obious format is set by t"e *oca*e& A *ess obious format is t"e )S1 @601 date format& Strin$ formats are a*%ays assumed to be in a *oca*e9specific format e3cept for routines specific to t"e )S1 @601 format& Ar$uments passed to t"e date and time functions are conerted to an appropriate type if possib*e& As a resu*t, most of t"e functions in Tab*e 36 accept strin$, numeric, and date ar$uments& Table 36. #ate and string conversion functions !nction Description #Date #onert a number or strin$ to a date& DateOa*ue #onert a formatted strin$ from December 1, 1A@2 t"rou$" December 31, BBBB to a Date a*ue t"at contains no time& #Date0rom)so #onert to a date from an )S1 @601 date representation& #DateTo)so #onert a date to an )S1 @601 date representation& )sDate )s t"is strin$ a proper*y formatted date> 5se t"e )sDate function to test if a strin$ contains a a*id date& T"e ar$ument is a*%ays conerted to a strin$ before it is used, so a numeric ar$ument %i** return 0a*se& T"e )sDate function tests more t"an /ust synta3 L it c"ec(s to see if t"e strin$ contains a a*id date& 0or e3amp*e, D02-2B-2003F fai*s because 0ebruary 2003 contains on*y 2@ days& T"e same a*idity c"ec( is not performed on t"e time component of t"e strin$ ,see Listin$ 102 and Listin$ 103.& 123 Listing 102. "s#ate verifies that a string contains a valid date. Print I#-ateB"-ece!ber >= ><Q' ':>%:?'"C )3rue Print I#-ateB"':>%:?'"C )3rue Print I#-ateB">'+>+><Q'"C )3rue Print I#-ateBHo*C )3rue Print I#-ateB"'A:A>:>>'"C )3rue: >>' #econd# and A> !inute#KKK Print I#-ateB3rueC )"al#e: Con:ert# to #trin $ir#t Print I#-ateB%'AQA&''%%'C )"al#e: Con:ert# to #trin $ir#t Print I#-ateB"7'+'@+'77%"C )"al#e: Onl. 'Q da.# in "ebruar. 7% T"e apparent inconsistency %it" t"e )sDate function is t"at D02-2B-2003F is an ina*id date but D26:61:112F is a*id& ;it" time a*ues, if a section of t"e time is too *ar$e, it is simp*y added to t"e ne3t section& 0or e3amp*e, 61 minutes is one "our and one minute& A$ain, 112 seconds adds one minute and A2 seconds to t"e fina* computed time a*ue& T"is is demonstrated in Listin$ 103 and s"o%n in 0i$ure !A& 4otice t"at, in *ine t%o, 30 "ours becomes si3 "ours and t"e day is incremented by one& Listing 103. /onverting time is strange. Sub Exa!ple3i!eCon:er#ion# On Error Jo3o Oop#: -i! -ate#BC -i! i A# Inteer -i! # A# Strin -ate#BC 6 Arra.B">+>+> 77:77:77 "= ">+>+> '':?7:77 "= ">+>+> %7:?7:77 "=5 ">+>+> %7:>77:77 "= ">+>+> %7:>77:>77"C "or i 6 ,BoundB-ate#BCC 3o 0BoundB-ate#BCC # 6 # 4 CStrBiC 4 " " 4 -ate#BiC 4 " 6D " # 6 # 4 C-ateB-ate#BiCC # 6 # 4 CHRFB>7C Hext M#Box #= 7= "Strane 3i!e Oalue#" Exit Sub Oop#: # 6 # 4 " Error" Re#u!e Hext End Sub Figure 45. 'hat appear to be invalid times are valid. Apart from t"e stran$e be"aior %it" respect to time, dates and times are conerted %it" no prob*ems e3cept for ina*id dates durin$ t"e s(ip from t"e Ku*ian to t"e Jre$orian ca*endar& 124 #.3. .ocale formatted dates 5se t"e #Date function to conert a strin$ or number to a date& T"e #Date function performs a *oca*e9 specific conersion inc*udin$ t"e time component& T"e DateOa*ue function remoes t"e time portion by remoin$ t"e fractiona* portion of t"e under*yin$ Doub*e& T"is causes une3pected resu*ts %it" some date a*ues& See Listin$ 10!& Listing 104. /#ate returns a date and a timeE #ate3alue removes the time. Print Ho* )$or exa!ple= 7Q+>A+'77% >A:7<:<% Print -ateOalueBHo*C )$or exa!ple= 7Q+>A+'77% T"e defau*t *an$ua$e on t"e computers t"at ) use is D2n$*is" 5SA&F To use a different *oca*e, se*ect Tools Options !anguage Settings !anguages to open t"e Lan$ua$es tab on t"e 1ptions dia*o$& T"en c"oose a *oca*e& To test different *oca*es, use t"e code in Listin$ 10A& Listing 105. 9rint date4related information dependent on current locale. -i! d A# -ate d 6 C-ateB">+'+%"C )Pou can u#e >&'&% or >+'+% reardle## o$ locale Print d )Print# locale #peci$ic Print PearBdC Print Mont(BdC Print -a.BdC ) ran t"e code in Listin$ 10A usin$ four different *oca*es: 2n$*is" 5SA, 2n$*is" 5<, 0renc" 0rance, and Jerman Jermany& T"e resu*ts are s"o%n in Tab*e 3M& T"e format used to print a date is *oca*e9specific, as you can see in t"e Jermany co*umn& T"e #Date function accepts dates formatted usin$ t"e period as a separator, een for t"e 5SA *oca*e& )nitia*iCin$ d usin$ #Date,Z1&2&3Z. rat"er t"an #Date,Z1-2-3Z. does not c"an$e t"e output in Tab*e 3M& Table 37. Locale affects the date. Code *S$ *K !rance -ermany Print d D01-02-2003F D01-02-2003F D01-02-2003F D01&02&2003F Print PearBdC 2003 2003 2003 2003 Print Mont(BdC 1 2 2 2 Print -a.BdC 2 1 1 1 #.4. !/O &#+1 dates T"e )nternationa* Standard )S1 @601 specifies t"e numeric representations of date and time& T"is standard notation "e*ps to aoid confusion in internationa* communication caused by numerous different notations, and increases t"e portabi*ity of computer user interfaces& )n addition, t"ese formats "ae seera* important adanta$es for computer usa$e compared to ot"er traditiona* date and time notations& T"e internationa* standard date notation is 66669MM9DD, %"ic" is a four9di$it year fo**o%ed by a t%o9 di$it mont" and a t%o9di$it day& T"e year is based on t"e usua* Jre$orian ca*endar& 0or e3amp*e, Marc" @, 2003 is %ritten as 200390390@& T"e separators are optiona*, so you cou*d a*so e3press t"e date as 2003030@7 t"is is t"e format returned by #DateTo)S1& See Listin$ 121& 1t"er components of t"e date format are beyond t"e scope of t"is boo(& T"e )S1 format "as seera* adanta$es: 125 ISO 8601 is easily comparable and sortable with a string comparison. This is why I prefer this format when appending dates to file names. ISO 8601 is easily readable and writable by software because no translation to and from month names is required. ISO 8601 is language and locale independent. There is no ambiguity compared to other date formats. For example, in other formats, theres often a question as to whether the month or the day is listed first. The convention in Europe, for example, would express the fifth day of June in 2003 as 5/6/03, while in the United States and North and South America, generally the same date would commonly be expressed as 6/5/03. The opportunity for confusion is great, especially around the time bills are due near the beginning of each month! This is illustrated by the Month and Day row entries shown in Table 37. Listing 106 Converts the same data to the appropriate ISO 8601 string . Listing 106. /onvert to "*O 0GC(. Sub Exa!pleC-ate3oISO Print C-ate3oISOB">'+%7+>Q@@"C )>Q@@>'%7 Print C-ate3oISOBHo*C )'7>77Q>A Print C-ate"ro!ISOB"'77%7%>%"C )7%+>%+'77% End Sub #.. 3roblems with dates Date and time information usua**y re8uires *itt*e t"ou$"t& Kust use t"e date and time functions and t"e correct e3pected resu*ts are produced& 5nfortunate*y, t"is fa**s apart as your dates start moin$ bac( in time& T"ree specific dates and times are of interest for eac" function: December 30, 1@BB at 00:00:00, %"en t"e interna* Date representation is a numerica* Cero& Any pure time a*ue ,%it"out a date component. appears to occur on December 30, 1@BB& 1ctober !, 1A@2, %"en t"e Ku*ian ca*endar %as dropped& 1ctober 1A,1A@2, %"en t"e Jre$orian ca*endar be$ins& Oarious ca*endar systems "ae been used at different times and p*aces around t"e %or*d& T"e Jre$orian ca*endar, on %"ic" 11o +asic is based, is used a*most uniersa**y& T"e predecessor to t"e Jre$orian ca*endar is t"e Ku*ian ca*endar& T"e t%o ca*endars are a*most identica*, differin$ on*y in "o% t"ey "and*e *eap years& T"e Ku*ian ca*endar "as a *eap year eery fourt" year, %"i*e t"e Jre$orian ca*endar "as a *eap year eery fourt" year e3cept century years t"at arenGt e3act*y diisib*e by !00& T"e c"an$e from t"e Ku*ian ca*endar to t"e Jre$orian ca*endar occurred in 1ctober of 1A@2, based on a sc"eme instituted by 'ope Jre$ory I)))& T"e Ku*ian ca*endar %as used t"rou$" 1ctober !, 1A@2, at %"ic" point 10 days %ere s(ipped and it became 1ctober 1A, 1A@2& Typica**y, for dates on or before ! 1ctober 1A@2, t"e Ku*ian ca*endar is used7 for dates on or after 1A 1ctober 1A@2, t"e Jre$orian ca*endar is used& T"us, t"ere is a 109day $ap in ca*endar dates, but no discontinuity in Ku*ian dates or days of t"e %ee(& Astronomers, "o%eer, typica**y use Ku*ian dates because t"ey donGt "ae a 109day $ap7 discontinuous dates do not typica**y %or( %e** in numerica* ca*cu*ations& As seen in Listin$ 116, Dates are printed based on t"e Jre$orian ca*endar, but %"en t"e component parts are e3tracted, t"ey are based on t"e Ku*ian date& 126 T"e )S1 @601 standard, introduced to standardiCe t"e e3c"an$e of date and time9re*ated data, introduces a comp*ication& T"e standard states t"at eery date must be consecutie, so c"an$in$ to t"e Ku*ian ca*endar io*ates t"e standard ,because at t"e s%itc"oer date, t"e dates %ou*d not be consecutie.& T"e fo**o%in$ e3amp*es demonstrate conertin$ a date - time %it" #Date, DateOa*ue, and #DateTo)S1& T"e DateOa*ue operates on t"e a*ue returned from #Date& T"e standard a*ues %or( as e3pected ,see Tab*e 3@.& Kanuary 1, 2001 is 36@B2 days after December 30, 1@BB, and Kanuary 1, 1B00 is 2 days after December 30, 1@BB& Table 38. #ates after Hanuary () (1CC work fine. Date . Time DateVale CDate CDateToISO 01-01-1B00 12:00 AM 2 2 1B000101 01-01-1B00 06:00 AM 2 2&2A 1B000101 01-02-1B00 12:00 AM 3 3 1B000102 01-02-1B00 06:00 AM 3 3&2A 1B000102 01-01-2001 12:00 AM 36@B2 36@B2 20010101 01-01-2001 06:00 AM 36@B2 36@B2&2A 20010101 01-01-2001 12:00 'M 36@B2 36@B2&A 20010101 Oa*ues near December 30, 1@BB reea*s some bu$s& 1. DateOa*ue $enerates an error on December 30, 1@BB& T"is may be intentiona* so t"at DateOa*ue $enerates an error on a pure time a*ue, %"ic" cannot be distin$uis"ed from a date-time on December 30, 1@BB& 2. DateOa*ue returns an incorrect ans%er for a** dates before December 30, 1@BB for a** time a*ues ot"er t"an midni$"t& 3. #DateTo)S1 returns an incorrect ans%er for a** dates before Kanuary 1, 1B00 for a** time a*ues ot"er t"an midni$"t& !. #DateTo)S1 "as an e3ceptiona* fai*ure on on December 31, 1@BB for times after midni$"t& Table 39. #ates near #ecember FC) (011 are a problem. Date . Time DateVale CDate CDateToISO 12-2@-1@BB 12:00 AM 92 92 1@BB122@ 12-2@-1@BB 06:00 AM 91 91&MA 1@BB122B 12-2B-1@BB 12:00 AM 91 91 1@BB122B 12-2B-1@BB 06:00 AM 2rror 90&MA 1@BB1230 12-30-1@BB 12:00 AM 2rror 0 1@BB1230 12-30-1@BB 06:00 AM 2rror 0&2A 1@BB1231 12-31-1@BB 12:00 AM 1 1 1@BB1231 12-31-1@BB 06:00 AM 1 1&2A 1@BB1201 127 'ure*y ina*id dates $enerate an error as t"ey s"ou*d7 for e3amp*e, dates bet%een t"e end of t"e Ku*ian ca*endar and t"e start of t"e Jre$orian ca*endar& )ssues %it" DateOa*ue and #dateTo)S1 continue %"en t"e time is not midni$"t& Table 40. Nothing special about dates near the Hulian , <regorian calendar change. Date . Time DateVale CDate CDateToISO 10-0!-1A@2 12:00 AM 911A@AB 911A@AB 1A@2101! 10-0!-1A@2 06:00 AM 911A@A@ 911A@A@&MA 1A@2101A 10-0A-1A@2 00:00:00 2rror 2rror 2rror 10-0A-1A@2 06:00:00 2rror 2rror 2rror 10-1A-1A@2 12:00 AM 911A@A@ 911A@A@ 1A@2101A 10-1A-1A@2 06:00 AM 911A@AM 911A@AM&MA 1A@21016 Listin$ 10M Demonstrates t"e issues conertin$ to date - time a*ues& Listing 107. #emonstrate odd date behavior. Sub Odd-ate3i!eBe(a:ior On Error Jo3o Oop#: -i! -ate#BC -i! i A# Inteer -i! # A# Strin -ate#BC 6 Arra.B">7+7?+><Q' 77:77:77"= ">7+7?+><Q' 7A:77:77"= 5 ">7+7<+><Q' 77:77:77"= ">7+7<+><Q' 7A:77:77"= 5 ">7+><+><Q' 77:77:77"= ">7+><+><Q' 7A:77:77"= 5 ">'+'Q+>Q@@ 77:77:77"= ">'+'Q+>Q@@ 7A:77:77"= 5 ">'+'@+>Q@@ 77:77:77"= ">'+'@+>Q@@ 7A:77:77"= 5 ">'+%7+>Q@@ 77:77:77"= ">'+%7+>Q@@ 7A:77:77"= 5 ">'+%>+>Q@@ 77:77:77"= ">'+%>+>Q@@ 7A:77:77"= 5 "7>+7>+>@77 77:77:77"= "7>+7>+>@77 7A:77:77"= 5 "7>+7'+>@77 77:77:77"= "7>+7'+>@77 7A:77:77"= 5 ">+>+> 77:77:77"= ">+>+> 7A:77:77"= ">+>+> >':77:77" 5 C "or i 6 ,BoundB-ate#BCC 3o 0BoundB-ate#BCC # 6 # 4 CStrBiC 4 " " 4 -ate#BiC 4 " 6D " # 6 # 4 C-blB-ateOalueBC-ateB-ate#BiCCCC # 6 # 4 " 6D " # 6 # 4 C-blBC-ateB-ate#BiCCC 4 " 6D " 4 C-ate3oISOB-ate#BiCC # 6 # 4 CHRFB>7C Hext M#Box #= 7= "Strane 3i!e Oalue#" Exit Sub Oop#: # 6 # 4 " Error" Re#u!e Hext End Sub 128 Figure 46. *ome #ate values convert poorly. TIP DateOa*ue fai*s %it" a run9time error for dates %it" a Cero day component, suc" as DateOa*ue,#Date,Z12-30-1@BB 06:00:00Z..& Dates before t"is return an incorrect a*ue& ) mi$"t a*so ar$ue t"at dates and times t"at use t"e same data type is a bu$, because it isnGt possib*e to distin$uis" bet%een a time and a date a*ue for t"e day 12-30-1@BB& DateOa*ue truncates t"e decima* portion of t"e number to determine t"e date& T"e )nt function, "o%eer, a*%ays rounds to%ard ne$atie infinity, %"ic" produces t"e correct resu*t& See Listin$ 10@& Remember t"at t"e )nt function rounds to%ards ne$atie infinity and returns a doub*e& Listing 108. Round toward negative infinity and convert it to a #ate. "unction Sa$e-ateOalueB:C -ate Sa$e-ateOalue 6 C-ateBIntBC-ateB:CCC End "unction SafeDateOa*ue in Listin$ 10@ corrects t"e %ron$ be"aior& Listin$ 10B repeats Listin$ 10M usin$ SafeDateOa*ue, so no% t"e correct a*ues are obtained& Listing 109. Round toward negative infinity and convert it to a #ate. Sub Sa$e-ate3i!eBe(a:ior On Error Jo3o Oop#: -i! -ate#BC -i! i A# Inteer -i! # A# Strin -ate#BC 6 Arra.B">7+7?+><Q' 77:77:77"= ">7+7?+><Q' 7A:77:77"= 5 ">7+7<+><Q' 77:77:77"= ">7+7<+><Q' 7A:77:77"= 5 ">7+><+><Q' 77:77:77"= ">7+><+><Q' 7A:77:77"= 5 129 ">'+'Q+>Q@@ 77:77:77"= ">'+'Q+>Q@@ 7A:77:77"= 5 ">'+'@+>Q@@ 77:77:77"= ">'+'@+>Q@@ 7A:77:77"= 5 ">'+%7+>Q@@ 77:77:77"= ">'+%7+>Q@@ 7A:77:77"= 5 ">'+%>+>Q@@ 77:77:77"= ">'+%>+>Q@@ 7A:77:77"= 5 "7>+7>+>@77 77:77:77"= "7>+7>+>@77 7A:77:77"= 5 "7>+7'+>@77 77:77:77"= "7>+7'+>@77 7A:77:77"= 5 ">+>+> 77:77:77"= ">+>+> 7A:77:77"= ">+>+> >':77:77" 5 C "or i 6 ,BoundB-ate#BCC 3o 0BoundB-ate#BCC # 6 # 4 CStrBiC 4 " " 4 -ate#BiC 4 " 6D " # 6 # 4 C-blBSa$e-ateOalueBC-ateB-ate#BiCCCC # 6 # 4 " 6D " # 6 # 4 C-blBC-ateB-ate#BiCCC 4 " 6D " 4 C-ate3oISOBSa$e-ateOalueB-ate#BiCCC # 6 # 4 CHRFB>7C Hext M#Box #= 7= "Strane 3i!e Oalue#" Exit Sub Oop#: # 6 # 4 " Error" Re#u!e Hext End Sub #.#. E:tract each part of a date Date ob/ects are based on f*oatin$9point Doub*e numbers so mat"ematica* operations and comparisons can be used %it" Date ob/ects& T"e Date and Time functions, "o%eer, return strin$s, so t"ey canGt be used in t"is capacity& 11o +asic proides functions to retriee t"e indiidua* pieces of a date ,see Tab*e !1.& Table 41. #ate component e.traction functions in OOo !asic. !nction Description 6ear,date. Return t"e year portion of a Date a*ue as an )nte$er& Mont",date. Return t"e mont" portion of a Date a*ue as an )nte$er& Day,date. Return t"e day portion of a Date a*ue as an )nte$er& Eour,date. Return t"e "our portion of a Date a*ue as an )nte$er& Minute,date. Return t"e minutes portion of a Date a*ue as an )nte$er& Second,date. Return t"e seconds portion of a Date a*ue as an )nte$er& ;ee(Day,date. Return an inte$er a*ue from 1 t"rou$" M, correspondin$ to t"e day of t"e %ee(, Sunday t"rou$" Saturday& T"e functions in Tab*e !1 a** e3pect a Date ob/ect, %"ic" is interna**y based on a Doub*e& 11o +asic automatica**y conerts t"e ar$ument to t"e appropriate type if possib*e& T"e Date function returns a strin$ %it" no time information ,eeryt"in$ to t"e ri$"t of t"e decima* is Cero. so t"ere is no time information for t"e Eour, Minute, and Second functions to return& Simi*ar*y, t"e Time function returns a strin$ %it" no date information ,eeryt"in$ to t"e *eft of t"e decima* is Cero., %"ic" corresponds to December 30, 1@BB& Print "Pear 6 " 4 PearB7&''%C )>Q@@= 7 $or date !ean# -ece!ber %7= >Q@@ Print "Pear 6 " 4 PearB3i!eC )>Q@@= Ho date in$or!ation $ro! 3i!eBC Print "Mont( 6 " 4 Mont(B-ateC )Current !ont( Print "-a. 6 " 4 -a.BHo*C )Ho* contain# date and ti!e in$or!ation 130 Print "Hour 6 " 4 HourB-ateC )7= Ho ti!e in$or!ation $ro! -ateBC Print "Minute# 6 " 4 MinuteBHo*C )Current !inute# Print "Second# 6 " 4 SecondB3i!eC )Current #econd# 5se t"e ;ee(Day function to determine t"e day of t"e %ee(& Some ca*endars start on Monday and some start on Sunday7 11o +asic assumes t"at Sunday is t"e first day of t"e %ee(& See Listin$ 110& Listing 110. #etermine the day of the week. Sub Exa!pleWee1-a.3ext Print "3oda. i# " 4 Wee1-a.3extB-ateC End Sub "unction Wee1-a.3extBdC A# Strin Select Ca#e Wee1-a.BdC ca#e > Wee1-a.3ext6"Sunda." ca#e ' Wee1-a.3ext6"Monda." ca#e % Wee1-a.3ext6"3ue#da." ca#e ? Wee1-a.3ext6"Wedne#da." ca#e < Wee1-a.3ext6"3(ur#da." ca#e A Wee1-a.3ext6""rida." ca#e 2 Wee1-a.3ext6"Saturda." End Select End "unction T"e Date'art function a**o%s you to pass a strin$ e3pression t"at determines t"e part of t"e date of interest7 as e3pressed as a strin$ as t"e first ar$ument& Runnin$ Date'art %it" September 1A, 2010 at 1B:13:20 yie*ds t"e resu*ts s"o%n in Tab*e !2& Table 42. #ate9art string specifier. !ormat Description &eslt yyyy 0our9di$it year 2010 8 _uarter 3 m Mont" B y Day of year 2A@ % ;ee(day ! %% ;ee( of year 3@ d Day of Mont" 1A " Eour 1B n Minute 13 s Second 20 131 Listing 111. Use #ate9art to e.tract components of a date. Sub Exa!ple-atePart -i! 3(e-ate A# -ate -i! $ -i! i A# Inteer -i! #F 3(e-ate 6 Ho* $ 6 Arra.B"...."= ";"= "!"= "."= "*"= "**"= "d"= "("= "n"= "#"C # 6 "Ho* 6 " 4 3(e-ate 4 CHRFB>7C "or i 6 ,BoundB$C 3o 0BoundB$C # 6 # 4 "-atePartB" 4 $BiC 4 "= " 4 3(e-ate 4 "C 6 " 4 5 -atePartB$BiC= 3(e-ateC 4 CHRFB>7C Hext M#Box # End Sub TIP A Jerman user c*aimed t"at Date'art fai*ed if it %ere not run %it" #ompatibi*ityMode,True.& Date'art supports an optiona* t"ird ar$ument t"at specifies %"en a %ee( is assumed to start ,see Tab*e !3.& T"e optiona* fourt" ar$ument, specifies %"en t"e year is assumed to start& T"e t"ird and fourt" ar$uments affect t"in$s suc" as t"e %ee( of t"e year, but %i** not affect ot"er a*ues suc" as t"e day of t"e year& Table 43. #ate9art week start and year start values. Vale /ee0 Start Description 1ear Start Description 0 5se system defau*t a*ue& 5se system defau*t a*ue& 1 Sunday ,defau*t. ;ee( 1 is t"e %ee( %it" Kanuary first ,defau*t.& 2 Monday ;ee( 1 is t"e first %ee( containin$ four or more days of t"at year& 3 Tuesday ;ee( 1 is t"e first %ee( containin$ on*y days of t"e ne% year& ! ;ednesday A T"ursday 6 0riday M Saturday After e3tractin$ portions of t"e date, it is usefu* to print t"e a*ues in an easy to read format& 5se Mont"4ame to conert t"e mont" number to t"e mont" name& Settin$ t"e optiona* second ar$ument to True causes t"e name to be abbreiated& Listing 112. 9rint the Month as a string. Sub Exa!pleMont(Ha!e -i! iG -i! #F "or i 6 > 3o >' # 6 # 4 i 4 " 6 " 4 Mont(Ha!eBi= 3rueC 4 " 6 " 4 Mont(Ha!eBiC 4 CHRFB>7C Hext M#Box #= 7= "Mont(Ha!e" End Sub 132
Figure 47. Use MonthName and 'eek#ayName to convert an integer into the name. ;ee(Day4ame, simi*ar to Mont"name, returns t"e day of t"e %ee( as a strin$& 1dd*y, ;ee(Day4ame on*y %or(s if compatibi*ity mode is on& ;ee(Day4ame a*so supports a t"ird ar$ument, %"ic" specifies t"e day t"at t"e %ee( be$ins ,see Tab*e !!.& Listing 113. 9rint the day of the week as a string. Sub Exa!pleWee1-a.Ha!e -i! iG -i! #F Co!patibilit.ModeB3rueC "or i 6 > 3o 2 # 6 # 4 i 4 " 6 " 4 Wee1-a.Ha!eBi= 3rueC 4 " 6 " 4 Wee1-a.Ha!eBiC 4 CHRFB>7C Hext M#Box #= 7= "Wee1-a.Ha!e" End Sub Table 44. hird argument for 'eek#ayName to specify the first day of the week. Vale Description 0 5se 4ationa* Lan$ua$e Support A') settin$& 1 Sunday ,defau*t. 2 Monday 3 Tuesday ! ;ednesday A T"ursday 6 0riday M Saturday 5se t"e ;ee(Day function to e3tract t"e day of t"e %ee( based on a date& T"e optiona* second ar$ument specifies t"e day on %"ic" t"e %ee( starts7 t"e a*ues are t"e same as for ;ee(Day4ame ,see Tab*e !!. e3cept t"at 0 corresponds to t"e system defau*t settin$& Print Wee1-a.BHo*C 133 5se 0ormatDateTime to disp*ay t"e date and time in a common format& T"e first ar$ument is t"e date& T"e second ar$ument is optiona* and specifies "o% t"e date s"ou*d be formatted ,see Tab*e !A.& Listing 114. +ormat a date,time string. Sub Exa!ple"or!at-ate3i!e -i! #F= iG -i! d A# -ate d 6 Ho* Co!patibilit.ModeB3rueC # 6 ""or!at-ate3i!eBdC 6 " 4 "or!at-ate3i!eBdC 4 CHRFB>7C "or i67 3o ? # 6 # 4 ""or!at-ate3i!eBd= " 4 i 4 "C 6 " 4 "or!at-ate3i!eBd= iC 4 CHRFB>7C Hext M#Box #= 7= ""or!at-ate3i!e" End Sub Figure 48. +ormat a date and time with +ormat#ateime. Table 45. *econd argument to +ormat#ateime specify format. Vale Description 0 Defau*t format %it" a s"ort date and and a *on$ time& 1 Lon$ date format %it" no time& 2 S"ort date format& 3 Time in t"e computerVs re$iona* settin$s& ! 2! "our "ours and minutes as "":mm& #.$. "ate arithmetic )nterna**y, a date is represented as a f*oatin$ point number& T"e decima* portion represents t"e time, and t"e inte$er portion represents t"e date& T"e representation a**o%s mat"ematica* manipu*ation, but, it re8uires a bit of t"ou$"t7 for e3amp*e, add: 1 Add one day Ho* W > 1-2! Add one "our Ho* W >+'? 36A Add one year, but *eap years are a prob*em& 5se DateAdd to simp*ify t"e process& T"e t"ird ar$ument is t"e date& T"e first ar$ument ,see Tab*e !2. determines "o% t"e a*ue in t"e second ar$ument is interpreted& ) can repeat t"e *ist aboe as: 134 Print -ateAddB"d"= >= Ho*C )Add one da.& Print -ateAddB"("= >= Ho*C )Add one (our& Print -ateAddB"..."= >= Ho*C )Add one .ear& 5se DateDiff to determine t"e number of Dintera*sF bet%een t%o dates7 for e3amp*e, t"e number %ee(s bet%een t%o dates& T"e first ar$ument specifies t"e intera* to use ,see Tab*e !2.& T"e second ar$ument is t"e first date, and t"e t"ird ar$ument is t"e second date& T"e optiona* fourt" and fift" ar$uments specify t"e first day of t"e %ee( and t"e first %ee( of t"e year ,see Tab*e !3.& Print -ate-i$$B"...."= "7%+>%+>@A<"= -ateBHo*CC )Pear# $ro! Marc( >%= >@A< to no* Print -ate-i$$B"d"= "7%+>%+>@A<"= -ateBHo*CC )-a.# $ro! Marc( >%= >@A< to no* #.&. 2ssembling dates from components T"e functions Eour, Minute, Second, 6ear, Mont", and Day are used to brea( a date into parts& T"e functions DateSeria* and TimeSeria* are used to put t"e dates bac( to$et"er a$ain& T"e function DateSeria* creates a Date ob/ect from t"e year, mont", and day& T"e function TimeSeria* creates a Date ob/ect from t"e "ours, minutes, and seconds& Print -ateSerialB'77%= >7= >C )>7+7>+'77% Print 3i!eSerialB>%= ?= ?<C )>%:7?:?< T"e first ar$ument to t"e DateSeria* function is t"e year, t"e second ar$ument is t"e mont", and t"e fina* ar$ument is t"e day& )f t"e mont" or day arenGt a*id a*ues, a run9time error occurs& 6ear a*ues $reater t"an 100 are used direct*y& 6ear a*ues *ess t"an 100, "o%eer, "ae 1B00 added to t"em& T%o9di$it years are mapped to t"e years 1B00 and *ater ,see Listin$ 11A.& Listing 115. #ate*erial adds (1CC to years earlier than (CC. Sub Exa!ple-ateSerial On Error Joto OOPS -i! x -i! iG -i! #F x 6 Arra.B'77%= >7= >= 5 >Q@@= >'= %>= 5 >Q@@= >'= %7= 5 >Q@@= >'= '@= 5 >Q@@= >'= 'Q= 5 @@= >7= >= 5 %= >7= >= 5 7= >= >= 5 9%= >7= >= 5 9@@= >7= >= 5 9>77= >7= >= 5 9>Q77= >7= >= 5 9>Q7>= >7= >C i 6 ,BoundBxC -o W(ile i E 0BoundBxC # 6 # 4 -ateSerialBxBiC= xBiW>C= xBiW'CC # 6 # 4 " E6 B" 4 3oStrWit(,enBxBiC= ?C 4 "=" # 6 # 4 3oStrWit(,enBxBiW>C= %C 4 "=" # 6 # 4 3oStrWit(,enBxBiW'C= %C 4 "C" # 6 # 4 CHRFB>7C 135 i 6 i W % ,oop M#Box # Exit Sub OOPS: # 6 # 4 ERROR Re#u!e Hext End Sub Figure 49. #ate*erial creates a date from a year) month) and day value. TIP DateSeria* adds 1B00 to years ear*ier t"an 100, inc*udin$ ne$atie years& An error is $enerated if t"e resu*tin$ year is sti** *o%er t"an 100& T"is a**o%s years from 91@00 t"rou$" 91, %"ic" s"ou*d probab*y be an error& T"e Date type is ab*e to "and*e dates prior to 1-1-00, but obious*y, DateSeria* cannot& Dates are printed based on t"e Jre$orian ca*endar, but %"en t"e component parts are e3tracted, t"ey are based on t"e Ku*ian date& Listing 116. #ate*erial accepts <regorian dates before (C,(I,(I0=. Print -ateSerialB><Q'= >7= ><C )>7+><+><Q' Print -ateSerialB><Q'= >7= >?C )>7+7?+><Q' Print -a.B-ateSerialB><Q'= >7= >?CC )>? #.(. Measuring elapsed time over short intervals 6ou can obtain simp*e e*apsed time by subtractin$ t%o date a*ues& 0or e3amp*e, #Ln$,4o% 9 #Date,Z1-1-2000Z.. determines t"e number of days e*apsed since Kanuary 1, 2000& 11o +asic supports returnin$ e*apsed time as t"e number of seconds ,Timer. and as t"e number of system tic(s ,JetSystemTic(s.& See Tab*e !6& )nterna**y, computers "ae a system timer t"at adances at a certain rate7 t"e rate is "ard%are dependent& 1n )nte*9based computers t"is a*ue is 1-1M t" of a second& 2ac" time t"at t"e timer adances by 1, itGs ca**ed a Dsystem tic(&F T"e number returned by JetSystemTic(s is a*%ays based on mi**iseconds, een if it re*ies on a *ess accurate c*oc(& 136 Table 46. $lapsed time functions in OOo !asic. !nction Description JetSystemTic(s Return t"e number of system tic(s as a Lon$& T"e reported time is a*%ays in mi**iseconds, een if t"e under*yin$ timer is *ess accurate& Timer Return t"e number of seconds since midni$"t as a Date& #ast t"is to a Lon$& 5se JetSystemTic(s to $et t"e system9dependent number of system timer tic(s& T"is a*ue is typica**y used to time interna* operations because it "as "i$"er precision t"an t"e interna* time and date functions ,see Listin$ 11M and 0i$ure A0.& T"e return a*ue is a Lon$& Listing 117. Measuring elapsed time. Sub Exa!pleElap#ed3i!e -i! Start3ic1# A# ,on -i! End3ic1# A# ,on -i! Start3i!e A# -ate -i! End3i!e A# -ate Start3ic1# 6 JetS.#te!3ic1#BC Start3i!e 6 3i!er WaitB'77C )Pau#e execution $or 7&' #econd# End3ic1# 6 JetS.#te!3ic1#BC End3i!e 6 3i!er M#Box "A$ter *aitin '77 !# B7&' #econd#C= " 4 CHRFB>7C 45 "S.#te! tic1# 6 " 4 CStrBEnd3ic1# 9 Start3ic1#C 4 CHRFB>7C 45 "3i!e elap#ed 6 " 4 CStrBBEnd3i!e 9 Start3i!eCC 45 " #econd#" 4 CHRFB>7C= 7= "Elap#ed 3i!e" End Sub Figure 50. <et*ystemicks has better resolution than Now. Run t"e macro in Listin$ 11M a fe% times& Sometimes it s"o%s 0 seconds, and sometimes it s"o%s 1 second& T"e reso*ution is too *ar$e for s"ort duration items& T"e Timer function returns t"e number of seconds since midni$"t as a Date ob/ect& T"e prob*em %it" t"is is t"at at 10 seconds past midni$"t, t"e return a*ue is 10& T"e Date ob/ect, "o%eer, interprets 10 to mean D10 daysF& #ast t"e returned type direct*y to a numerica* type usin$ #Ln$ or #Db* to obtain t"e number of e*apsed seconds& -i! nSecond# A# ,on nSecond# 6 3i!er Print "Hu!ber o$ #econd# 6 " 4 nSecond# Print "Hu!ber o$ #econd# 6 " 4 ClnB3i!erC 137 TIP T"e Timer function returns t"e number of seconds since midni$"t& 5sin$ Timer to determine e*apsed time for spans t"at start before midni$"t and end after midni$"t produces use*ess resu*ts& #.1+. ,ow fast does this runE 2 real9world e:ampleF T"e $reatest common diisor ,J#D. of t%o inte$ers is t"e *ar$est inte$er t"at diides bot" inte$ers %it" no remainder& 0or e3amp*e, t"e J#D of 6 and B is 3& T"e numbers 1 and 3 bot" diide t"e numbers 6 and B ,see Tab*e !M.& T"e $reatest of t"ese is 3& Table 47. #ividing G and 1 by integers. %m2er 3 Divided By 4 5 Divided By 4 Bot6 Divide 1 6 B 6es 2 3 ! remainder 1 4o 3 2 3 6es ! 1 remainder 2 2 remainder 1 4o A 1 remainder 1 1 remainder ! 4o 6 1 1 remainder 3 4o M 0 remainder 6 1 remainder 2 4o @ 0 remainder 6 1 remainder 1 4o B 0 remainder 6 1 4o T"is e3amp*e be$ins around t"e year 300 +&#& %it" a $uy *iin$ in ancient Jreece named 2uc*id& 2uc*id %as a pretty smart $uy %"o %rote numerous boo(s, inc*udin$ #ata, concernin$ t"e so*ution of prob*ems t"rou$" $eometric ana*ysis, On #ivisions 6of +igures7, t"e Optics, t"e 9henomena, a paper on sp"erica* $eometry for astronomers, t"e $lements, a 139o*ume te3tboo( on $eometry, and seera* *ost %or(s on "i$"er $eometry& Eis impact on society %as "u$e& 1ne of "is most %e**9(no%n contributions is an e3treme*y efficient a*$orit"m to so*e t"e J#D prob*em& 4o% /ump a"ead a fe% t"ousand years to 1*iier +ietCer, %"o noticed t"at ) "ad an impractica**y s*o% a*$orit"m for so*in$ t"e J#D prob*em& 1*iier, %"o certain*y (no%s a *ot about t"ese t"in$s, %rote t"e macro in Listin$ 11@ t"at so*es t"e J#D prob*em usin$ 2uc*idGs a*$orit"m, and sent it to me& Listing 118. /alculate the </#. )Aut(or: Oli:ier Biet8er )e9!ail: oli:ier&biet8erIlapo#te&net )3(i# u#e# Euclid)# alorit(! and it i# :er. $a#tK "unction JC-5>BB.Oal x A# ,on= B.Oal . A# ,onC A# ,on -i! pcd A# ,on= te#t A# ,on ) We !u#t (a:e x D6 . and po#iti:e :alue# x6ab#BxC : .6ab#B.C I$ Bx E .C 3(en te#t 6 x : x 6 . : . 6 te#t End I$ I$ . 6 7 3(en Exit "unction ) Euclid #a.# &&&& pcd 6 . ) b. de$inition= PJC- i# t(e #!alle#t 138 te#t 6 x MO- . ) re!ainder a$ter di:i#ion -o W(ile Bte#tC ) W(ile not 7 pcd 6 te#t ) pcd i# t(e re!ainder x 6 . ) x=. and current pcd per!utation . 6 pcd te#t 6 x MO- . ) te#t aain ,oop JC-5> 6 pcd ) pcd i# t(e la#t non 7 re#t K Maic &&& End "unction )n $enera*, t"e best %ay to speed up a so*ution to a computationa* prob*em is by usin$ a better a*$orit"m& T"e a*$orit"m in Listin$ 11@ runs rou$"*y 1000 times faster t"an t"e routine t"at ) "ad& )f a faster a*$orit"m is not aai*ab*e, you can *oo( for ot"er %ays to improe performance& ,Sometimes itGs possib*e to inent a %"o**y ne% and improed a*$orit"m7 but t"at is 8uite a tric(T )f you succeed in dee*opin$ a ne%, faster a*$orit"m for a %ide*y (no%n prob*em, you may "ae $reat career potentia* as a professiona* mat"ematics or computer science professor&. T"e code in Listin$ 11@ is a*ready pretty *ean& T"ere isnGt a %"o*e *ot to remoe, but ) t"ou$"t t"at ) cou*d reduce t"e number of assi$nments ,see Listin$ 11B.& Listing 119. /alculate the </# 6another way7. "unction JC-5'BB.Oal x A# ,on= B.Oal . A# ,onC A# ,on -i! pcd A# ,on= te#t A# ,on ) We !u#t (a:e x D6 . and po#iti:e :alue# x6ab#BxC : .6ab#B.C I$ Bx E .C 3(en te#t 6 x : x 6 . : . 6 te#t End I$ I$ . 6 7 3(en Exit "unction -o W(ile B.C ) W(ile not 7 pcd 6 . ) pcd i# t(e re!ainder . 6 x MO- pcd ) te#t aain x 6 pcd ) x=. and current pcd per!utation ,oop JC-5' 6 pcd ) pcd i# t(e la#t non 7 re!ainder K Maic &&& End "unction 4o% t"e 8uestion is, %"ic" function is faster> )f you use a stop%atc" to see "o% 8uic(*y ) can b*in(, t"e resu*ts arenGt *i(e*y to be ery accurate because of measurement errors& )tGs muc" easier to te** me to b*in( as many times as ) can in four seconds or to time "o% 8uic(*y ) can b*in( A0 times& T"e code in Listin$ 120 does somet"in$ simi*ar& )t sits in a ti$"t *oop and ca**s eac" J#D imp*ementation A000 times& ) %ant to (no% "o% *on$ it ta(es to ca** t"e J#D function A000 times, but )Gm actua**y timin$ "o% *on$ it ta(es to *oop A000 times, $enerate 10,000 random numbers, and ca** t"e J#D function A000 times& To compensate for t"is, t"e amount of time re8uired to *oop A000 times and $enerate 10,000 random numbers is measured& TIP T"e test pro$ram ta(es a fe% seconds to run, so, be patient& Listing 120. ime the two different </# methods. Sub te#tJC- -i! nStart3ic1# A# ,on )W(en I #tarted ti!in -i! nEnd3ic1# A# ,on )W(en I #topped ti!in 139 -i! n,oop3ic1# A# ,on )3ic1# to do onl. t(e loop -i! nJC-5>53ic1# A# ,on )3ic1# $or JC-5> -i! nJC-5'53ic1# A# ,on )3ic1# $or JC-5' -i! nMinIt# A# ,on )Hu!ber o$ iteration# -i! x4= .4= i4= n4 )3e!porar. lon nu!ber# -i! #F )Hold t(e output #trin nMinIt# 6 <777 )Set t(e nu!ber o$ iteration# Rando!i8eB'C )Set to a 1no*n #tate nStart3ic1# 6 JetS.#te!3ic1#BC )Start tic1# "or i4 6 > 3o nMinIt# )Control t(e nu!ber o$ iteration# x 6 >7777 * RndBC )Jenerate t(e rando! data . 6 >7777 * RndBC )Jenerate t(e rando! data Hext nEnd3ic1# 6 JetS.#te!3ic1#BC n,oop3ic1# 6 nEnd3ic1# 9 nStart3ic1# Rando!i8eB'C )Set to a 1no*n #tate nStart3ic1# 6 JetS.#te!3ic1#BC )Start tic1# "or i4 6 > 3o nMinIt# )Control t(e nu!ber o$ iteration# x 6 >7777 * RndBC )Jenerate t(e rando! data . 6 >7777 * RndBC )Jenerate t(e rando! data JC-5>Bx= .C )-o t(e *or1 *e reall. care about Hext nEnd3ic1# 6 JetS.#te!3ic1#BC nJC-5>53ic1# 6 nEnd3ic1# 9 nStart3ic1# 9 n,oop3ic1# Rando!i8eB'C )Set to a 1no*n #tate nStart3ic1# 6 JetS.#te!3ic1#BC )Start tic1# "or i4 6 > 3o nMinIt# )Control t(e nu!ber o$ iteration# x 6 >7777 * RndBC )Jenerate t(e rando! data . 6 >7777 * RndBC )Jenerate t(e rando! data JC-5'Bx= .C )-o t(e *or1 *e reall. care about Hext nEnd3ic1# 6 JetS.#te!3ic1#BC nJC-5'53ic1# 6 nEnd3ic1# 9 nStart3ic1# 9 n,oop3ic1#
# 6 ",oopin " 4 nMinIt# 4 " iteration# ta1e# " 4 n,oop3ic1# 45 " tic1#" 4 CHRFB>7C 45 "Callin JC-5> ta1e# " 4 nJC-5>53ic1# 4 " tic1# or " 45 "or!atBnMinIt# * >77 +nJC-5>53ic1#= "LLLLL77&77"C 45 " Iteration# per #econd" 4 CHRFB>7C 45 "Callin JC-5' ta1e# " 4 nJC-5'53ic1# 4 " tic1# or " 45 "or!atBnMinIt# * >77 +nJC-5'53ic1#= "LLLLL77&77"C 45 " Iteration# per #econd" M#Box #= 7= "Co!pare JC-" End Sub 1ne prob*em in %ritin$ timin$ routines is determinin$ "o% many iterations to do& ) fre8uent*y use computers of different speeds& T"e resu*ts in 0i$ure A1 are based on my "ome computer runnin$ t"e macro in Listin$ 120& T"e macro in Listin$ 120 ma(es a specific number of iterations& Sometimes ) use a so*ution 140 t"at *imits t"e iterations based on time rat"er t"an number of iterations& T"is comp*icates t"e measurement of oer"ead and is *eft as an interestin$, but not oer*y difficu*t, prob*em for t"e reader&
Figure 51. he improvement is about (C percent. #.11. .ong time intervals and special dates )tGs easy to obtain e*apsed time oer *on$ intera*s by subtractin$ date a*ues& To determine precise dates and intera*s, you can creatie*y use t"e component pieces& 0or e3amp*e, $ien t"e date, %"at is t"e first day of t"e mont"> T"is is easy because t"e first day of eery mont" is day 1& 5se t"e functions 6ear and Mont" to e3tract t"e year and mont", and t"en reassemb*e t"e date usin$ DateSeria* and set t"e day to 1& T"e samp*e macro a*so ca**s ;ee(DayTe3t s"o%n in Listin$ 110& Listing 121. +irst day of the month. "unction "ir#t-a.O$Mont(Bd A# -ateC A# -ate "ir#t-a.O$Mont(BC 6 -ateSerialBPearBdC= Mont(BdC= >C End "unction Sub "ir#t-a.O$3(i#Mont(BC -i! d A# -ate d 6 "ir#t-a.O$Mont(BHo*BCC M#Box ""ir#t da. o$ t(i# !ont( B" 4 d 4 "C i# a " 4 Wee1-a.3extBdC End Sub To find t"e *ast day of a mont", find t"e first day of t"e ne3t mont" and t"en subtract 1 from t"e number& )f t"e current mont" is December, set t"e mont" to Kanuary and increment t"e year by 1& Listing 122. Last day of the month. "unction ,a#t-a.O$Mont(Bd A# -ateC A# -ate -i! nPear A# Inteer -i! nMont( A# Inteer nPear 6 PearBdC )Current .ear nMont( 6 Mont(BdC W > )Hext !ont(= unle## it *a# -ece!ber& I$ nMont( D >' 3(en )I$ it i# -ece!ber t(en nMont( i# no* >% nMont( 6 > )Roll t(e !ont( bac1 to > nPear 6 nPear W > )but incre!ent t(e .ear End I$ ,a#t-a.O$Mont( 6 C-ateB-ateSerialBnPear= nMont(= >C9>C End "unction Sub ,a#t-a.O$3(i#Mont(BC -i! d A# -ate d 6 ,a#t-a.O$Mont(BHo*BCC M#Box ",a#t da. o$ t(i# !ont( B" 4 d 4 "C i# a " 4 Wee1-a.3extBdC End Sub 141 )tGs easy to find t"e first day of t"e year for any $ien date7 itGs a*%ays Kanuary 1 of t"at year& 5se t"e 6ear function to obtain t"e current year and t"en set t"e day and mont" eac" e8ua* to 1& 0indin$ t"e *ast day of t"e year for any $ien date is on*y mar$ina**y more difficu*t& 0irst, find t"e first day of t"e ne3t year by incrementin$ t"e year by 1 and settin$ t"e mont" and day e8ua* to 1& Subtractin$ 1 from t"e first day of ne3t year proides t"e *ast day of t"is year& d 6 Ho* Print -ateSerialBPearBdC= >= >C )7>+7>+'77% Print C-ateB-ateSerialBPearBdCW>= >= >C9>C )>'+%>+'77% 5se t"e ;ee(Day function to find t"e first and *ast days of a %ee(& Subtract t"e day of t"e %ee( and add 1 to ta(e t"e date to Sunday at t"e be$innin$ of t"e current %ee(& d 6 -ate Print C-ateBC-blBdC 9 Wee1-a.BdC W >C )Q+>7+'77% i# a Sunda. Print C-ateBC-blBdC 9 Wee1-a.BdC W 2C )Q+>A+'77% i# a Saturda. 6ou can use simi*ar date manipu*ations to so*e ot"er date9re*ated prob*ems, suc" as determinin$ t"e %or( %ee(, "o% many days unti* your anniersary, or t"e a$e of a person in years, mont"s, and days& #.12. Conclusion A*t"ou$" dates in 1pen1ffice&or$ +asic are strai$"tfor%ard and easy to use, you must ta(e care %it" dates prior to 1ctober 1A, 1A@2& T"e /ump from t"e Jre$orian and Ku*ian ca*endar a*so may potentia**y cause une3pected prob*ems& A*so ta(e care %"en t"e under*yin$ imp*ementation, a Doub*e, becomes a ne$atie number7 t"is "appens around December 30, 1@BB& T"is c"apter a*so discussed met"ods of timin$ routines and determinin$ specific dates& 142 /. tring 6outines T"is c"apter introduces t"e subroutines and functions supported by 1pen1ffice&or$ +asic t"at are re*ated to strin$s& T"is inc*udes functions to manipu*ate strin$s, conert ot"er data types to strin$s, and to perform specia* formattin$& Te3t data is stored in strin$s as a se8uence of 169bit unsi$ned inte$er 5nicode ersion 2&0 a*ues& T"e 5nicode ;or*d%ide #"aracter Standard is a set of binary codes representin$ te3tua* or script c"aracters desi$ned because AS#)), t"e ori$ina* standard, can "and*e on*y 2A6 distinct c"aracters& T"e first 12@ c"aracters ,numbered 0 t"rou$" 12M. correspond to t"e *etters and symbo*s on a standard 5&S& (eyboard& T"e ne3t 12@ c"aracters ,numbered 12@ t"rou$" 2AA. consist of specia* c"aracters suc" as accent mar(s, Latin9 based c"aracters, and a fe% symbo*s& T"e remainin$ 6A,2@0 a*ues L of %"ic" on*y about 3!,000 are current*y used L are used for a %ide ariety of %or*d%ide te3t c"aracters, mat"ematica* symbo*s, accent mar(s ,diacritics., and tec"nica* symbo*s& 1pen1ffice&or$ "as a *ar$e number of functions t"at a**o% you to manipu*ate strin$s& T"ese strin$9 manipu*ation operations ran$e from conertin$ uppercase to *o%ercase ,or ice ersa. to se*ectin$ substrin$s out of a *on$er strin$& T"e functions *isted in Tab*e !@ are t"e strin$ functions coered in t"is c"apter& T"e functions *isted in Tab*e !B are re*ated to strin$s as %e** as eit"er numerica* or array manipu*ations7 t"ese are coered in ot"er c"apters& Table 48. hese string4related functions are covered in this section. !nction Description AS#,str. Return t"e inte$er AS#)) a*ue of t"e first c"aracter in t"e strin$& T"is supports 169bit 5nicode a*ues as %e**& #ER,n. #onert an AS#)) number to a c"aracter& #Str,ob/. #onert standard types to a strin$& 0ormat,ob/, format. 0ancy formattin$7 %or(s on*y for strin$s& Ee3,n. Return t"e "e3adecima* representation of a number as a strin$& )nStr,str, str. )nStr,start, str, str. )nStr,start, str, str, mode. Attempt to find strin$ 2 in strin$ 1& Returns 0 if not found and startin$ *ocation if it is found& T"e optiona* start ar$ument indicates %"ere to start *oo(in$& T"e defau*t a*ue for mode is 1 ,case9insensitie comparison.& Settin$ mode to 0 performs a case9sensitie comparison& )nStrRe,str, find, start, mode. Return t"e position of t"e first occurrence of one strin$ %it"in anot"er, startin$ from t"e ri$"t side of t"e strin$& 1n*y aai*ab*e %it" D1ption O+ASupport 1F& Start and mode are optiona*& Koin,s,.. Koin,s,., str. #oncatenate t"e array e*ements, separated by t"e optiona* strin$ de*imiter, and return t"e a*ue as a strin$& T"e defau*t de*imiter is a sin$*e space& )nerse of t"e Sp*it function& L#ase,str. Return a *o%ercase copy of t"e strin$& Left,str, n. Return t"e *eftmost n c"aracters from t"e strin$& Len,str. Return t"e *en$t" of t"e strin$& LSet str1 ? str2 Left9/ustify a strin$ into t"e space ta(en by anot"er strin$& LTrim,str. Return a copy of t"e strin$ %it" a** *eadin$ spaces remoed& Mid,str, start. Mid,str, start, *en. Mid,str, start, *en, str. Return t"e substrin$, startin$ at start& )f t"e *en$t" is omitted, t"e entire end of t"e strin$ is returned& )f t"e fina* strin$ ar$ument is inc*uded, t"is rep*aces t"e specified portion of t"e first strin$ %it" t"e *ast strin$& 1ct,n. Return t"e octa* representation of a number as a strin$& 143 !nction Description Rep*ace,str, find, rp*, start, count, mode. Searc" str for find and rep*ace it %it" rp*& 1ptiona**y, specify t"e start, count, and mode& Ri$"t,str, n. Return t"e ri$"tmost n c"aracters& RSet str1 ? str2 Ri$"t9/ustify a strin$ into t"e space ta(en by anot"er strin$& RTrim,str. Return a copy of t"e strin$ %it" a** trai*in$ spaces remoed& Space,n. Return a strin$ %it" t"e number of specified spaces& Sp*it,str. Sp*it,str, str. Sp*it a strin$ into an array based on an optiona* de*imiter& )nerse of t"e Koin function& Str,n. #onert a number to a strin$ %it" no *oca*iCation& Str#omp,s1, s2. Str#omp,s1, s2, mode. #ompare t%o strin$s returnin$ 91, 0, or 1 if t"e first strin$ is *ess t"an, e8ua* to, or $reater t"an t"e second in a*p"abetica* order& Set t"e optiona* t"ird ar$ument to Cero for a case9insensitie comparison& T"e defau*t is 1 for a case9sensitie comparison& Str#on,str, modec, *oca*d. #onerts a strin$ based on t"e mode: 1?upper, 2?*o%er, !?%ide, @?narro%, 16?<ata(ana, 32?Eira$ana, 6!?to unicode, 12@?from unicode& Strin$,n, c"ar. Strin$,n, ascii. Return a strin$ %it" a sin$*e c"aracter repeated mu*tip*e times& T"e first ar$ument is t"e number of times to repeat7 t"e second ar$ument is t"e c"aracter or AS#)) a*ue& StrReerse Reerse a strin$& Must use D1ption O+ASupport 1F, or precede it %it" #ompatibi*tyMode,True.& Trim,str. Return a copy of t"e strin$ %it" a** *eadin$ and trai*in$ spaces remoed& 5#ase,str. Return an uppercase copy of t"e strin$& Oa*,str. #onert a strin$ to a doub*e& T"is is ery to*erant to non9numeric te3t& T"e subroutines and functions re*ated to strin$ "and*in$ in 11o +asic are *isted in Tab*e !@& Some of t"ese functions ,see Tab*e !B. "ae in9dept" coera$e in ot"er c"apters, because t"ey are direct*y re*ated to t"e content in t"ose c"apters& T"ey are coered brief*y near t"e end of t"is c"apter, in t"e section tit*ed D#onertin$ data to a strin$&F Table 49. hese string4related functions are covered in other chapters. !nction Covered In Description Koin,s,.. Koin,s,., str. A& Array Routines #oncatenate t"e array e*ements, separated by t"e optiona* strin$ de*imiter, and return t"e a*ue as a strin$& Sp*it,str. Sp*it,str, str. A& Array Routines Sp*it a strin$ into an array based on an optiona* de*imiter& #Str,ob/. !& 4umerica* Routines #onert standard types to a strin$& Str,n. !& 4umerica* Routines #onert a number to a strin$ %it" no *oca*iCation& Ee3,n. !& 4umerica* Routines Return t"e "e3adecima* representation of a number as a strin$& 1ct,n. !& 4umerica* Routines Return t"e octa* representation of a number as a strin$& Oa*,str. !& 4umerica* Routines #onert a strin$ to a doub*e& T"is is ery to*erant to non9numeric te3t& 144 $.1. 2/C!! and )nicode values )n t"e ear*y days of computers t"ere %ere different types of data9processin$ e8uipment, and t"ere %as no common met"od of representin$ te3t& To a**eiate t"is prob*em, t"e American 4ationa* Standards )nstitute ,A4S). proposed t"e American Standard #ode for )nformation )nterc"an$e ,AS#)). in 1B63& T"e standard %as fina*iCed in 1B6@ as a mappin$ of 12@ c"aracters, numbers, punctuation, and contro* codes to t"e numbers from 0 to 12M ,see Tab*e A0.& T"e computer9minded reader may notice t"at t"is re8uires M bits and does not use an entire byte& Table 50. he original (=0 -*/"" characters. 3 1 2 # $ , . / 0 2 ) * C ( E + 3 NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF VT FF CR SO S 1 DLE DC1 DC2 DC3 DC4 NAK SYN ETB CAN EM SUB ESC FS GS RS US 2 SP ! # $ % & ' ( ) * + , - . / # 0 1 2 3 4 5 6 7 8 9 : ; < = > ? $ @ A B C D E F G H J K L M N O , P Q R S T U V W X Y z [ \ ] ^ _ . ` a b c d e f g h i j k l m n o / p q r s t u v w x y z { | } ~ DEL Tab*e A0 *ists t"e ori$ina* 12M AS#)) c"aracters& T"e top ro% and t"e *eft co*umn are used to identify t"e "e3adecima* AS#)) a*ue& 0or e3amp*e, t"e capita* *etter A "as an AS#)) a*ue of !1 in "e3adecima* format, and C "as an AS#)) a*ue of AA& )f more t"an one *etter occupies a bo3, t"at a*ue represents a specia* command c"aracter ,see Tab*e A1.& Some of t"ese specia* commands are desi$ned for communications, some for fi*e formats, and some are een aai*ab*e on t"e (eyboard& Table 51. Non4printable -*/"" characters. Hex DEC Sym2ol Description 00 0 45L 4u**, usua**y si$nifyin$ not"in$ 01 1 S1E Start of "eadin$ 02 2 STI Start of te3t 03 3 2TI 2nd of te3t 0! ! 21T 2nd of transmission L not t"e same as 2T+ 0A A 24_ 2n8uiry 06 6 A#< Ac(no%*ed$e L ) am "ere or data successfu**y receied 0M M +2L +e** L #auses te*etype mac"ines and many termina*s to rin$ a be** 0@ @ +S +ac(space L Moes t"e cursor or print "ead bac(%ard ,*eft. one space 0B B TA+ EoriConta* tab L Moes t"e cursor ,or print "ead. ri$"t to t"e ne3t tab stop 0A 10 L0 Line feed or ne% *ine L Moes t"e cursor ,or print "ead. to a ne% *ine 0+ 11 OT Oertica* tab 0# 12 00 0orm feed L Adances paper to t"e top of t"e ne3t pa$e 0D 13 #R #arria$e return L Moes t"e cursor ,or print "ead. to t"e *eft mar$in 145 Hex DEC Sym2ol Description 02 1! S1 S"ift out L S%itc"es t"e output deice to an a*ternate c"aracter set 00 1A S) S"ift in L S%itc"es t"e output deice bac( to t"e defau*t c"aracter set 10 16 DL2 Data *in( escape 11 1M D#1 Deice contro* 1 12 1@ D#2 Deice contro* 2 13 1B D#3 Deice contro* 3 1! 20 D#! Deice contro* ! 1A 21 4A< 4e$atie ac(no%*ed$e 16 22 S64 Sync"ronous id*e 1M 23 2T+ 2nd of transmission b*oc( L not t"e same as 21T 1@ 2! #A4 #ance* 1B 2A 2M 2nd of medium 1A 26 S5+ Substitute 1+ 2M 2S# 2scape L T"is is t"e 2sc (ey on your (eyboard 1# 2@ 0S 0i*e separator 1D 2B JS Jroup separator 12 30 RS Record separator 10 31 5S 5nit separator M0 12M D2L De*ete L T"is is t"e De* (ey on your (eyboard 0or most computers, t"e sma**est easi*y stored and retrieed piece of data is a byte, %"ic" is composed of @ bits& T"e c"aracters in Tab*e A0 re8uire on*y M bits& To aoid %astin$ space, t"e 23tended AS#)) c"aracters %ere introduced7 t"ese used t"e numbers 12@ t"rou$" 2AA& A*t"ou$" t"ese c"aracters introduce specia*, mat"ematica*, $rap"ic, and forei$n c"aracters, it /ust %asnGt enou$" to satisfy internationa* use& Around 1B@6, Iero3 started %or(in$ to e3tend t"e c"aracter set to %or( %it" Asian c"aracters& T"is %or( eentua**y *ed to t"e current 5nicode set, %"ic" uses 169bit inte$ers and a**o%s for 6A,A36 uni8ue c"aracters& 11o stores c"aracters as 169bit unsi$ned inte$er 5nicode a*ues& T"e AS# and #ER functions conert bet%een t"e inte$er a*ue and t"e c"aracter a*ue, for e3amp*e, bet%een 6A and A& 5se t"e AS# function to determine t"e numerica* AS#)) a*ue of t"e first c"aracter in a strin$& T"e return a*ue is a 169bit inte$er a**o%in$ for 5nicode a*ues& 1n*y t"e first c"aracter in t"e strin$ is used7 t"e rest of t"e c"aracters are i$nored& A run9time error occurs if t"e strin$ "as Cero *en$t"& T"is is essentia**y t"e inerse of t"e #ERY function, %"ic" conerts t"e number bac( into a c"aracter& TIP T"e #ER function is fre8uent*y %ritten as #ERY& )n Oisua* +asic, #ERY returns a strin$ and canGt "and*e nu** input a*ues, and #ER returns a ariant t"atGs ab*e to accept and propa$ate nu** a*ues& )n 11o +asic, t"ey are t"e same7 t"ey bot" return strin$s and t"ey bot" $enerate a run9time error %it" a nu** input a*ue& 5se t"e #ER function to conert a 169bit AS#)) a*ue to t"e c"aracter t"at it represents& T"is is usefu* %"en you %ant to insert specia* c"aracters into a strin$& 0or e3amp*e, #ER,10. is t"e ne%9*ine c"aracter& T"e #ER function is t"e inerse of t"e AS# function& A*t"ou$" t"e AS# function returns t"e 5nicode numbers, t"ese numbers are fre8uent*y $enerica**y referred to as Dt"e AS#)) a*ue&F Strict*y spea(in$, t"is is incorrect, 146 but itGs a %ide*y used s*an$ e3pression& T"e numbers correspond direct*y to t"e AS#)) a*ues for t"e numbers 0 t"rou$" 2AA, and "ain$ used t"e termino*o$y for years, pro$rammers arenGt *i(e*y to stop& So, %"en you see t"e term DAS#)) a*ueF in t"is boo(, t"in( D5nicode a*ue&F Listing 123. #emonstrate new line. Sub S(o*C(rA#c -i! #F Print CHRFBA<C )A Print ASCB"Andre*"C )A< # 6 ">" 4 CHRFB>7C 4 "'" )He* line bet*een > and ' M#Box # End Sub TIP 5se t"e Ms$+o3 statement to print strin$s t"at contain #ERY,10. or #ERY,13. L t"ey bot" cause 11o +asic to print a ne% *ine& T"e 'rint statement disp*ays a ne% dia*o$ for eac" ne% *ine& Ms$+o3, "o%eer, proper*y disp*ays ne% *ines in a sin$*e dia*o$& ;"i*e attemptin$ to decip"er t"e interna* functions of 1pen1ffice&or$, ) fre8uent*y find strin$s t"at contain c"aracters t"at arenGt immediate*y isib*e, suc" as trai*in$ spaces, ne% *ines, and carria$e returns& #onertin$ t"e strin$ to a se8uence of AS#)) c"aracters simp*ifies t"e process of reco$niCin$ t"e true contents of t"e strin$& See Listin$ 12! and 0i$ure A2& Listing 124. /onvert a string to -*/"". Sub Exa!pleStrin3oASCII -i! # A# Strin # 6 "AB"""" """"BA" M#Box # 4 CHRFB>7C 4 Strin3oASCIIB#C= 7= "Strin 3o ASCII" End Sub "unction Strin3oASCIIB#InputFC A# Strin -i! # A# Strin -i! i A# Inteer "or i 6 > 3o ,enB#InputFC # 6 # 4 CStrBASCBMidB#InputF= i= >CCC 4 " " Hext Strin3oASCII 6 # End "unction Figure 52. - string followed by its corresponding -*/"" valuesJ -DGI) !DGG) KDF2) and so on ... 1n more t"an one occasion, ) needed to (no% e3act*y "o% 11o stored data in a te3t document& 1ne common e3amp*e is tryin$ to manipu*ate ne% *ines and ne% para$rap"s in a manner not easi*y supported by re$u*ar e3pressions& T"e subroutine in Listin$ 12A disp*ays t"e current*y se*ected te3t as a strin$ of AS#)) a*ues& T"e important t"in$ to *earn in t"is c"apter is "o% to ie% t"e AS#)) a*ues associated %it" t"e te3t& 147 T"is %i** s"o% t"e c"aracters used bet%een para$rap"s, for e3amp*e& T"e met"ods to proper*y retriee and manipu*ate se*ected te3t are coered *ater& To test t"is macro, se*ect run t"e macro& Listing 125. #isplay the selected te.t as -*/"" characters. Sub Selected3extA#ASCIIBC -i! :Selection# )Multiple di#Nointed #election# -i! :Sel )A #inle #election -i! :Cur#or )OOo docu!ent cur#or -i! i A# Inteer )Index :ariable -i! # A# Strin )3e!porar. utilit. #trin :ariable -i! bI#Selected A# Boolean )I# an. text #electedU bI#Selected 6 3rue )A##u!e t(at text i# #elected
)3(e current #election in t(e current controller& )I$ t(ere i# no current controller= it return# H0,,& )3(i#co!ponent re$er# to t(e current docu!ent :Selection# 6 3(i#Co!ponent&etCurrentSelectionBC I$ I#HullB:Selection#C OR I#E!pt.B:Selection#C 3(en bI#Selected 6 "al#e El#eI$ :Selection#&etCountBC 6 7 3(en bI#Selected 6 "al#e End I$
)3(e #election# are nu!bered $ro! 8ero )Print t(e ASCII :alue# o$ eac( "or i 6 7 3o :Selection#&etCountBC 9 > :Sel 6 :Selection#&etB.IndexBiC :Cur#or 6 3(i#Co!ponent&3ext&Create3extCur#orB.RaneB:SelC # 6 :Cur#or&etStrinBC I$ ,enB#C D 7 3(en M#Box Strin3oASCIIB:Cur#or&etStrinBCC= 7= "ASCII o$ Selection " 4 i El#eI$ :Selection#&etCountBC 6 > 3(en Print "Hot(in i# #elected" End I$ Hext End Sub $.2. /tandard string functions T"e basic comparison operators ,?, [, [?, R, R?, and [R. %or( %it" strin$s as %e** as numbers& T"ey perform case9sensitie comparisons& T"is means t"at t"e strin$s DaF and DAF are not considered to be t"e same& 6ou can a*so use t"e Str#omp function to compare strin$s7 it defau*ts to performin$ case9sensitie comparisons& T"e Str#omp function returns 91, 0, or 1 if t"e first strin$ ar$ument is *ess t"an, e8ua* to, or $reater t"an t"e second strin$ ar$ument& Set t"e optiona* t"ird ar$ument to Cero for a case9insensitie comparison& 148 My %ife rea**y *i(es to fi*e& ) a*so *i(e to fi*e, but my %ife is t"e rea* fi*er in t"e fami*y& S"e *i(es "er fi*in$ cabinets and s"e (eeps t"e fi*es in a*p"abetica* order L %e**, s"e usua**y does& +esides my %ifeGs fi*es, t"e te*ep"one boo( is anot"er p*ace to *oo( for an a*p"abetiCed *ist& T"e name DAAF comes before DAAAF, because a*t"ou$" t"e *etters are t"e same, DAAF is s"orter t"an DAAAF& T"e Str#omp function uses a simi*ar met"od to compare strin$s& T"e fo**o%in$ code $ies an idea of "o% Str#omp %or(s for a case9sensitie comparison& A case9insensitie comparison %ou*d simp*y conert bot" strin$s to a** uppercase before performin$ t"e comparison& ,et #> 6 #trin> ,et #' 6 #trin' ,et !in5len 6 !ini!u!B,enB#>C= ,enB#'CC "or i 6 > 3o !in5len I$ ASCBMidB#>= i= >CC E ASCBMidB#'= i= >CC 3(en #et return :alue to 9> Exit "unction End I$ I$ ASCBMidB#>= i= >CC D ASCBMidB#'= i= >CC 3(en #et return :alue to 9> Exit "unction End I$ Hext I$ ,enB#>C E ,enB#'C 3(en #et return :alue to 9> Exit "unction End I$ I$ ,enB#>C D ,enB#'C 3(en #et return :alue to > Exit "unction End I$ #et return :alue to 7 Exit "unction T"e numerica* 5nicode a*ue of t"e first c"aracter in t"e first strin$ is compared to t"e numerica* 5nicode a*ue of t"e first c"aracter in t"e second strin$& )f t"e first c"aracter is numerica**y *ess t"an t"e second c"aracter, 91 is returned& )f t"e first c"aracter is numerica**y $reater t"an t"e second c"aracter, 1 is returned& )f t"e first c"aracter in eac" strin$ is t"e same, t"e second c"aracter in eac" strin$ is compared& )f t"e correspondin$ numerica* 5nicode a*ue of eac" c"aracter is t"e same and t"e strin$s are t"e same *en$t", 0 is returned& )f correspondin$ c"aracters a** matc", but t"e strin$s are of different *en$t"s, t"e s"orter strin$ is considered *ess t"an t"e *on$er strin$& Listing 126. #emonstrate *tr/omp. Print StrCo!pB "A"= "AA"C )9> becau#e "A" E "AA" Print StrCo!pB"AA"= "AA"C ) 7 becau#e "AA" 6 "AA" Print StrCo!pB"AA"= "A"C ) > becau#e "AA" D "A" Print StrCo!pB "a"= "A"C ) > becau#e "a" D "A" Print StrCo!pB "a"= "A"= >C) > becau#e "a" D "A" Print StrCo!pB "a"= "A"= 7C) 7 becau#e "a" 6 "A" i$ ca#e i# inored 5se t"e 5#ase and L#ase functions to return a copy of t"e strin$ %it" a** c"aracters in uppercase or *o%ercase& 149 Listing 127. #emonstrate U/ase and L/ase. SF 6 ",a# Oea#" Print ,Ca#eB#C REM Return# "la# :ea#" Print 0Ca#eB#C REM Return# ",AS OEJAS" )f numerous comparisons %i** be made, usin$ L#ase or 5#ase is sometimes faster t"an performin$ a case9 insensitie comparison eac" time& And sometimes, it is simp*y easier to use& I$ ,Ca#eBRi(tB#"ileHa!e= %CC 6 "odt" 3(en 5se Str#on,strin$, mode, *oca*e=id. to conert a strin$ %it" more f*e3ibi*ity t"an t"e indiidua* met"ods 5#ase and L#ase& T"e supported modes ,s"o%n in Tab*e A2. are bit a*ues t"at can be used to$et"er7 for e3amp*e, 1N6!?6A causes a** c"aracters to be conerted to uppercase and to 5nicode& T"e fina* ar$ument, *oca*e=id, is an optiona* inte$er *oca*e identifier t"at is not current*y supported ,as of 11o ersion 3&2&1. Table 52. Modes supported by the *tr/onv statement. )ode Description 0 4o c"an$e& 1 #onert a** c"aracters to uppercase& 2 #onert a** c"aracters to *o%ercase& ! #onert narro% ,"a*f9%idt". c"aracters in t"e strin$ to %ide ,fu**9%idt". c"aracters& @ #onert %ide ,fu**9%idt". c"aracters in t"e strin$ to narro% ,"a*f9%idt". c"aracters& 16 #onert Eira$ana c"aracters in t"e strin$ to <ata(ana c"aracters& 32 #onert <ata(ana c"aracters in t"e strin$ to Eira$ana c"aracters& 6! #onerst a** c"aracters to 5nicode& 12@ #onert a** c"aracters from 5nicode& 5se t"e LTrim, RTrim, and Trim functions to return copies of a strin$ %it" *eadin$, trai*in$, or bot" *eadin$ and trai*in$ spaces remoed& ) usua**y do t"is %it" data retrieed from fi*es and databases, and direct*y from users& T"e ori$ina* strin$ is unc"an$ed, as are a** interna* spaces& Some trim routines in ot"er pro$rammin$ *an$ua$es trim a** sorts of inisib*e c"aracters, suc" as carria$e returns, ne%9*ine c"aracters, and tabs& )n 11o +asic, on*y t"e space c"aracter %it" an AS#)) a*ue of 32 is trimmed& Listing 128. #emonstrate Lrim and Rrim. # 6 " (ello *orld " Print "B" 4 ,3ri!B#C 4 "C" )B(ello *orld C Print "B" 4 R3ri!B#C 4 "C" )B (ello *orldC Print "B" 4 3ri!B#C 4 "C" )B(ello *orldC 5se t"e Len function to return t"e number of c"aracters in t"e strin$& )f t"e ar$ument is not a strin$, it is conerted to a strin$ first& )tGs probab*y safer to use #Str to conert nonstrin$ ar$uments to strin$s, rat"er t"an to re*y on t"e automatic be"aior& 0or e3amp*e, types suc" as +yte %i** not conert automatica**y as e3pected& T"e a*ue "e*d in t"e +yte data type is treated as an AS#)) a*ue and conerted to a sin$*e c"aracter& T"e #Str function aoids t"is prob*em& Listing 129. #emonstrate Len. Print ,enB""C )7 Print ,enB">"C )> 150 Print ,enB">'%"C )% Print ,enB>'C )' t(e nu!ber i# con:erted to a #trin To create a strin$ %it" a sin$*e c"aracter repeated mu*tip*e times, use t"e Strin$ function& T"e first ar$ument is an inte$er indicatin$ "o% many times t"e c"aracter is repeated& Pero is a a*id a*ue for t"e first ar$ument, returnin$ an empty strin$& T"e second ar$ument is t"e c"aracter to repeat& Kust *i(e t"e AS# function, t"e Strin$ function uses t"e first c"aracter from t"e strin$ and i$nores t"e rest& )f t"e second ar$ument is a number, itGs treated as an AS#)) a*ue and t"e c"aracter is created from t"e number& Listing 130. #emonstrate *tring. Print StrinB'= A<C )AA A< i# ASCII $or A Print StrinB'= "AB"C )AA Onl. t(e $ir#t c(aracter i# u#ed Print ASCBStrinB'CC )7 Bu: Created #trin *it( t*o ASCII 7 c(aracter# Print ,enBSpaceB?CC )? "our #pace# 5se t"e function )nStr to find %"ere ,and if. one strin$ is contained inside anot"er& T"e )nStr function can ta(e four ar$uments& T"e first ar$ument is an optiona* inte$er t"at indicates t"e first c"aracter to c"ec(& T"is defau*ts to 1, t"e first c"aracter, if it is not inc*uded& )nStr t"en searc"es t"e second ar$ument to see if it contains t"e t"ird ar$ument& T"e fourt" optiona* ar$ument determines if t"e comparison is case sensitie ,0. or case insensitie ,1.& T"e defau*t searc" is case insensitie& 6ou canGt use t"e fourt" ar$ument un*ess you a*so use t"e first ar$ument& TIP T"e Str#omp function uses a 0 to indicate a case9insensitie comparison and a 1 L t"e defau*t L to indicate a case9sensitie comparison& T"e )nStr function, "o%eer, uses a 0 to indicate a case9sensitie comparison and a 1 L t"e defau*t L to indicate a case9insensitie comparison& T"e on*y simi*arity is t"at t"e a*ue 1 is t"e defau*t& Listing 131. #emonstrate "n*tr. Print InStrB"CBAABC"= "abc"C )? de$ault to ca#e in#en#iti:e Print InStrB>= "CBAABC"= "b"C )' $ir#t aru!ent i# > b. de$ault Print InStrB'= "CBAABC"= "b"C )' #tart *it( #econd c(aracter Print InStrB%= "CBAABC"= "b"C )< #tart *it( t(ird c(aracter Print InStrB>= "CBAABC"= "b"= 7C )7 ca#e9#en#iti:e co!pari#on Print InStrB>= "CBAABC"= "b"= >C )' ca#e9in#en#iti:e co!pari#on Print InStrB>= "CBAABC"= "B"= 7C )' ca#e9#en#iti:e co!pari#on )nStrRe is on*y aai*ab*e %"i*e O+ compatibi*ity mode is true& T"e start *ocation is ar$ument 3, as opposed to t"e first ar$ument in )nStr& A start *ocation of 91 means start at t"e ri$"t most c"aracter7 ) %is" t"at 92 %as t"e second c"aracter from t"e ri$"t, but it causes a run9time e3ception& Listing 132. #emonstrate "n*trRev. Sub Exa!pleInStrRe: Co!patibilit.ModeB3rueC Print InStrRe:B"CBAABC"= "ABC"C )? de$ault to ca#e #en#iti:e Print InStrRe:B"CBAABC"= "abc"C )7 de$ault to ca#e #en#iti:e Print InStrRe:B"CBAABC"= "abc"= 9>= >C )? $orce ca#e in#en#iti:e Print InStrRe:B"CBAABC"= "B"= >C )7 #tart *it( $ir#t c(aracter Print InStrRe:B"CBAABC"= "B"= 'C )' #tart *it( #econd c(aracter Print InStrRe:B"CBAABC"= "B"= 9>C )< #tart *it( la#t c(aracter Print InStrRe:B"CBAABC"= "B"= <C )< #tart *it( $i$t( c(aracter Print InStrRe:B"CBAABC"= "B"= ?C )' #tart *it( $ourt( c(aracter Print InStrRe:B"CBAABC"= "b"= 9>= 7C )7 ca#e9#en#iti:e co!pari#on 151 Print InStrRe:B"CBAABC"= "b"= 9>= >C )< ca#e9in#en#iti:e co!pari#on Print InStrRe:B"CBAABC"= "B"= 9>= 7C )< ca#e9#en#iti:e co!pari#on End Sub 'rior to 11o 2&0, t"e return a*ue from )nStr is an inte$er, %"ic" is *imited to a*ues from 932,M6@ t"rou$" 32,M6M& A strin$ can be up to 6A,A3A c"aracters in *en$t", %"ic" causes prob*ems %"en )nStr searc"es *ar$e strin$s& Startin$ %it" 11o 2&0, "o%eer, t"e return type is a *on$& Listing 133. #emonstrate "n*tr and a long string. -i! #> A# Strin #> 6 StrinB??777= "*"C 4 "//" )3(i# #trin (a# ??77' c(aracter#& Print InStrB#>= "//"C )??77> in OOo '&7 and 9'><%< in OOo >&>&>& $.3. /ubstrings 5se t"e Left function to retriee a portion of t"e strin$ from t"e start& T"e first ar$ument is t"e strin$ from %"ic" to e3tract t"e c"aracters, and t"e second ar$ument indicates "o% many c"aracters to return& Ana*o$ous*y, t"e Ri$"t function returns strin$s from t"e end of a strin$& )f t"e re8uested *en$t" is Cero, an empty strin$ is returned& )f t"e re8uested *en$t" is too *ar$e, t"e entire strin$ is returned& Print ,e$tB">'%?<"= 'C )>' Print ,e$tB">'%?<"= QC )>'%?< Print Ri(tB">'%?<"= 'C )?< T"e *en$t" ar$ument for t"e Left and Ri$"t functions is a *on$, correct*y "and*in$ strin$s, %"ic" can contain up to 6A,A3A c"aracters ,see Listin$ 13!.& Listing 134. *trings can contain up to GI)IFI characters. -i! #> A# Strin #> 6 StrinB??77'= "*"C )3(i# #trin (a# ??77' c(aracter# Print ,enB#>C )??77' Print ,enB,e$tB#>= ??777CC )??777 B$ixed in OOo '&7C Print ,enBRi(tB#>= ??777CC )??777 5se t"e Mid function to e3tract arbitrary substrin$s and to rep*ace substrin$s in an e3istin$ strin$& )n $enera*, t"e strin$ functions return a ne% strin$ rat"er t"an modifyin$ t"e e3istin$ strin$& 0or e3amp*e, t"e Trim function returns a ne% strin$ %it" *eadin$ and trai*in$ spaces remoed, rat"er t"an remoin$ *eadin$ and trai*in$ spaces from t"e e3istin$ strin$& T"e Mid function, "o%eer, can be used to modify t"e strin$ rat"er t"an simp*y returnin$ a ne% one& )n its simp*est form, t"e Mid function "as functiona*ity to t"e Ri$"t function& T"e first ar$ument is a strin$, and t"e second ar$ument is a startin$ position& T"e optiona* t"ird ar$ument indicates t"e *en$t" of t"e strin$ to return& Listing 135. #emonstrate Mid. Print MidB">'%?<A"= %C )%?<A Print MidB">'%?<A"= %= 'C )%? #> 6 StrinB??777= "*"C4"//" Print MidB#>= ??777C )*// Ho proble! *it( lare aru!ent# Print ,enBMidB#>= '= ?7777CC )?7777 Ho proble! *it( lare aru!ent# T"e Mid function can proide t"e same functiona*ity as t"e Left function& ,e$tB#= nC 6 MidB#= >= nC 152 T"e Mid function ta(es an optiona* fourt" ar$ument, a strin$, t"at rep*aces t"e specified substrin$ in t"e first ar$ument& )n ot"er %ords, if four ar$uments are present, t"e first t"ree ar$uments specify a substrin$ in t"e strin$ and t"e fourt" ar$ument rep*aces t"e substrin$& T"is may s"orten t"e *en$t" of a strin$, but in 11o +asic t"is %i** neer cause t"e strin$ to become *on$er& )f t"e fina* ar$ument is *on$er t"an t"e specified substrin$, on*y t"e first c"aracters are used from t"e fina* ar$ument to rep*ace t"e substrin$& Listing 136. #emonstrate Mid to replace strings. # 6 ">'%?<A2Q@" MidB#= %= <= ""C )Replace $i:e c(aracter# *it( not(in Print # )>'Q@ # 6 ">'%?<A2Q@" MidB#= %= <= "//"C )Replace $i:e c(aracter# *it( t*o Print # )>'//Q@ # 6 ">'%?<A2Q@" MidB#= %= <= "ABC-E"J"C )Cannot add !ore t(an .ou replace $ro! t(e !iddle Print # )>'ABC-EQ@ # 6 ">'%?<A2Q@" MidB#= 2= >'= "ABC-E"J"C)Pou can add !ore t(an .ou re!o:e $ro! t(e end Print # )>'%?<AABC-E"J $.4. %eplace T"e Rep*ace)nStrin$ function ,see Listin$ 13M. emu*ates t"e Mid function, %it" t%o e3ceptions: )t puts t"e entire ne% strin$ in p*ace, een if itGs *on$er t"an t"e substrin$ t"at it rep*aces, and it doesnGt modify t"e ori$ina* strin$& Listing 137. - general replace string method. REM 3(i# $unction i# #i!ilar to Mid *it( $our aru!ent#& REM 3(i# $unction doe# not !odi$. t(e oriinal #trin& REM 3(i# $unction (andle# replace!ent text larer t(an n& "unction ReplaceInStrinB#F= i4= n4= #He*FC A# Strin I$ i E6 > 3(en )Place t(e #trin in $ront& )3(e onl. ;ue#tion i# (o* !uc( #trin !u#t be re!o:ed&
I$ n E > 3(en )Re!o:e not(in ReplaceInStrin 6 #He* 4 # El#eI$ n D6 ,enB#C 3(en )Re!o:e e:er.t(in ReplaceInStrin 6 #He* El#e )Re!o:e a portion $ro! t(e le$t ReplaceInStrin 6 #He* 4 Ri(tB#= ,enB#C 9 nC End I$
El#eI$ i W n D ,enB#C 3(en )Replacin pa#t t(e end= t(en extract t(e le$t!o#t part# )Mid *or1# to $ind i$ t(e lent( aru!ent i# larer t(an t(e )#trin= #o t(i# i# $ineK Append t(e ne* text to t(e end&
ReplaceInStrin 6 MidB#= >= i 9 >C 4 #He* 4 Ri(tB#= ,enB#C 9 i 9 n W >C End I$ End "unction +ut %ait, t"ere is an undocumented statement Rep*ace,strn$, find, rp*, start, #ount, mode., %"ic" finds a** occurrences of find and rep*aces t"em %it" rp*& T"e *ast t"ree ar$uments are optiona*& T"e start a*ue indicates %"at part of t"e strin$ to return, not %"ere to start rep*ace& A a*ue of one for t"e start a*ue returns a** of t"e c"aracters& A start a*ue of t"ree i$nores t"e first t%o c"aracters in t"e return strin$& T"e count indicates t"e ma3imum number of times to rep*ace t"e found te3t& A a*ue of 91 rep*aces a** a*ues& A mode a*ue of 1, t"e defau*t, indicates a case9insensitie compare is used to find matc"in$ te3t& A mode a*ue of 0 causes a case9sensitie compare& $.. 2ligning strings with ./et and %/et 5se t"e LSet and RSet statements to *eft9/ustify and ri$"t9/ustify strin$s into t"e space ta(en by anot"er strin$& T"is is usefu*, for e3amp*e, to create co*umn "eadin$s t"at are *eft or ri$"t /ustified %it" *eadin$ or trai*in$ spaces& T"e RSet and LSet functions use t"e same synta3& ,Set #trin5> 6 expre##ion RSet #trin5> 6 expre##ion T"e strin$ on t"e *eft9"and side can contain any data as *on$ as it is t"e *en$t" t"at you %ant& T"e ri$"t9"and side must ea*uate to a strin$7 t"at strin$ %i** be disp*ayed in t"e space defined by t"e *en$t" of t"e *eft9"and strin$& 5n*i(e t"e be"aior for many functions in 11o +asic, t"e e3pression is not automatica**y conerted to a strin$& Listing 138. R*et. -i! # A# Strin )Strin :ariable to contain t(e re#ult # 6 StrinB>7= "*"C )3(e re#ult i# >7 c(aracter# *ide RSet # 6 CStrB>&'%C )3(e nu!ber i# not auto!aticall. con:erted to a #trin Print "F" 4 # )F >&'% T"e important t"in$ about t"e strin$ on t"e *eft is its *en$t" L t"e %idt" of t"e fie*d in %"ic" t"e a*ue of interest %i** be disp*ayed& T"e easiest %ay to $et a strin$ of a specified *en$t" is to use t"e Strin$ function& T"e c"aracter t"at you use is not important because a** of t"e e3tra c"aracters in t"e fina* resu*t are rep*aced %it" spaces& Listing 139. L*et. -i! # A# Strin )Strin :ariable to contain t(e re#ult # 6 StrinB>7= "/"C )3(e re#ult i# >7 c(aracter# *ide ,Set # 6 CStrB>&'%C )3(e nu!ber i# not auto!aticall. con:erted to a #trin 154 Print # 4 "G" )>&'% G )f t"e strin$ on t"e *eft is s"orter t"an t"e strin$ e3pression on t"e ri$"t, t"e e3pression is truncated to fit& +ot" LSet and RSet c"op c"aracters from t"e end of t"e e3pression to ma(e it fit %it"in t"e defined strin$ *en$t"& Listing 140. L*et and R*et truncate. -i! # A# Strin )Strin :ariable to contain t(e re#ult # 6 StrinB?= "/"C )3(e re#ult *ill be $our c(aracter# *ide ,Set # 6 CStrB'>&'%C)3runcated on t(e ri(t Print "F" 4 # 4 "G" )F'>&'G RSet # 6 CStrB'>&'%C)3runcated on t(e ri(t Print "F" 4 # 4 "G" )F'>&'G T"e code in Listin$ 1!1 demonstrates t"e be"aior of t"e LSet and RSet commands& T"e resu*ts are disp*ayed in 0i$ure A3& Listing 141. /omplete L*et and R*et e.ample. Sub Exa!ple,SetAndRSet -i! # A# Strin -i! #Oar A# Strin -i! #3!p A# Strin
M#Box #= 7= "RSet and ,Set" End Sub 155 Figure 53. RSet and LSet justify strings. TIP )n Oisua* +asic, LSet a**o%s you to oer*ay data from one user9defined type %it" data from anot"er, oer*ayin$ a** t"e bytes from one data structure on top of t"e ot"er7 i$norin$ t"e under*yin$ structure& )n 11o +asic, LSet on*y manipu*ates strin$s& $.#. Canc' formatting with Cormat 6ou can conert a number to a strin$ formatted accordin$ to t"e optiona* format strin$& And you can inc*ude mu*tip*e formats in a sin$*e format strin$& See Tab*e A3& T"e current *oca*e inf*uences t"e returned formatted strin$& Set t"e *oca*e usin$ Tools Options !anguage Settings !anguages& )f t"e format strin$ is omitted, 0ormat produces output simi*ar to t"e #Str function& Listing 142. *imple +ormat statement. Print "or!atB>''%= "77&77"C )>''%&77 Print "or!atB>'%?&<A2Q@= "LLL77&77"C )>'%?&<2 2ac" indiidua* format is separated by a semico*on ,7.& T"e first format is used for positie numbers, t"e second for ne$atie numbers, and t"e t"ird for Cero& )f on*y one format code is present, it app*ies to a** numbers& Listing 143. +ormat string may specify formatting for positive ) negative) and zero numbers. -i! # A# Strin # 6 "P 77777&777\H LLLL&77\V 7&7" Print "or!atB9>'&%= #C )H >'&%7 Print "or!atB7= #C )V 7&7 Print "or!atB>'&%= #C )P 7777>'&%77 Table 53. Numeric +ormat specifiers. Code Description 0 )f t"e number "as a di$it at t"e position of t"e 0 in t"e format code, t"e di$it is disp*ayed7 ot"er%ise a Cero appears& T"is means t"at *eadin$ and trai*in$ Ceros are disp*ayed, *eadin$ di$its are not truncated, and trai*in$ decima*s are rounded& W T"is %or(s *i(e t"e 0, but *eadin$ and trai*in$ Ceros are not disp*ayed& & T"e decima* p*ace"o*der determines t"e number of decima* p*aces to t"e *eft and ri$"t of t"e decima* separator& A*t"ou$" t"e period is used in t"e format strin$ re$ard*ess of *oca*e, t"e output correct*y uses t"e *oca*e9specific decima* separator& X Mu*tip*y t"e number by 100 and insert t"e percent si$n ,X. %"ere it appears in t"e format code& 29 2N )f t"e format code contains at *east one numerica* di$it p*ace"o*der ,0 or W. to t"e ri$"t of t"e symbo*, t"e number is formatted in t"e scientific notation& T"e *etter 2 or e is inserted bet%een t"e number and t"e e3ponent& T"e number of p*ace"o*ders for di$its to t"e ri$"t of t"e symbo* 156 Code Description e9 eN determines t"e number of di$its in t"e e3ponent& )f t"e e3ponent is ne$atie, a minus si$n ,9. is disp*ayed direct*y before an e3ponent& )f t"e e3ponent is positie, a p*us si$n ,N. is on*y disp*ayed before e3ponents %it" 2N or eN& , T"e comma is a p*ace"o*der for t"e t"ousands separator& )t separates t"ousands from "undreds in a number %it" at *east four di$its& T"e t"ousands de*imiter is disp*ayed if t"e format code contains t"e p*ace"o*der surrounded by di$it p*ace"o*ders ,0 or W.& 9 N Y , . space '*us si$ns ,N., minus si$ns ,9., do**ar si$ns ,Y., spaces, or brac(ets entered direct*y in t"e format code are disp*ayed as t"e *itera* c"aracter& S T"e bac(s*as" disp*ays t"e ne3t c"aracter in t"e format code& )n ot"er %ords, it preents t"e ne3t c"aracter from bein$ seen as a specia* c"aracter& T"e bac(s*as" is not disp*ayed un*ess you enter a doub*e bac(s*as" ,SS. in t"e format code& #"aracters t"at must be preceded by a bac(s*as" in t"e format code in order to be disp*ayed as *itera* c"aracters are t"e date9 and time9formattin$ c"aracters ,a, c, d, ", m, n, p, 8, s, t, %, y, -, :., numeric9formattin$ c"aracters ,W, 0, X, 2, e, comma, period., and strin$9formattin$ c"aracters ,[, R.& 6ou may a*so enc*ose c"aracters in doub*e 8uotation mar(s& Jenera* 4umber 4umbers are disp*ayed as entered& #urrency A currency symbo* is p*aced in front of t"e number, and ne$atie numbers are in brac(ets& 0i3ed At *east one di$it is disp*ayed in front of t"e decima* separator& T%o decima*s are disp*ayed& 'ercent Mu*tip*y t"e number by 100 and append a percent si$n ,X.& Standard Disp*ays numbers %it" a *oca*e9specific t"ousands separator& T%o decima*s are disp*ayed& Scientific Disp*ays numbers in scientific notation& T%o decima*s are disp*ayed& T"e format function "as been dramatica**y improed oer t"e years and most of t"e bu$s "ae been fi3ed& 0ormat specifiers re*ated to numbers are s"o%n in Tab*e A3& Listing 144. #emonstrate numeric format specifiers. Sub Exa!ple"or!at M#Box "or!atBA%'Q&'= "LL=LL7&77"C REM A=%'Q&'7 M#Box "or!atB>'%?<A2Q@&<<<<= "LL=LL7&77"C REM >'%=?<A=2Q@&<A M#Box "or!atB7&<<<= "&LL"C REM &<A M#Box "or!atB>'%&<<<= "L&LL"C REM >'%&<A M#Box "or!atB>'%&<<<= "&LL"C REM >'%&<A M#Box "or!atB7&<<<= "7&LL"C REM 7&<A M#Box "or!atB7&>'<<<<<= "GL&LL"C REM G>'&<A M#Box "or!atB>'%&?<A2Q= "LLE9LLLL"C REM >'E> M#Box "or!atB&77>'%?<A2Q= "7&7E9LLLL"C REM >&'E977% M#Box "or!atB>'%&?<A2Q= "L&e9LLL"C REM >&e77' M#Box "or!atB&77>'%?<A2Q= "L&e9LLL"C REM >&e977% M#Box "or!atB>'%&?<A2Q@= "L&LL i# LLL"C REM >'%&?A M#Box "or!atBQ>'%&?<A2Q@= "Jeneral Hu!ber"C REM Q>'%&?<A2Q@ M#Box "or!atBQ>'%&?<A2Q@= ""ixed"C REM Q>'%&?A M#Box "or!atBQ>'%&?<A2Q@= "Currenc."C REM Q=>'%&?A F Bbro1enC M#Box "or!atBQ>'%&?<A2Q@= "Standard"C REM Q=>'%&?A M#Box "or!atBQ>'%&?<A2Q@= "Scienti$ic"C REM Q&>'EW7% M#Box "or!atB7&77>'%?<A2Q@= "Scienti$ic"C REM >&'%E97% M#Box "or!atB7&77>'%?<A2Q@= "Percent"C REM 7&>'G End Sub 157 0ormat specifiers re*ated to date and time formattin$ are s"o%n in Tab*e A!& 0or reasons t"at ) do not understand, t"ey are not inc*uded %it" t"e standard documentation& Table 54. #ate and time format specifiers. Code Description 8 T"e 8uarter of t"e year ,1 t"rou$" !.& 88 T"e 8uarter of t"e year as 1st 8uarter t"rou$" !t" 8uarter y T"e day in t"e year ,1 t"rou$" 36A.& yy T%o9di$it year& yyyy #omp*ete four9di$it year& m Mont" number %it" no *eadin$ Cero& mm T%o9di$it mont" number7 *eadin$ Ceros are added as re8uired& mmm Mont" name abbreiated to t"ree *etters& mmmm 0u** mont" name as te3t& mmmmm 0irst *etter of mont" name& d Day of t"e mont" %it" no *eadin$ Cero& dd Day of t"e mont"7 *eadin$ Ceros are added as re8uired& ddd Day as te3t abbreiated to t"ree *etters ,Sun, Mon, Tue, ;ed, T"u, 0ri, Sat.& dddd Day as te3t ,Sunday t"rou$" Saturday.& ddddd 0u** date in a s"ort date format& dddddd 0u** date in a *on$ format& % Day of t"e %ee( as returned by ;ee(Day ,1 t"rou$" M.& %% ;ee( in t"e year ,1 t"ou$" A2.& " Eour %it" no *eadin$ Cero& "" T%o9di$it "our7 *eadin$ Ceros are added as re8uired& n Minute %it" no *eadin$ Cero& nn T%o9di$it minute7 *eadin$ Ceros are added as re8uired& s Second %it" no *eadin$ Cero& ss T%o9di$it second7 *eadin$ Ceros are added as re8uired& ttttt Disp*ay comp*ete time in a *on$ time format& c Disp*ay a comp*ete date and time& - Date separator& A *oca*e9specific a*ue is used& : Time separator& A *oca*e9specific a*ue is used& T"e date and time format specifiers are no% imp*emented& ) am a%are of at *east one bu$ t"at is demonstrated in Listin$ 1!A %it" t"e format strin$ Dd-mmmm-yyyy ":nn:ssF7 0i$ure A! s"o%s t"at DnnF does not e3pand proper*y on t"e *ast *ine& Listing 145. #emonstrate date and time format specifiers. Sub "or!at-ate3i!eStrin# -i! iG 158 -i! d A# -ate d 6 no*BC -i! #F -i! $or!at# $or!at# 6 Arra.B";"= ";;"= "."= ".."= "...."= 5 "!"= "!!"= "!!!"= "!!!!"= "!!!!!"= 5 "d"= "dd"= "ddd"= "dddd"= "ddddd"= "dddddd"= 5 "*"= "**"= "("= "(("= "n"= "nn"= "nnn"= "#"= "##"= 5 "ttttt"= "c"= "d+!!!!+.... (:nn:##"C "or i 6 ,BoundB$or!at#C 3o 0BoundB$or!at#C # 6 # 4 $or!at#BiC 4 " 6D " 4 "or!atBd= $or!at#BiCC 4 CHRFB>7C Hext M#Box # End Sub Figure 54. #ate and time format specifiers. 159 0ormat specifiers re*ated to strin$s are s"o%n in Tab*e AA& Table 55. *tring format specifiers. Code Description [ Strin$ in *o%ercase& R Strin$ in uppercase& 1t"er strin$ format specifiers used to be documented, but "ae neer been imp*emented ,see Tab*e A6.& ) inc*ude t"em because t"e specifiers in Tab*e A! and Tab*e AA used to be documented but not imp*emented7 no% t"ey are imp*emented but not documented& Table 56. *tring format specifiers. Code Description : #"aracter p*ace"o*der& )f t"e input c"aracter is empty, p*ace a space in t"e output strin$& 0or e3amp*e, D,:::.F formats to D, .F %it" an empty strin$& Q #"aracter p*ace"o*der& )f t"e input c"aracter is empty, p*ace not"in$ in t"e output strin$& 0or e3amp*e, D,QQQ.F formats to D,.F %it" an empty strin$& T 4orma**y, c"aracter p*ace"o*ders are fi**ed ri$"t to *eft7 t"e T forces t"e p*ace"o*ders to be fi**ed *eft to ri$"t& As of t"is %ritin$ %it" 11o ersion 3&2&1, on*y t"e upper - *o%er case strin$ format specifiers are imp*emented& Listing 146. *tring format specifiers. Sub "or!atStrin# -i! iG -i! #F -i! $or!at# $or!at# 6 Arra.B"E"= "D"= 5 "II"= "BIIIC"= "XIIIIY"= 5 "44"= "B444C"= "X4444Y"= 5 C "or i 6 ,BoundB$or!at#C 3o 0BoundB$or!at#C # 6 # 4 $or!at#BiC 4 " 6D B" 4 "or!atB"On"= $or!at#BiCC 4 "C" 4 CHRFB>7C Hext M#Box # End Sub $.$. Converting data to a string 11o +asic contains functions t"at conert ot"er data types to a strin$& A*t"ou$" t"e 0ormat function is t"e most ersati*e met"od of conertin$ a number to a strin$, t"at *ee* of contro* is typica**y not re8uired& T"e Str function conerts a number to a strin$ %it" no *oca*iCation, and t"e Oa* function conerts it bac( to a number& T"e Ee3 and 1ct functions conert a Lon$ to its correspondin$ "e3adecima* or octa* notation& T"e *eadin$ DQEF and DQ1F are not inc*uded& To conert bac( to a number, t"ese strin$s must be manua**y prepended to t"e strin$& 160 T"e #Str function is ab*e to inte**i$ent*y conert a*most any data type to a strin$ in a *oca*e9specific %ay ,see Tab*e AM.& T"e Str function is *imited to numbers and does not perform a *oca*e9specific conersion& Table 57. /onverting data types with /*tr. Type Converted to Strin+ +oo*ean True or 0a*se Date 0ormatted date strin$ suc" as 06-0@-2010 4u**, uninitia*iCed ob/ect Run9time error 2mpty, uninitia*iCed ariant Pero9*en$t" strin$ any numeric a*ue 4umber as a strin$ Listing 147. /*tr with a few data types. Sub Exa!pleCStr On Error Joto Handler -i! b A# Boolean -i! o A# ObNect -i! : A# Oariant ) 3(i# i# e!pt. -i! d A# -ouble : d 6 PIBC
Print "Boolean B" 4 CStrBbC 4 "C" Print "-ate B" 4 CStrBHo*C 4 "C" Print "E!pt. Oariant B" 4 CStrB:C 4 "C" Print "-ouble B" 4 CStrBdC 4 "C" Print "Hull obNect B" 4 CStrBoC 4 "C" Exit Sub Handler: Print "Encountered error: " 4 Error Re#u!e Hext End Sub T"e #Str function is usefu* %"en you need to e3p*icit*y conert a a*ue to a strin$ to aoid incorrect defau*t conersions to ot"er types& 0or e3amp*e, t"e first operand to t"e addition operator determines if t"e resu*t is a strin$ or a number& T"is is a*so an ar$ument a$ainst t"e use of t"e addition operator ,N. for strin$ concatenation rat"er t"an t"e operator specifica**y desi$ned for strin$ concatenation ,Q.& Print % W "?" )2 Print CStrB%C W "?" )%? T"e Koin function concatenates a** of t"e e*ements in a one9dimensiona* array into a sin$*e strin$& )f no de*imiter is specified, a space separates eac" e*ement& Print MoinBArra.B%= ?= <CC )% ? < Print MoinBArra.B%= ?= <C= "/"C )%/?/< T"e Sp*it function is used to sp*it a strin$ into pieces based on an optiona* de*imiter& T"is is essentia**y t"e opposite of t"e Koin function and is t"e fastest met"od to parse a strin$ into a series of substrin$s based on a de*imiter& SplitB"% ? <"C )return# t(e arra. B%= ?= <C SplitB"%/?/<"= "/"C )return# t(e arra. B%= ?= <C 161 $.&. 2dvanced searching T"e usua* searc" met"ods are Str#omp ,Listin$ 126., )nStr ,Listin$ 131., and )nStrRe ,Listin$ 132.& Adanced searc"in$ can be done usin$ t"e Te3tSearc" serice& Searc"in$ can be done usin$ A+S1L5T2, R2J2I', or A''R1I)MAT2 mode& ) %i** not ta(e t"e time to pursue t"e Te3tSearc" serice in dept"7 for e3amp*e, to inesti$ate rep*acin$ te3t& Listing 148. using the e.t*earch service. Sub Strin3extSearc( -i! o3extSearc( ) 3extSearc( #er:ice& -i! #Str3oSearc( A# Strin ) Strin to #earc(& -i! #Matc(Strin A# Strin ) Strin t(at *a# $ound& -i! aSearc(Re#ult ) co!&#un&#tar&util&Searc(Re#ult -i! ran1 A# ,on -i! iMatc(StartPo# A# ,on -i! iMatc(,en A# ,on -i! aSrcOpt A# He* co!&#un&#tar&util&Searc(Option# -i! #F -i! en,ocale A# He* co!&#un&#tar&lan&,ocale
)3(i# doe# not *or1& )&tran#literate"la# 6 co!&#un&#tar&i>Qn&3ran#literationModule#He*&IJHORE5CASE
)3(i# *or1# &tran#literate"la# 6 co!&#un&#tar&i>Qn&3ran#literationModule#He*&0PPERCASE5,OWERCASE End Wit( o3extSearc(&#etOption#BaSrcOptC #Str3oSearc( 6 "aaa (ello AAA" aSearc(Re#ult 6 o3extSearc(&#earc("or*ardB#Str3oSearc(= 7=,enB#Str3oSearc(C9> C )Print aSearc(Re#ult&#ubReExpre##ion# REM #ubReExpre##ion# (a# :alue 8ero i$ no !atc(&&& -o W(ile aSearc(Re#ult&#ubReExpre##ion# D 7 )Print "" W ,BoundBaSearc(Re#ult&#tartO$$#etC W ":" W 0BoundBaSearc(Re#ult&#tartO$$#etC ran1 6 aSearc(Re#ult&#ubReExpre##ion# 9 > iMatc(StartPo# 6 aSearc(Re#ult&#tartO$$#etBran1C W > 162 iMatc(,en 6 aSearc(Re#ult&endO$$#etBran1C 9 aSearc(Re#ult&#tartO$$#etBran1C #Matc(Strin 6 MidB#Str3oSearc(= iMatc(StartPo#= iMatc(,enC # 6 # 4 "B" W ,BoundBaSearc(Re#ult&#tartO$$#etC 4 ":" 4 5 0BoundBaSearc(Re#ult&#tartO$$#etC4 "C 6D " 4 #Matc(Strin 4 CHRFB>7C aSearc(Re#ult 6 o3extSearc(&#earc("or*ardB#Str3oSearc(= 5 aSearc(Re#ult&endO$$#etBran1CW>=,enB#Str3oSearc(C9> C ,oop M#Box # End Sub $.(. Conclusion )t pays to (no% t"e different functions supported by 11o +asic& +efore ) %as a%are of t"e Sp*it function, ) spent a *ot of time %ritin$ a macro t"at parsed a strin$ into pieces& ) re%rote my code usin$ t"e Sp*it function and t"e macro %as si$nificant*y faster& )tGs a*so important to (no% t"e *imitations of strin$s& ) sa% a macro t"at counted %ords in a document by first conertin$ t"e entire document into a sin$*e strin$& T"is tec"ni8ue %or(ed %e**, and it %as ery fast, but it fai*ed %"en t"e number of c"aracters in t"e document e3ceeded 6A,A3A& T"ere are a *ot of ery po%erfu* capabi*ities for formattin$ te3t in 11o +asic& Amon$ ot"er t"in$s, t"e use of t"e 5nicode c"aracter set a**o%s processin$ of near*y any *an$ua$e in t"e %or*d& T"ere are a*so a number of $ood functions for /oinin$, sp*ittin$, and formattin$ te3t strin$s& 163 0. +ile 6outines T"is c"apter introduces t"e subroutines and functions supported by 1pen1ffice&or$ +asic t"at are re*ated to fi*es and directories& After readin$ t"is c"apter youG** be ab*e to create, de*ete, rename, and moe fi*es and directories& 6ouG** *earn met"ods t"at inspect fi*es, bot" open and c*osed, and directories& T"is c"apter a*so e3p*ains t"e idiosyncrasies and bu$s re*ated to readin$ and %ritin$ fi*es, a*on$ %it" differences bet%een operatin$ systems& 11o +asic inc*udes functions t"at a**o% you to interact %it" t"e fi*e system ,see Tab*e A@.& 6ou can perform simp*e and comp*e3 tas(s suc" as creatin$ and de*etin$ directories, or een openin$ and parsin$ fi*es& )n t"is c"apter )G** spend a fair amount of time on directories, fi*e attributes, and t"e different fi*e types& ) %i** e3amine "o% fi*es are or$aniCed and manipu*ated, "o% t"e different fi*e types are structured, and %"ic" functions read and %rite data for t"ose different fi*e types& ) %as "appy %it" "o% easi*y ) %as ab*e to %rite macros to moe and rename fi*es& 1n t"e ot"er "and, t"e functions to manipu*ate binary and random fi*es fee* rou$" around t"e ed$es& Table 58. +ile functions in OOo !asic. !nction Description #"Dir,pat". #"an$e t"e current*y *o$$ed directory or drie& Deprecated7 do not use& #"Drie,pat". #"an$e t"e current*y *o$$ed drie& Deprecated7 do not use& #*ose Wn #*ose a preious*y opened fi*e or fi*es& Separate fi*e numbers %it" a comma& #onert0rom5RL,str. #onert a pat" e3pressed as a 5RL to a system9specific pat"& #onertTo5RL,str. #onert a system9specific pat" to a 5RL& #urDir #urDir,drie. Return t"e current directory as a system9specific pat"& )f t"e optiona* drie is specified, t"e current directory for t"e specified drie is returned& Dir,pat". Dir,pat", attr. Return a *istin$ of fi*es based on an inc*uded pat"& T"e pat" may contain a fi*e specification L for e3amp*e, D-"ome-andy-\&t3tF& 1ptiona* attributes determine if a *istin$ of fi*es or directories is returned& 210,number. Return True if t"e fi*e denoted by DnumberF is at t"e end of t"e fi*e& 0i*eAttr,number, 1. Return t"e mode used to open t"e fi*e $ien by DnumberF& T"e second ar$ument specifies if t"e fi*e9access or t"e operatin$9system mode is desired, but on*y t"e fi*e mode is current*y supported& 0i*e#opy,src, dest. #opy a fi*e from source to destination& 0i*eDateTime,pat". Return t"e date and time of t"e specified fi*e as a strin$& 0i*e23ists,pat". Return True if t"e specified fi*e or directory e3ists& 0i*eLen,pat". Return t"e *en$t" of t"e specified fi*e as a *on$& 0ree0i*e,. Return t"e ne3t aai*ab*e fi*e number for use& Jet Wnumber, ariab*e Jet Wnumber, pos, ariab*e Read a record from a re*atie fi*e, or a se8uence of bytes from a binary fi*e, into a ariab*e& )f t"e position ar$ument is omitted, data is read from t"e current position in t"e fi*e& 0or fi*es opened in binary mode, t"e position is t"e byte position in t"e fi*e& JetAttr,pat". Return a bit pattern identifyin$ t"e fi*e type& Jet'at"Separator,. Return t"e system9specific pat" separator& )nput Wnumber, ar Se8uentia**y read numeric or strin$ records from an open fi*e and assi$n t"e data to one or more ariab*es& T"e carria$e return ,AS#?13., *ine feed ,AS#?10., and comma act as de*imiters& )nput cannot read commas or 8uotation mar(s ,Z. because t"ey de*imit t"e te3t& 5se t"e Line )nput statement if you must do t"is& <i**,pat". De*ete a fi*e from dis(& 164 !nction Description Line )nput Wnumber, ar Se8uentia**y read strin$s to a ariab*e *ine9by9*ine up to t"e first carria$e return ,AS#?13. or *ine feed ,AS#?10.& Line end mar(s are not returned& Loc,number. Return t"e current position in an open fi*e& L10,number. Return t"e siCe of an open fi*e, in bytes& M(Dir,pat". #reate t"e directory& 4ame src As dest Rename a fi*e or directory& 1pen pat" 0or Mode As Wn 1pen a data c"anne* ,fi*e. for Mode ,)nput ? read, 1utput ? %rite. 'ut Wn, ar 'ut Wn, pos, ar ;rite a record to a re*atie fi*e or a se8uence of bytes to a binary fi*e& Reset #*ose a** open fi*es and f*us" a** fi*es to dis(& RmDir,pat". Remoe a directory& See( Wn, pos Set t"e position for t"e ne3t %ritin$ or readin$ in a fi*e& SetAttr,pat", attr. Set fi*e attributes& ;rite Wn, strin$ ;rite data to a fi*e& &.1. )sing )%. notation to specif' a file Many of t"e functions in Tab*e A@ specify a fi*e or pat"& T"ese functions accept bot" system9specific names and 5niform Resource Locator ,5RL. notation& T"is is t"e same notation used by your ;eb bro%ser& Tab*e AB s"o%s e3amp*es& Table 59. URL e.amples. System System Pat6 *&L Pat6 ;indo%s c:STempS"e*p&t3t fi*e:---c:-Temp-"e*p&t3t ;indo%s c:SMy Documents fi*e:---c:-MyX20Documents 5ni3 -"ome-andy-Temp-"e*p&t3t fi*e:---"ome-andy-Temp-"e*p&t3t 5ni3 -"ome-andy-My Documents fi*e:---"ome-andy-MyX20Documents TIP T"e statement DS"e**,Z#:S'ro$ 0i*esSca*c&e3eZ,2.F fai*ed because t"ere is a space in t"e pat"& T"e S"e** statement passes t"e strin$ to t"e command s"e**, %"ic" interprets t"e portion of t"e pat" before t"e space as t"e pro$ram to run& 5RL notation aoids t"is prob*em& 1ne adanta$e of 5RL notation is t"at specia* c"aracters are encoded& Ar$uments t"at are passed to a s"e**, for e3amp*e, fre8uent*y "ae prob*ems %it" pat"s t"at contain a space& )n 5RL notation, spaces are encoded as DX20F ,see Tab*e AB.& 5se t"e functions #onertTo5RL to conert a system9specific pat" to 5RL notation and #onert0rom5RL to conert to a system9specific pat"& Listing 149. /onverting to and from a URL. Sub 3o"ro!0R, Print Con:ert3o0R,B"+(o!e+and.+loo&!i$$"C Print Con:ert"ro!0R,B"$ile:+++(o!e+and.+loo&!i$$"C )3(i# re;uire# 0HI/ Print Con:ert3o0R,B"c:\M. -ocu!ent#"C )3(i# re;uire# Windo*# Print Con:ert"ro!0R,B"$ile:+++c:+M.G'7-ocu!ent#"C )3(i# re;uire# *indo*# End Sub 165 Specia* c"aracters, suc" as t"e space, are encoded %it" a percent si$n ,X. fo**o%ed by t"e AS#)) a*ue of t"e c"aracter encoded as a t%o9di$it "e3adecima* number& T"e space c"aracter "as an AS#)) a*ue of 32, %"ic" is 20 in "e3adecima* format& T"is is %"y a space is encoded as X20& Listing 150. *pecial URL characters. Sub 0R,SpecialEncodin Print Con:ert"ro!0R,B"$ile:+++G?>G?'G?%+GA>GA'GA%"C )+ABC+abc B0HI/C Print Con:ert"ro!0R,B"$ile:++c:+G?>G?'G?%+GA>GA'GA%"C)+ABC+abc BWindo*#C End Sub 5RL notation is system independent, so 5RL pat"s %or( as %e** on an App*e computer as t"ey do on a ;indo%s computer& To create a system9specific pat", use t"e function Jet'at"Separator to obtain t"e system9specific pat" separator& Listin$ 1A1 demonstrates "o% to use Jet'at"Separator to bui*d a comp*ete pat"& ;indo%s9based computers use DSF as t"e pat" separator, and 5ni39based computers use D-F as t"e pat" separator& 5RL notation uses D-F as t"e separator re$ard*ess of t"e operatin$ system& Listing 151. Use <et9ath*eparator67 rather than >LA or >,A. #Pat(3o"ile 6 "C:\te!p" #Boo1Ha!e 6 "OOME&odt" #Pat(3oBoo1 6 #Pat(3o"ile 4 JetPat(SeparatorBC 4 #Boo1Ha!e TIP Oisua* +asic for App*ications ,O+A. does not support t"e function Jet'at"Separator, but it does "ae t"e property App*ication&'at"Separator, %"ic" a*%ays returns a bac(s*as", een on a Macintos" computer& O+A a*so does not support #onertTo5RL or #onert0rom5RL& &.2. "irector' manipulation functions Some functions app*y e8ua**y %e** to directories as %e** as fi*es& T"is section is concerned %it" t"ose t"at app*y on*y to directories& T"e function #urDir, %it" a drie specifier as t"e ar$ument, returns t"e current directory for t"e specified drie& See Listin$ 1A2 and 0i$ure AA& )f t"e ar$ument is omitted, t"e current directory for t"e current drie is returned& T"e drie specifier is i$nored on 5ni3 systems& T"e initia* a*ue of t"e current directory is system dependent and may c"an$e dependin$ upon "o% 11o is started& )f you start 11o from a command9*ine prompt, youG** *i(e*y "ae a different current directory t"an if you start 11o from a menu or anot"er app*ication& 0or some operatin$ systems, usin$ 0i*e a 1pen to open an e3istin$ document sets t"e current directory to t"e directory containin$ t"e opened document ,) "ae seen t"is in ;indo%s.& )n some operatin$ systems, suc" as Linu3, t"is does not affect t"e current directory& Do not re*y on t"is be"aiorT Listing 152. 9rint the current directory. Sub Exa!pleCur-ir M#Box "Current director. on t(i# co!puter i# " 45 Cur-ir= 7= "Current -irector. Exa!ple" End Sub Figure 55. /ur#ir returns the current directory. 166 T"e functions #"Dir and #"Drie, a*t"ou$" present in 11o +asic, do not"in$ and %i** *i(e*y be remoed from t"e *an$ua$e& T"eir ori$ina* purpose %as to c"an$e t"e current drie and directory, but t"is %as a system %ide c"an$e, %"ic" is dan$erous in mu*titas(in$ enironments *i(e %e use today& T"e initia* current directory is dependent upon t"e operatin$ system and "o% 11o %as opened& T"e initia* a*ues, t"erefore, cannot be assumed& 5se t"e M(Dir function to create a directory, and RmDir to remoe a directory& )n Listin$ 1A3, a directory pat" is created from t"e ar$ument to M(Dir& )f an abso*ute pat" is not proided, t"e created directory is re*atie to t"e current directory as obtained %it" t"e function #urDir& T"e function RmDir remoes t"e directory, a** directories be*o% it, and a** fi*es contained in t"e directories& T"is macro ca**s 11M2;or(Dir in Listin$ 16!& Listing 153. /reate and then remove directories in the OOM$ 'ork #irectory. Sub Exa!pleCreateR!-ir# I$ HO3 CreateOOMEWor1-irBC 3(en Exit Sub End I$ -i! #Wor1-irF -i! #Pat(F #Wor1-ir 6 OOMEWor1-irBC #Pat( 6 #Wor1-ir 4 "a" 4 JetPat(SeparatorBC 4 "b" M1-ir #Pat( Print "Created " 4 #Pat( R!OOMEWor1-irBC Print "Re!o:ed " 4 #Wor1-ir End Sub T"e code in Listin$ 1A3 uses abso*ute pat"s& )tGs possib*e to use re*atie pat"s, but ) stron$*y discoura$e it& T"e be"aior of t"e current directory is operatin$9system dependent& 0i*e9re*ated functions t"at a*so %or( %it" directories inc*ude Dir, 0i*eDateTime, 0i*e23ists, 0i*eLen, JetAttr, and 4ame& T"ese are discussed *ater& &.3. Cile manipulation functions T"is section e3p*ores functions t"at dea* %it" inspectin$ and manipu*atin$ entire fi*es, rat"er t"an t"e contents of t"ose fi*es& Some of t"ese functions "ae a dua* purpose, actin$ on bot" fi*es and directories& )n eac" case, t"e function accepts at *east one ar$ument t"at identifies a fi*e or directory& T"e fo**o%in$ t"in$s are true about ar$uments t"at identify fi*es or directories: If the path is not present, the current directory as returned by CurDir is used. The system representation and the URL notation are both allowed. For example, C:\tmp\foo.txt and file:///c:/tmp/foo.txt refer to the same file. Unless it is explicitly stated, a single file or directory must be uniquely identified. The only function that accepts a file specification is Dir, which returns a listing of files matching the file specification. 2ac" fi*e and directory "as attributes ,see Tab*e 60.& 2ac" attribute represents a sin$*e bit in a number, a**o%in$ eac" item in a pat" to "ae mu*tip*e attributes set at t"e same time& Some attributes "ae been deprecated to be more system dependent& 4ot a** systems support "idden or system fi*es, for e3amp*e& 5se JetAttr to return t"e attributes& 167 Table 60. +ile and directory attributes. Deprecated $ttri2te Description 4o 0 4orma*7 no bits set 4o 1 Read91n*y 6es 2 Eidden 6es ! System 4o @ Oo*ume 4o 16 Directory 4o 32 Arc"ie bit ,fi*e c"an$ed since *ast bac(ed up. T"e function in Listin$ 1A! accepts an attribute from t"e JetAttr function and returns an easy9to9understand strin$& )f no bits are set, t"e attributes indicate a norma* fi*e& Listing 154. 9rint attributes as a string. REM u#e# bit*i#e co!pari#on to read t(e attribute# "unction "ileAttributeStrinBx A# InteerC A# Strin -i! # A# Strin I$ Bx 6 7C 3(en # 6 "Hor!al" El#e I$ Bx AH- >AC ED 7 3(en # 6 "-irector." )-irector. bit 777>7777 #et I$ Bx AH- >C ED 7 3(en # 6 # 4 " Read9Onl." )read9onl. bit 7777777> #et I$ Bx AH- 'C ED 7 3(en # 6 # 4 " Hidden" )-eprecated I$ Bx AH- ?C ED 7 3(en # 6 # 4 " S.#te!" )-eprecated I$ Bx AH- QC ED 7 3(en # 6 # 4 " Oolu!e" )Oolu!e bit 7777>777 #et I$ Bx AH- %'C ED 7 3(en # 6 # 4 " Arc(i:e" )Arc(i:e bit 77>77777 #et End I$ "ileAttributeStrin 6 # End "unction TIP Listin$ 1A! performs bit operations ,e3p*ained *ater. to determine %"ic" attributes are set& 5se t"e JetAttr function to $et t"e attributes of a fi*e, and use SetAttr to set t"e attributes& T"e first ar$ument to t"e function SetAttr is t"e name of t"e fi*e L re*atie or abso*ute L and t"e second ar$ument is a number representin$ t"e attributes to set or c*ear& )n ot"er %ords, after ca**in$ SetAttr,name, n., t"e function JetAttr,name. s"ou*d return t"e inte$er n& 0or e3amp*e, ca**in$ SetAttr %it" t"e attribute set to 32 sets t"e arc"ie bit and c*ears a** t"e ot"ers so JetAttr returns 32& To set more t"an one bit at t"e same time, use t"e 1R operator to combine attributes& 5se SetAttr,fi*e4ame, 1 1R 32. to set bot" t"e arc"ie bit and t"e read9on*y bit& SetAttr %or(s on directories as %e** as fi*es& TIP Attributes faor t"e ;indo%s enironment& 1n 5ni39based operatin$ systems suc" as Linu3 and Sun, settin$ attributes affects t"e user, $roup, and %or*d settin$s& Settin$ t"e attribute to 0 ,not read9on*y. corresponds to Dr%3r%3r%3F& Settin$ t"e attribute to 1 ,read9on*y. corresponds to Dr r rF& 5se t"e 0i*eLen function to determine t"e *en$t" of a fi*e& T"e return a*ue is a *on$& T"e function in Listin$ 1AA obtains t"e fi*e *en$t" and t"en creates a pretty strin$ to disp*ay t"e *en$t"& T"e fi*e *en$t" is returned in 168 bytes L <, M+, J, or T L dependin$ on t"e *en$t"& T"is produces a more easi*y understood resu*t t"an a simp*e number& Listing 155. #isplay a number in a nice readable form such as =M rather than =C20. "unction Prett."ile,enBpat(FC A# Strin Prett."ile,en 6 nPrett."ile,enB"ile,enBpat(CC End "unction "unction nPrett."ile,enBB.Oal n A# -oubleC A# Strin -i! i A# Inteer )Count nu!ber o$ iteration# -i! :BC A# Oariant )Hold# abbre:iation# $or ^ilob.te#= Meab.te#= &&& :BC 6 Arra.B"b.te#"= "^"= "MB"= "J"= "3"C )Abbre:iation#
REM E:er. ti!e t(at t(e nu!ber i# reduced b. > 1ilob.te= REM t(e counter i# increa#ed b. >& REM -o not decrea#e t(e #i8e to le## t(an > 1ilob.te& REM -o not increa#e t(e counter b. !ore t(an t(e #i8e o$ t(e arra.& -o W(ile n D >7'? AH- iW> E 0BoundB:BCC n 6 "ixBn + >7'?C )3runcate a$ter t(e di:i#ion i 6 i W > )Started at i67 Bb.te#C incre!ent to next abbre:iation ,oop nPrett."ile,en 6 CStrBnC 4 :BiC End "unction 5se t"e 0i*e23ists function to determine if a fi*e or directory e3ists& 5se 0i*eDateTime to return a strin$ %it" t"e date and time t"at a fi*e %as created or *ast modified& T"e returned strin$ is in a system9dependent format& 1n my computer, t"e format is DMM-DD-6666 EE:MM:SSF& T"e returned strin$ can be passed direct*y to t"e function #Date& T"e Jet0i*e)nfo macro in Listin$ 1A6 uses a** of t"e fi*e and directory inspection functions to return information in an easy9to9read format& A*so see 0i$ure A6& Listing 156. <et information about a file. "unction Jet"ileIn$oBpat(C A# Strin -i! # A# Strin -i! iAttr A# Inteer # 6 "3(e pat( """ 4 pat( 4 """" I$ Hot "ileExi#t#Bpat(C 3(en Jet"ileIn$o 6 # 4 " doe# not exi#t" Exit "unction End I$ # 6 # 4 " exi#t#" 4 CHRFB>7C # 6 # 4 "-ate and 3i!e 6 " 4 "ile-ate3i!eBpat(C 4 CHRFB>7C iAttr 6 JetAttrBpat(C REM 3(e lent( o$ a director. i# al*a.# 8ero I$ BiAttr AH- >AC 6 7 3(en # 6 # 4 ""ile lent( 6 " 4 Prett."ile,enBpat(C 4 CHRFB>7C End I$ # 6 # 4 "Attribute# 6 " 4 "ileAttributeStrinBiAttrC 4 CHRFB>7C Jet"ileIn$o 6 # End "unction 169 Figure 56. Nou can learn a lot about a file by using the file4inspection functions. 5se t"e <i** statement to de*ete a fi*e from t"e dis(& A run9time error occurs if t"e fi*e does not e3ist& ^illB"C:\te!p\Bad"ile&txt"C 5se t"e 0i*e#opy function to copy fi*es& T"e first ar$ument is t"e fi*e to copy and t"e second ar$ument is t"e destination fi*e& See Tab*e 61& T"e 0i*e#opy function is ab*e to recursie*y copy entire directories, but it canGt "and*e fi*e specifications& Surprisin$*y, if t"e first ar$ument is a fi*e, t"e second ar$ument must a*so be a fi*e L ) e3pected t"at ) cou*d copy a fi*e to a directory %it" 0i*e#opy,Z#:Sauto&batZ, Z#:Sba(SZ.& Table 61. -rguments to +ile/opy. Valid Sorce Destination Comment 6es 0i*e 0i*e #opy t"e fi*e& T"e names do not "ae to be t"e same& 6es Directory Directory Recursie*y copy a** fi*es and directories contained in one directory to anot"er directory& 4o fi*e spec 0i*e specifications ,%i*dcards, for e3amp*e, \&\. are not a**o%ed& 4o 0i*e Directory )f t"e source is a fi*e, t"e destination must a*so be a fi*e& "ileCop.B"C:\auto&bat"= "C:\auto&ba1"C )Cop. $ile "ileCop.B"C:\auto&bat"= "C:\t!p\auto&bat"C )Cop. $ile "ileCop.B"C:\lo#"= "C:\ba1"C )Cop. director. TIP Do not recursie*y copy a directory into itse*f L t"is creates an infinite *oop& 0or e3amp*e, 0i*e#opy,Z#:S*o$sZ, Z#:S*o$sSba(Z. %i** neer finis" because t"e Dba(F subdirectory immediate*y becomes part of t"e contents of D*o$sF, %"ic" t"en "as to be copied as %e**& +ad idea& 5se t"e 4ame statement to rename a fi*e or directory& T"is statement "as an unusua* synta3: )t p*aces t"e (ey%ord As bet%een t"e source and destination names& Ha!e "C:\Moe&txt" A# "C:\bill&txt" )Rena!e a $ile Ha!e "C:\lo#" A# "C:\oldlo#" )Rena!e a director. Ha!e "C:\Moe&txt" A# "C:\t!p\Noe&txt" )Mo:e t(e $ile to t(e t!p director. Ha!e "C:\lo#" A# "C:\ba1\lo#" )Mo:e t(e lo# director. TIP A common po%er9user tric( is to use t"e 4ame command to moe a fi*e or directory from one *ocation to anot"er& &.4. Cile attributes4 bitmas*s4 and binar' numbers )t isnGt necessary to understand binary numbers and bitmas(s to use eit"er fi*e attributes or bitmas(s in 11o +asic, so donGt panic7 simp*y s(ip t"e parts t"at ma(e your "ead spin& 5nderstandin$ t"is materia*, "o%eer, ma(es it simp*er to understand %"at is "appenin$ %it" fi*e attributes and "o% to use t"em& 170 T"e fi*e and directory attributes in Tab*e 60 %ere strate$ica**y c"osen to "ae a nice property %"en %ritten in base 2 ,see Tab*e 62. L eac" attribute "as on*y one bit set& Pero is a specia* case L it "as no bits set& Table 62. +ile and directory attributes. Decimal $ttri2te Binary $ttri2te Description Comment 00 0000 0000 4orma* 4o bits set 01 0000 0001 Read91n*y +it 1 set 02 0000 0010 Eidden +it 2 set 0! 0000 0100 System +it 3 set 0@ 0000 1000 Oo*ume +it ! set 16 0001 0000 Directory +it A set 32 0010 0000 Arc"ie +it 6 set 5se JetAttr to obtain t"e attributes of a fi*e or pat"& )f t"e fi*e or pat" is a directory, t"en bit A is set& )f t"e fi*e or pat" is read9on*y, t"en bit 1 is set& A returned attribute of 0 means t"at no bits are set and t"at t"is is a norma* fi*e& #onsider an attribute a*ue of 33, %"ic" in binary is 0010 0001& +it 1 is set, so t"is is read9on*y& +it 6 is set, so t"is fi*e "as c"an$ed since it %as *ast arc"ied& 6ou can see t"at you donGt need to (no% "o% to conert a decima* number into a binary number& Eo%eer, you do need to (no% "o% to %rite a macro to determine %"ic" bits are set and %"ic" bits are not set& 5se t"e A4D operator to determine %"ic" bits are set& ;it" A4D, t%o t"in$s must bot" be true for t"e ans%er to be true& 0or e3amp*e, my f*as"*i$"t %or(s if it "as a *i$"t bu*b A4D it "as batteries& T"e A4D operator %or(s %it" numbers by performin$ t"is *o$ica* operation on eac" of t"e bits& 0or e3amp*e, D3 A4D AF represented as base 2 is D0011 A4D 0101 ? 0001F& +it 1 L t"e bit in t"e ri$"tmost position L in eac" number is e8ua* to 1, so bit 1 in t"e resu*t is a*so 1& A** of t"e ot"er bits do not "ae correspondin$ 1s in t"e same position, so a** of t"e ot"er bits in t"e resu*t e8ua* Cero& 4o% )G** app*y t"is idea to t"e prob*em at "and& )f t"e numeric a*ue of an attribute is not Cero, t"en at *east one property is set& Jien t"is, you can t"en c"ec( eac" attribute as i**ustrated by t"e e3amp*e in Tab*e 63& Table 63. /heck attribute value FF 6(CCCC(7 for each file property. 6ead7Onl" ;idden "stem 5olume (irector" )rchi'e >7 777> AH- 77 777> B>C 77 777> >7 777> AH- 77 77>7 B7C 77 7777 >7 777> AH- 77 7>77 B7C 77 7777 >7 777> AH- 77 >777 B7C 77 7777 >7 777> AH- 7> 7777 B7C 77 7777 >7 777> AH- >7 7777 B%'C>7 7777 To do t"is in 11o +asic, use code simi*ar to t"e fo**o%in$: I$ 3(eAttribute 6 7 3(en REM Ho attribute# #et El#e I$ B3(eAttribute AH- >C 6 > 3(en &&& )Read9Onl. $ile: bit > i# #et I$ B3(eAttribute AH- >AC 6 >A 3(en &&& )-irector.: bit < i# #et& I$ B3(eAttribute AH- ?C ED 7 3(en &&& )Anot(er *a. to code t(e #a!e loic& End I$ 2ac" fi*e and directory "as an attribute defined as t"ese bit patterns& )f a bit in t"e attribute t"at corresponds to a particu*ar property is set, t"en t"e fi*e "as t"at property& 'erformin$ t"e A4D operator %it" t"e 171 indiidua* bit positions determines if t"e fi*e "as t"at property& T"e function 0i*eAttributeStrin$ in Listin$ 1A! uses t"is met"od& To set t"e arc"ie bit and read9on*y bit on a fi*e, combine t"e bits and ca** t"e function once& 5se t"e 1R operator to combine bit patterns& ;it" t"e 1R operator, if eit"er bit is set, t"e resu*tin$ bit is a 1& To set t"e read9on*y and t"e arc"ie bits, use D1 1R 32F& )f you set t"e attributes to 1, t"en a** of t"e ot"er attributes %i** be c*eared and on*y t"e read9on*y bit %i** be set& &.. Obtaining a director' listing 5se t"e Dir function to obtain a directory *istin$& T"e first ar$ument is a fi*e specification& A*t"ou$" a fi*e or directory may be uni8ue*y identified, fi*e specs ,a*so ca**ed %i*dcards. are a**o%ed& 0or e3amp*e, t"e command Dir,Z#:StempS\&t3tZ. returns a *ist of a** fi*es t"at "ae t"e e3tension TIT& T"e second ar$ument specifies attributes, for %"ic" t"ere are t%o a*id a*ues: 0 ,t"e defau*t. returns fi*es7 set t"e second ar$ument to 16 to retriee a *ist of directories& TIP Most operatin$ systems contain t%o specia* directory names, represented by a sin$*e period ,&. and a doub*e period ,&&.& A sin$*e period references t"e current directory, and t%o periods reference t"e parent directory& T"ese specia* directories are inc*uded in t"e directory *ist as returned by t"e Dir function& )f you %rite a macro t"at *oo(s at eac" directory recursie*y but you donGt ta(e t"ese t%o into consideration, your macro %i** erroneous*y run foreer& T"e first ca** to Dir starts readin$ a directory and returns t"e first fi*e t"at matc"es& 2ac" additiona* ca**, %"ic" ta(es no ar$uments, returns t"e ne3t fi*e t"at matc"es& #"ileHa!e 6 -irBpat(= attributeC )Jet t(e $ir#t one -o W(ile B#"ileHa!e ED ""C )W(ile #o!et(in $ound #"ileHa!e 6 -irBC )Jet t(e next one ,oop )f t"e pat" uni8ue*y identifies a fi*e or directory, on*y one entry is returned& 0or e3amp*e, t"e command Dir,Z#:StmpSautoe3ec&batZ. returns t"e sin$*e fi*e Dautoe3ec&batF& Less obious*y, t"e command Dir,Z#:StmpZ. returns t"e sin$*e directory DtmpF& To determine %"at a directory contains, t"e pat" must eit"er contain a fi*e specifier ,#:StmpS\&\. or t"e pat" must contain a trai*in$ pat" separator ,#:StmpS.& T"e code in Listin$ 1AM performs a simp*e *istin$ of t"e current directory7 it uses t"e function Jet'at"Separator to obtain t"e pat" separator in an operatin$9system9independent %ay& Listing 157. List the files in the current directory. Sub Exa!ple-ir -i! # A# Strin )3e!porar. #trin -i! #"ileHa!e A# Strin ),a#t na!e returned $ro! -IR -i! i A# Inteer )Count nu!ber o$ dir# and $ile# -i! #Pat( )Current pat( *it( pat( #eparator at end #Pat( 6 Cur-ir 4 JetPat(SeparatorBC )Wit( no #eparator= -IR return# t(e #"ileHa!e 6 -irB#Pat(= >AC )director. rat(er t(an *(at it contain# i 6 7 )Initiali8e t(e :ariable -o W(ile B#"ileHa!e ED ""C )W(ile #o!et(in returned i 6 i W > )Count t(e directorie# # 6 # 4 "-ir " 4 CStrBiC 45 " 6 " 4 #"ileHa!e 4 CHRFB>7C )Store in #trin $or later printin #"ileHa!e 6 -irBC )Jet t(e next director. na!e ,oop i 6 7 )Start countin o:er $or $ile# 172 #"ileHa!e 6 -irB#Pat(= 7C )Jet $ile# t(i# ti!eK -o W(ile B#"ileHa!e ED ""C i 6 i W > # 6 # 4 ""ile " 4 CStrBiC 4 " 6 " 4 #"ileHa!e 4 " " 45 Prett."ile,enB#Pat( 4 #"ileHa!eC 4 CHRFB>7C #"ileHa!e 6 -irBC ,oop M#Box #= 7= Con:ert3o0R,B#Pat(C End Sub Samp*e output from Listin$ 1AM is s"o%n in 0i$ure AM& 0irst, t"e directories are *isted& T"e first t%o directories, D&F and D&&F, represent t"e fo**o%in$: $ile:+++(o!e+and.+M.G'7-ocu!ent#+OpenO$$ice+ $ile:+++(o!e+and.+M.G'7-ocu!ent#+ T"e inc*usion of D&F and D&&F is a common source of prob*ems& A *istin$ of directories contains t"ese t%o directories, %"ic" s"ou*d usua**y be i$nored& Figure 57. #irectory listing of the current directory. &.#. Open a file 1pen1ffice&or$ uses *o%9*ee*, system9specific met"ods to manipu*ate fi*es& T"e operatin$ system maintains a *ist of t"e open fi*es and identifies t"em %it" a number, %"ic" is ca**ed a Dfi*e "and*e&F )n t"e %or*d of +asic, t"is is usua**y ca**ed t"e Dfi*e numberF or Ddata c"anne*&F To open a fi*e, you must te** it %"at fi*e number ,fi*e "and*e. to use& 5se t"e 0ree0i*e function to obtain an unused fi*e number, %"ic" %i** be used %"en openin$ a fi*e, referencin$ t"e open fi*e, and %"en c*osin$ t"e fi*e& T"e 1pen statement is used to open a fi*e before it is usab*e for readin$ or %ritin$& T"e 1pen statement re8uires a fi*e number, %"ic" s"ou*d a*%ays be obtained from t"e 0ree0i*e function& 5se t"e #*ose statement %"en you are finis"ed %it" t"e fi*e& 6ou can c*ose mu*tip*e fi*es in a sin$*e statement by proidin$ a comma9 separated *ist of numbers after t"e #*ose statement& 5se t"e Reset function to c*ose a** of t"e open fi*es at one time %it"out "ain$ to e3p*icit*y *ist t"e fi*e numbers& A** open fi*e numbers are c*osed and t"eir data is f*us"ed to dis(& n 6 "ree"ileBC 173 Open "ileHa!e "or Mode XAcce## ioModeY X,oc1 ModeY A# Ln X,en6-atalenY Clo#e Ln D0i*e4ameF is t"e name of t"e fi*e t"at you %ant to open& )f t"e fi*e name does not inc*ude t"e pat", t"e current directory is assumed& D0or ModeF specifies t"e state of t"e fi*e %"en it is opened and "o% you intend to use t"e fi*e ,see Tab*e 6!.& Table 64. 3alid >+or ModeA values and the resulting configuration if -ccess is not used. +or Mode +ile <ointer +ile Exists -o +ile 6ead 8rite Comment For Append end Open Create Yes Yes Sequential access For nput start Open error Yes No Sequential access For Output start Delete Create Yes Yes Sequential access For Binary start Delete Create Yes Yes Random access For Random start Delete Create Yes Yes Random access 2ac" mode "as its o%n set of be"aiors as s"o%n in Tab*e 6!& #onsider t"e ro% 0or )nput, t"is can be read to say: ;"en a fi*e is opened D0or )nputF: 1& T"e fi*e pointer is positioned at t"e start of t"e fi*e& 2& )f t"e fi*e e3ists, it is opened ,and not de*eted.& 3& )f t"e fi*e does not e3ist, an error is $enerated& !& T"e fi*e is opened %it" read access, but not %rite access ,assumin$ t"at Access is not e3p*icit*y proided.& A& Se8uentia* access is used for readin$ t"e fi*e& 5nfortunate*y, t"e precise imp*ementation is dependent on t"e operatin$ system and een t"e compi*er used to create your ersion of 11o7 for e3amp*e, on some systems, you can %rite to a fi*e opened for )nput& ;"en a fi*e is open, a pointer into t"e fi*e is maintained& T"is pointer identifies %"ere t"e ne3t read or %rite operation %i** occur& 0or e3amp*e, if t"e fi*e pointer is at t"e start of t"e fi*e, t"e ne3t DreadF command %i** read t"e first t"in$ in t"e fi*e& )f t"e fi*e pointer is at t"e end of t"e fi*e, t"e ne3t D%riteF command %i** append data to t"e end of t"e fi*e& 6ou "ae some contro* oer t"e initia* position of t"e fi*e pointer %"en t"e fi*e is opened, and you can moe t"is fi*e pointer around %"en t"e fi*e is open& A** of t"e D0orF modes, e3cept D0or Append,F position t"e fi*e pointer at t"e start of t"e fi*e& 6ou can access a fi*e se8uentia**y or random*y& A se8uentia* fi*e is simi*ar to a ideo tape& A*t"ou$" you can fast for%ard and re%ind t"e tape to a specific *ocation on t"e tape, t"e entire tape moes past t"e read-%rite "ead& 6ou t"en press '*ay or Record and t"e data is eit"er se8uentia**y read from or %ritten to t"e tape& A random fi*e is simi*ar to a music #D& A*t"ou$" you can p*ay t"e #D se8uentia**y, it isnGt re8uired7 you can 8uic(*y /ump to any son$ and p*ay it& To ma(e t"e ana*o$y more accurate, "o%eer, eac" son$ on t"e #D must be t"e same siCe& T"is is t"e disadanta$e to t"e D0or RandomF mode& #onsider storin$ names of different *en$t"s in a fi*e on t"e dis(& Storin$ one name per *ine in t"e fi*e is efficient %it" respect to space& 6ou can use a ne%9*ine c"aracter bet%een eac" name& To find a specific name in t"e fi*e, you start at t"e be$innin$ and read unti* you find t"e personGs name& 1n t"e ot"er "and, if you (no% t"at t"e *on$est name is 100 c"aracters, you can store eac" name on t"e dis(, and store enou$" spaces after t"e name to use a tota* of 100 c"aracters for eac" name& T"is %astes space, but it a**o%s you to 8uic(*y moe bet%een names on t"e dis(, because of t"e re$u*ar fi*e structure& To read or %rite t"e 1000t" name in t"e fi*e, you simp*y moe direct*y to t"at record& 6ou "ae %asted space in t"is desi$n, but you "ae $ained 174 speed performance& A** of t"e D0orF modes,F e3cept D0or +inaryF and D0or Random,F specify se8uentia* fi*e access& Random fi*es use t"is abi*ity to fi3 t"e record *en$t" to t"e ma3imum siCe of interest in order to permit ery rapid fi*e access and retriea*& T"e access modes in Tab*e 6A affect t"e defau*t treatment of a fi*e %"en it is opened& ;"en an access mode is specified, it a*so erifies t"at you "ae access to eit"er read or %rite t"e fi*e& )f you do not "ae %rite access to a fi*e opened %it" DAccess ;rite,F a run9time error occurs& T"e access mode affects eery open D0orF mode e3cept D0or AppendF L %"ic" neer de*etes an e3istin$ fi*e %"en it is opened& Table 65. 3alid -ccess ioModes. $ccess io)ode Description Access Read Do not de*ete an e3istin$ fi*e& Oerify t"at you "ae read access& Access ;rite De*ete an e3istin$ fi*e& Oerify t"at you "ae %rite access& Access Read ;rite De*ete an e3istin$ fi*e& Oerify t"at you "ae read and %rite access& 5sin$ DAccess ;riteF %"i*e openin$ a fi*e D0or )nputF a**o%s you to %rite to t"e fi*e after it is opened7 first t"e fi*e is erased and t"en a ne% fi*e is created& After t"e fi*e is open, different operatin$ systems enforce t"e access ri$"ts different*y& As of 11o ersion 1&1&1, openin$ a binary or random fi*e %it" DAccess ReadF a**o%s you to %rite to t"e fi*e %"en usin$ ;indo%s, but not on Linu3& )t is a*%ays safe to open a fi*e D0or AppendF and t"en moe t"e fi*e pointer to t"e start of t"e fi*e manua**y& TIP T"e on*y safe %ay to open a fi*e for bot" readin$ and %ritin$ %it"out erasin$ t"e contents of t"e fi*e is to open t"e fi*e D0or Append,F and t"en moe t"e fi*e pointer to t"e start of t"e fi*e& To *imit access to a fi*e %"i*e itGs open, use t"e DLoc(F modes ,see Tab*e 66.& T"is preents ot"ers from readin$ and-or %ritin$ to t"e fi*e %"i*e you "ae it open& T"is is primari*y used in mu*ti9user enironments because you canGt contro* %"at ot"ers mi$"t try to do %"i*e you are usin$ t"e fi*e& Table 66. 3alid protected keywords. Loc0 )ode Description Loc( Read 1t"ers cannot read t"e fi*e %"i*e itGs open, but t"ey can %rite to it& Loc( ;rite 1t"ers cannot %rite t"e fi*e %"i*e itGs open, but t"ey can read from it& Loc( Read ;rite 1t"ers cannot read or %rite t"e fi*e %"i*e it is open& 5se t"e Len (ey%ords to specify t"e siCe of eac" record %"en t"e fi*e is opened D0or RandomF ,discussed *ater.& &.$. !nformation about open files 11o +asic "as functions t"at return fi*e information by usin$ t"e fi*e name ,see Listin$ 1A6.& )t is a*so possib*e to obtain information about open fi*es from t"e fi*e number& T"e 0i*eAttr function returns "o% t"e fi*e associated %it" t"e $ien fi*e number %as opened& Tab*e 6M *ists t"e return a*ues and t"eir meanin$s& "ileAttrBn= >C )Ho* t(e $ile *a# opened in BASIC u#in Open "or &&& 175 Table 67. #escription of +ile-ttr67 return values. &etrn Vale Description 1 1pen 0or )nput 2 1pen 0or 1utput ! 1pen 0or Random @ 1pen for Append 16 1pen 0or +inary 32 Documentation incorrect*y states t"at t"is is for open for binary& TIP 0i*eAttr is incorrect*y documented& 0i*eAttr,n, 2. does not return a system fi*e "and*e, if t"e second ar$ument is not 1, t"e return a*ue is a*%ays 0& Anot"er prob*em is t"at t"e inc*uded "e*p incorrect*y states t"at +inary "as a return a*ue of 32& 5se t"e 210 function to determine if t"e end of t"e fi*e "as been reac"ed& A typica* use is to read a** of t"e data unti* D2nd 1f 0i*e&F n 6 "ree"ile )Al*a.# $ind t(e next $ree $ile nu!ber Open "ileHa!e "or Input A# Ln )Open t(e $ile $or input -o W(ile HO3 EO"BnC )W(ile HO3 End O$ "ile Input Ln= # )Read #o!e dataK REM Proce## t(e input (ereK ,oop 5se t"e L10 function to determine t"e *en$t" of an open fi*e& T"is number is a*%ays in bytes& ,O"BnC 5se t"e Loc function to obtain t"e current *ocation of t"e fi*e pointer& T"is number is not a*%ays accurate and t"e return a*ue "as a different meanin$ dependin$ on "o% t"e fi*e %as opened& Loc returns t"e actua* byte position for fi*es opened in +inary mode& 0or Random fi*es, Loc returns t"e record number of t"e *ast record read or %ritten& 0or se8uentia* fi*es opened %it" )nput, 1utput, or Append, "o%eer, t"e number returned by Loc is t"e current byte position diided by 12@& T"is is done to maintain compatibi*ity %it" ot"er ersions of +AS)#& ,ocBnC TIP )f a fi*e is opened in a mode ot"er t"an Random, and 11o +asic considers t"e fi*e a te3t fi*e, Loc returns t"e *ine number t"at %i** be read ne3t& ) cannot decide if t"is is a bu$ or /ust incomp*ete documentation& Sometimes t"e return a*ues from Loc are /ust %ron$& 0or e3amp*e, if you open a fi*e for output and t"en %rite some te3t, Loc returns 0& T"e See( function, %"en used %it" on*y one ar$ument, returns t"e ne3t position t"at %i** be read or %ritten& T"is is simi*ar to t"e Loc function e3cept t"at for se8uentia* fi*es, t"e abso*ute byte position is a*%ays returned& )f you %ant to sae t"e position in a fi*e and return to it *ater, use t"e See( function to obtain t"e current fi*e pointer7 t"en you can use t"e See( function to return t"e fi*e pointer to t"e ori$ina* *ocation& po#ition 6 See1BnC )Obtain and #a:e t(e current po#ition& #tate!ent# )-o arbitrar. #tu$$& See1Bn= po#itionC )Mo:e t(e $ile pointer bac1 to t(e oriinal po#ition& 176 T"e ar$ument for settin$ t"e fi*e pointer usin$ t"e See( function is t"e same as t"e a*ue returned by t"e See( function& 0or Random fi*es, t"e position is t"e number of t"e ob/ect to read, not t"e byte position& 0or se8uentia* fi*es, t"e position is t"e byte position in t"e fi*e& T"e macro in Listin$ 1A@ returns information about an open fi*e from t"e fi*e number, inc*udin$ t"e open mode, fi*e *en$t", and fi*e pointer *ocation& Listin$ 1AB uses Listin$ 1A@, and t"e resu*t is s"o%n in 0i$ure A@& Listing 158. Return information about an open file as a string. "unction JetOpen"ileIn$oBn A# InteerC A# Strin -i! # A# Strin -i! iAttr A# Inteer On Error Jo3o Bad"ileHu!ber iAttr 6 "ileAttrBn= >C I$ iAttr 6 7 3(en # 6 ""ile (andle " 4 CStrBnC 4 " i# not currentl. open" 4 CHRFB>7C El#e # 6 ""ile (andle " 4 CStrBnC 4 " *a# opened in !ode:" I$ BiAttr AH- >C 6 > 3(en # 6 # 4 " Input" I$ BiAttr AH- 'C 6 ' 3(en # 6 # 4 " Output" I$ BiAttr AH- ?C 6 ? 3(en # 6 # 4 " Rando!" I$ BiAttr AH- QC 6 Q 3(en # 6 # 4 " Append" I$ BiAttr AH- >AC 6 >A 3(en # 6 # 4 " Binar." iAttr 6 iAttr AH- HO3 B> OR ' OR ? OR Q OR >AC I$ iAttr AH- HO3 B> OR ' OR ? OR Q OR >AC ED 7 3(en # 6 # 4 " un#upported attribute " 4 CStrBiAttrC End I$ # 6 # 4 CHRFB>7C # 6 # 4 ""ile lent( 6 " 4 nPrett."ile,enB,O"BnCC 4 CHRFB>7C # 6 # 4 ""ile location 6 " 4 CStrB,OCBnCC 4 CHRFB>7C # 6 # 4 "See1 6 " 4 CStrBSee1BnCC 4 CHRFB>7C # 6 # 4 "End O$ "ile 6 " 4 CStrBEO"BnCC 4 CHRFB>7C End I$ All-one: On Error Jo3o 7 JetOpen"ileIn$o 6 # Exit "unction Bad"ileHu!ber: # 6 # 4 "Error *it( $ile (andle " 4 CStrBnC 4 CHRFB>7C 45 "3(e $ile i# probabl. not open" 4 CHRFB>7C 4 ErrorBC Re#u!e All-one End "unction TIP T"e position ar$ument passed to t"e See( function is one9based, not Cero9based& T"is means t"at t"e first byte or record is 1, not 0& 0or e3amp*e, See(,n, 1. positions t"e fi*e pointer to t"e first byte or record in t"e fi*e& T"e macro in Listin$ 1AB opens a fi*e for output& A *ar$e amount of data is %ritten to t"e fi*e to $ie it some siCe& At t"is point, t"e Loc function returns 0 and 210 returns True& T"e See( function is used to moe t"e fi*e pointer to a position in t"e fi*e t"at a**o%s some data to be read& T"e Loc function sti** returns 0& 1ne "undred pieces of data are read from t"e fi*e in order to adance t"e a*ue returned by t"e Loc function& 0ina**y, t"e fi*e is de*eted from t"e dis(& 0i$ure A@ s"o%s information based on a fi*e number& 177 Listing 159. /reate delme.t.t in the current directory and print file information. Sub WriteExa!pleJetOpen"ileIn$o -i! "ileHa!e A# Strin )Hold# t(e $ile na!e -i! n A# Inteer )Hold# t(e $ile nu!ber -i! i A# Inteer )Index :ariable -i! # A# Strin )3e!porar. #trin $or input "ileHa!e 6 Con:ert3o0R,BCur-irC 4 "+del!e&txt" n 6 "ree"ileBC )Hext $ree $ile nu!ber Open "ileHa!e "or Output Acce## Read Write A# Ln )Open $or read+*rite "or i 6 > 3o ><7%' )Write a lot o$ data Write Ln= "3(i# i# line "=CStrBiC="or"=i )Write #o!e text Hext See1 Ln= >7'' )Mo:e t(e $ile pointer to location >7'' "or i 6 > 3o >77 )Read >77 piece# o$ data\ t(i# *ill #et ,oc Input Ln= # )Read one piece o$ data into t(e :ariable # Hext M#Box JetOpen"ileIn$oBnC= 7= "ileHa!e Clo#e Ln ^illB"ileHa!eC )-elete t(i# $ile= I do not *ant it End Sub Figure 58. "nformation based on a file number. &.&. %eading and writing data 0i*es opened for Random and +inary data use t"e statements 'ut and Jet for %ritin$ and readin$ data& 0i*es opened in any ot"er mode use t"e Line )nput, )nput, 'rint, and ;rite statements for readin$ and %ritin$& )f no e3pressions are entered, a b*an( *ine is %ritten to t"e fi*e& T"e ;rite statement accepts mu*tip*e ar$uments to print to t"e fi*e and it automatica**y adds de*imiters as it %rites& )n t"e created fi*e, eac" e3pression is separated by a comma& Strin$s are enc*osed in doub*e 8uotation mar(s, numbers are not enc*osed in anyt"in$, and dates and +oo*ean a*ues are enc*osed bet%een octot"orpe ,W. c"aracters& Write Ln= expre##ion>= expre##ion'= expre##ion%= &&& Print Ln= expre##ion>= expre##ion'= expre##ion%= &&& TIP T"e c"aracter DWF "as many names, inc*udin$ number si$n, pound si$n, "as", s"arp, crunc", "e3, $rid, pi$pen, tic9tac9toe, sp*at, cross"atc", and octot"orpe, to name a fe%& T"e 'rint statement does not %rite any usefu* de*imiters& )nstead, it %rites spaces bet%een eac" e3pression& 4umbers typica**y use 13 spaces& Write Ln= i= "t(e ti!e L i#"= Ho*= C-blB>&''>C= CBoolB7C Print Ln= i= "t(e ti!e L i#"= Ho*= C-blB>&''>C= CboolB7C 178 T"e code aboe produces t"e te3t be*o%& 7="t(e ti!e L i#"=L72+7>+'7>7 '>:7<:?@L=>&''>=L"al#eL 7 t(e ti!e L i# 72+7>+'7>7 '>:7<:?@ >&''> "al#e Listin$ 160 demonstrates t"e difference bet%een ;rite and 'rint& Listing 160. #emonstrate 'rite versus 9rint. Sub Exa!pleWriteOrPrint -i! "ileHa!e A# Strin )Hold# t(e $ile na!e -i! n A# Inteer )Hold# t(e $ile nu!ber -i! i A# Inteer )Index :ariable -i! # A# Strin )3e!porar. #trin $or input -i! #3e!pF "ileHa!e 6 Con:ert3o0R,BCur-irC 4 "+del!e&txt" n 6 "ree"ileBC )Hext $ree $ile nu!ber Open "ileHa!e "or Output Acce## Read Write A# Ln )Open $or read+*rite Write Ln= i= "t(e ti!e L i#"= Ho*= C-blB>&''>C= CBoolB7C Print Ln= i= "t(e ti!e L i#"= Ho*= C-blB>&''>C= CBoolB7C
See1 Ln= > )Mo:e t(e $ile pointer to location > ,ine Input Ln= # ,ine Input Ln= #3e!p # 6 # 4 CHRFB>7C 4 #3e!p M#Box # Clo#e Ln ^illB"ileHa!eC )-elete t(i# $ile= I do not *ant it End Sub As its name imp*ies, t"e Line )nput statement reads an entire *ine of te3t ,see Listin$ 160., but it does not return t"e de*imiter& 2ac" *ine is de*imited by eit"er a carria$e return ,AS#)) a*ue 13. or a *ine9feed c"aracter ,AS#)) a*ue 10.& T"ese t%o de*imiters %or( to read *ines on eery operatin$ system supported by 1pen1ffice&or$& ,ine Input Ln= #trinOar )Read an entire line but not t(e deli!iter& T"e )nput statement reads te3t based on t"e fo**o%in$ de*imiters: comma, carria$e return, or *ine9feed c"aracters& T"e )nput statement can read mu*tip*e ariab*es of differin$ types in a sin$*e command& #"an$in$ Line )nput to )nput in Listin$ 160 causes on*y t"e first t%o items to be read rat"er t"an t%o *ines& Input Ln= :ar>= :ar'= :ar%= &&& T"e ;rite command adds appropriate de*imiters automatica**y so t"at you can read strin$ and numeric data into t"e appropriate ariab*e types& T"e )nput command automatica**y remoes commas and doub*e 8uotation mar(s from t"e input %"en t"ese c"aracters are used as t"e de*imiters& See Listin$ 161 and 0i$ure AB for input e3amp*es& Listing 161. Use "nput to read te.t written with 'rite. Sub Exa!pleInput -i! #"ileHa!e A# Strin -i! n A# Inteer -i! t A# Strin= d A# -ouble= # A# Strin #"ileHa!e 6 Con:ert3o0R,BCur-irC 4 "+del!e&txt" n 6 "ree"ileBC 179 Open #"ileHa!e "or Output Acce## Read Write A# Ln Write Ln= >&%%= Ho*= "I a! a #trin" See1Bn= >C Input Ln= d= t= # clo#e Ln ^illB#"ileHa!eC # 6 "#trin B" 4 # 4 "C" 4 CHRFB>7C 45 "nu!ber B" 4 d 4 "C" 4 CHRFB>7C 45 "ti!e B" 4 t 4 "C E66 read a# a #trin" 4 CHRFB>7C M#Box #= 7= "Exa!ple Input" End Sub Figure 59. "nput cannot read time delimited with >OA. TIP A friend in Jermany "ad different resu*ts, because t"e number 1&33 is %ritten as 1,33& ;"i*e readin$ t"e a*ues, t"e comma is seen as a de*imiter rat"er t"an as part of t"e number& 5nfortunate*y, t"e de*imiters produced by t"e ;rite statement are not supported by t"e )nput statement& 4umbers and simp*e strin$s read %it" no prob*ems& Date and +oo*ean a*ues de*imited %it" t"e W c"aracter, "o%eer, fai*& T"ese a*ues must be read into strin$ ariab*es and t"en parsed& Do not use t"e )nput statement if you do not "ae a *ot of contro* oer t"e input te3t fi*e& Doub*e98uotation mar(s and commas in te3t strin$s are assumed to be te3t de*imiters& T"e end resu*t is t"at t"e te3t is not proper*y parsed %"en it is read& )f your input data may contain t"ese c"aracters, use t"e Line )nput command and t"en manua**y parse t"e te3t& )f you must read t"e carria$e return or *ine9feed c"aracters, t"e fi*e s"ou*d be read as a binary fi*e& A binary fi*e is a random fi*e %it" a b*oc( *en$t" of Cero& 5se t"e 'ut statement to %rite random and binary fi*es& T"e simp*est case ino*es puttin$ a simp*e ariab*e direct*y to t"e fi*e& int5:ar 6 ? : lon5:ar 6 ' Put Ln==int5:ar )7? 77 Bt*o b.te# *rittenC Put Ln==lon5:ar )7' 77 77 77 B$our b.te# *rittenC T"e first ar$ument is t"e fi*e number and t"e t"ird ar$ument is t"e ariab*e or data to %rite& T"e second ar$ument is t"e position in t"e fi*e %"ere t"e date s"ou*d be %ritten& )f you omit t"e position, as s"o%n in t"e e3amp*e, you must sti** inc*ude t"e comma& Put Ln==:ariable )Write to t(e next record or b.te po#ition Put Ln= po#ition= :ariable )Speci$. t(e next record or b.te po#ition Random fi*es assume t"at t"e position identifies a record number& +inary fi*es assume t"at t"e position identifies an abso*ute byte position& )f t"e position is not specified, t"e data is %ritten at t"e current fi*e pointer, %"ic" is adanced %it" t"e data t"at is %ritten& )f t"e data ariab*e is a Oariant, an inte$er identifyin$ t"e data type precedes t"e data& T"is inte$er is t"e same inte$er returned by t"e OarType function, to be detai*ed *ater& 180 : 6 ? )A Oariant :ariable Put Ln==: )7' 77 7? 77 B$ir#t t*o b.te# #a.# t.pe i# 'C Put Ln==? )7' 77 7? 77 B$ir#t t*o b.te# #a.# t.pe i# 'C Put Ln==CIntB?C )7' 77 7? 77 B$ir#t t*o b.te# #a.# t.pe i# 'C A strin$ stored as a Oariant inc*udes t"e OarType if it is D'utF to a fi*e t"at %as opened as any type ot"er t"an +inary& ;"en an array is 'ut to a fi*e, eac" e*ement of t"e array is %ritten& )f t"e array contains a Strin$ Oariant, it inc*udes t"e OarType een if t"e fi*e type is +inary& ;"en 'ut p*aces a strin$ as a Oariant, it actua**y %rites t"e OarType, t"e strin$ *en$t", and t"en t"e strin$& :BC 6 Arra.B"ABC-"C )ASCII in (exadeci!al i# ?> ?' ?% ?? Put Ln==:BC )7Q 77 7? 77 ?> ?' ?% ?? B7Q 77 6 t.peCB7? 77 6 lent(C ;"en data is 'ut to a fi*e, t"e current fi*e pointer is saed and t"en a** of t"e data is %ritten& )f a non9Cero b*oc( *en$t" is used, t"e fi*e pointer is positioned one b*oc( *en$t" past t"e saed fi*e position re$ard*ess of "o% muc" data %as %ritten& 0or e3amp*e, if t"e b*oc( *en$t" is 32 and t"e current fi*e position is 6!, t"e fi*e pointer is positioned to byte B6 after t"e data is %ritten& )f more t"an 32 bytes are %ritten, part of t"e ne3t record is oer%ritten& )f fe%er t"an 32 bytes are %ritten, t"en t"e preious data is *eft unc"an$ed& +ecause of t"is, some peop*e initia*iCe eery record t"at %i** be %ritten %"en t"e fi*e is created& 4umeric a*ues are usua**y initia*iCed to Cero, and strin$ a*ues are usua**y initia*iCed to spaces& 1n t"e ot"er "and, een t"ou$" ) donGt recommend it, you can use t"e 'ut statement %it" a fi*e opened in a se8uentia* mode& Li(e%ise, you can use t"e ;rite, Line )nput, and )nput statements for fi*es opened in +inary or Random mode& T"e actua* bytes %ritten for %ritin$ met"ods used for fi*es of t"e D%ron$F fi*e structure are not documented, and ) "ad difficu*ty understandin$ t"e output& ) fina**y read t"e source code to determine %"at is %ritten in eac" case, but undocumented be"aior determined in t"is %ay s"ou*d not be assumed to be stab*e, re*iab*e be"aior for 11o +asic& )f you %ant to use t"ese met"ods for ot"er fi*e structures t"an t"ose documented, ) recommend t"at you test t"e output for your specific data& ;"en a piece of data is %ritten to a fi*e, t"e specific conte3t is used to determine %"at to %rite& See Tab*e 6@& Table 68. *ummary of what the 9ut statement writes. Type Bytes Comment +oo*ean 1 11o +asic stores a +oo*ean in an inte$er& T"e True a*ue "as a** of t"e bits set, %"ic" incorrect*y cast do%n to one byte, causin$ a run9time error& 0a*se %rites %it" no prob*em& +yte 3 A*t"ou$" t"e byte ariab*e uses on*y one byte %"en %ritin$ t"e data, byte ariab*es are supported on*y %"en stored in a Oariant, so t"e data is preceded by t%o bytes of type information& #urrency @ )nterna**y stored as a Doub*e& Date @ )nterna**y stored as a Doub*e& Doub*e @ )nte$er 2 Lon$ ! 1b/ect 2rror Run9time error: 1n*y t"e basic types are supported& Sin$*e ! Strin$ Len,s. 2ac" c"aracter is one byte& #"aracters %it" an AS#)) a*ue *ar$er t"an 2AA are %ritten %it" incomp*ete data& )n +inary mode, t"e 'ut statement %i** not %rite c"aracters %it" an AS#)) a*ue of Cero& T"is is %ritten fine in Random mode and t"e strin$ is preceded by t"e strin$ *en$t"& Oariant Oaries T%o bytes of type information are %ritten, fo**o%ed by t"e data& A strin$ a*so inc*udes t"e *en$t" of t"e strin$ in t%o bytes& 181 Type Bytes Comment 2mpty ! An empty Oariant ariab*e %rites t%o bytes of type information indicatin$ an inte$er a*ue, and t"en it %rites t%o bytes %it" Ceros& 4u** 2rror 1n*y an ob/ect can contain t"e a*ue 4u**, and t"e 'ut statement does not %or( %it" ob/ects& TIP 11o +asic on*y supports usin$ Jet and 'ut %it" t"e standard data types& TIP 4umbers %ritten to binary fi*es are %ritten in reerse byte order& TIP T"e 'ut statement cannot %rite a +oo*ean %it" a True a*ue, and it doesnGt proper*y %rite strin$s %it" 5nicode a*ues $reater t"an 2AA7 %ritin$ t"en tryin$ to read t"e a*ue causes 11o to cras"& TIP T"e Jet statement fai*s for binary fi*es if t"e position is not proided& 5se Jet to read +inary data and Random fi*es& T"e synta3 for t"e Jet statement is simi*ar to t"e 'ut statement& Jet Ln==:ariable )Read $ro! next record or b.te po#ition Jet Ln= po#ition= :ariable )Speci$. t(e next record or b.te po#ition )f t"e ar$ument to t"e Jet statement is a Oariant, t"e type information is a*%ays read, re$ard*ess of t"e conte3t& ;"en a strin$ is read, it is assumed to be preceded by an inte$er t"at contains t"e *en$t" of t"e strin$& T"is re8uired strin$ *en$t" is not %ritten automatica**y to binary fi*es but it is to random fi*es& Listin$ 162 s"o%s an e3amp*e of readin$ and %ritin$ a binary fi*e& A*so see 0i$ure 60& Listing 162. /reate and then read a binary file. Sub Exa!pleReadWriteBinar."ile -i! #"ileHa!e A# Strin )"ile na!e $ro! *(ic( to read and *rite -i! n A# Inteer )"ile nu!ber to u#e -i! i A# Inteer )Scrap Inteer :ariable -i! l A# ,on )Scrap ,on :ariable -i! # A# Strin )Scrap Strin :ariable -i! #' A# Strin )Anot(er #crap Strin :ariable -i! : )Scrap Oariant :ariable #"ileHa!e 6 Con:ert3o0R,BCur-irC 4 "+del!e&txt" I$ "ileExi#t# B#"ileHa!eC 3(en ^illB#"ileHa!eC End I$ n 6 "ree"ileBC Open #"ileHa!e "or Binar. A# Ln i 6 >7 : Put Ln==i )7A 77 i 6 '<< : Put Ln==i )"" 77 i 6 9' : Put Ln==i )"E "" l 6 >7 : Put Ln==l )7A 77 77 77 l 6 '<< : Put Ln==l )"" 77 77 77 l 6 9' : Put Ln==l )"E "" "" ""
182 REM Put #trin data= precede it *it( a lent( i 6 Q : Put Ln==i )7Q 77 Babout to put ei(t c(aracter# to t(e $ileC # 6 "ABC-" Put Ln==# )?> ?' ?% ?? BASCII $or ABC-C Put Ln==# )?> ?' ?% ?? BASCII $or ABC-C
REM Put data contained in a Oariant Put Ln==CIntB>7C )7' 77 7A 77 i 6 9' : Put Ln==CIntBiC )7' 77 "E "" B"unction# return a OariantC Put Ln==C,nB'<<C )7% 77 "" 77 77 77 B"unction# return a OariantC : 6 '<< : Put Ln==: )7' 77 "" 77 B3(i# IS a OariantC : 6 "ABC-" : Put Ln==: )?> ?' ?% ?? BHot in an arra.C : 6 Arra.B'<<= "ABC-E"C )3(e #trin contain# t.pe in$or!ation and lent( Put Ln==:BC )7' 77 "" 77 7Q 77 7< 77 ?> ?' ?% ?? ?< clo#e Ln
REM no*= read t(e $ile& # 6 "" n 6 "ree"ileBC Open #"ileHa!e "or Binar. Acce## Read A# Ln Jet Ln= >= i : # 6 # 4 "Read Inteer " 4 i 4 CHRFB>7C Jet Ln= %= i : # 6 # 4 "Read Inteer " 4 i 4 CHRFB>7C Jet Ln= <= i : # 6 # 4 "Read Inteer " 4 i 4 CHRFB>7C Jet Ln= 2= l : # 6 # 4 "Read ,on " 4 l 4 CHRFB>7C Jet Ln= >>= l : # 6 # 4 "Read ,on " 4 l 4 CHRFB>7C Jet Ln= ><= l : # 6 # 4 "Read ,on " 4 l 4 CHRFB>7C Jet Ln= >@= #' : # 6 # 4 "Read Strin " 4 #' 4 CHRFB>7C clo#e Ln M#Box #= 7= "Read Write Binar. "ile" End Sub Figure 60. Use <et and 9ut to read and write binary files. Random fi*es are usua**y used to store a user9defined data type, but t"is is not supported in 11o +asic7 use D1pen 0i*e4ame 0or RandomF to open a fi*e for random access& T"e code in Listin$ 163 %rites numerous types and siCes of data to t"e fi*e %it" a b*oc( *en$t" of @& )f t"e 'ut statement "ad no bu$s, t"en after %ritin$ t"e first b*oc(, t"e fi*e pointer %ou*d be positioned to t"e second b*oc( for %ritin$& )t is instead positioned to t"e end of t"e fi*e& To aoid t"is bu$, e3p*icit*y inc*ude t"e position to %rite in t"e statement& )f t"e position points to a position beyond t"e end of t"e fi*e, t"e fi*e pointer is moed to t"e end of t"e fi*e& T"is is t"e primary reason %"y t"e code in Listin$ 163 initia*iCes t"e fi*e to a** Ceros before startin$7 t"e fi*e is initia*iCed %it" *ocations for t"e subse8uent operations& 4otice t"at t"e strin$ inc*udes t"e strin$ *en$t" 183 before t"e te3t %"en it is 'ut to t"e fi*e& T"e output is essentia**y t"e same as Listin$ 162 s"o%n in 0i$ure 60& Listing 163. 'rite and then read a random access file. Sub Exa!pleReadWriteRando!"ile -i! #"ileHa!e A# Strin )"ile na!e $ro! *(ic( to read and *rite -i! n A# Inteer )"ile nu!ber to u#e -i! i A# Inteer )Scrap Inteer :ariable -i! l A# ,on )Scrap ,on :ariable -i! # A# Strin )Scrap Strin :ariable -i! #' A# Strin )Anot(er #crap Strin :ariable #"ileHa!e 6 Con:ert3o0R,BCur-irC 4 "+del!e&txt"
REM Ho* t(e $ile i# initiali8ed #o it can be u#edK REM Mu#t u#e Acce## Read #o t(at t(e $ile i# not created ne* REM I cannot *rite t(i# a# a binar. $ile becau#e t(en ASCII REM 8ero# are not *ritten& n 6 "ree"ileBC Open #"ileHa!e "or Rando! A# Ln ,en 6 Q REM "ir#t= create a $ile *it( all 8ero# *it( enou( roo! REM $or '7 Q9b.te record#& # 6 StrinBQ * '79'= 7C )Strin (a# ><Q c(aracter# *it( ASCII :alue 7 Put Ln=>=# )Written a# Rando! #o ,enB#C i# *ritten $ir#t i 6 7 : Put Ln=>=i )Write o:er t(e lent( *it( 8ero#&
REM Ho* *rite t(e data i 6 >7 : Put Ln=>=i )7A 77 i 6 '<< : Put Ln='=i )"" 77 i 6 9' : Put Ln=%=i )"E "" l 6 >7 : Put Ln=?=l )7A 77 77 77 l 6 '<< : Put Ln=<=l )"" 77 77 77 l 6 9' : Put Ln=A=l )"E "" "" ""
REM Put #trin data= precede it *it( a lent( Binteer :alueC auto!aticall. # 6 "ABC-" : Put Ln=2=# )7? 77 ?> ?' ?% ?? B,ent(= t(en ASCII $or ABC-C clo#e Ln
REM Ho* read t(e $ile& # 6 "" n 6 "ree"ileBC Open #"ileHa!e "or Rando! Acce## Read A# Ln ,en6Q Jet Ln= >= i : # 6 # 4 "Read Inteer " 4 i 4 CHRFB>7C Jet Ln= '= i : # 6 # 4 "Read Inteer " 4 i 4 CHRFB>7C Jet Ln= %= i : # 6 # 4 "Read Inteer " 4 i 4 CHRFB>7C Jet Ln= ?= l : # 6 # 4 "Read ,on " 4 l 4 CHRFB>7C Jet Ln= <= l : # 6 # 4 "Read ,on " 4 l 4 CHRFB>7C Jet Ln= A= l : # 6 # 4 "Read ,on " 4 l 4 CHRFB>7C Jet Ln= 2= #' : # 6 # 4 "Read Strin " 4 #' 4 CHRFB>7C clo#e Ln M#Box #= 7= "Read Write Rando! "ile" End Sub 184 &.(. Cile and director' related services Some of t"e 11o met"ods for fi*e manipu*ation are bu$$y and unre*iab*e& 6ou may %ant to consider some of t"e bui*t9in 11o serices7 serices are discussed *ater>>& 0.2.1. <ath ettings Most of t"e macros in t"is c"apter use t"e #urDir function to c"oose a p*ace to store fi*es& T"e 'at"Settin$s serice proides read-%rite access ,and t"e abi*ity to re$ister a *istener. for t"e pat"s properties used by 11o& A*t"ou$" t"e documentation is not c*ear on t"is, my e3amp*es indicate t"at t"e pat" is returned as a 5RL& 1n t"e ot"er "and, t"e 'at"Settin$s serice uses t"e 'at"Substitution serice, %"ic" specifica**y states t"at it returns 5RLS& 11M2;or(Dir in Listin$ 16! demonstrates obtainin$ t"e ;or( directory& Listing 164. #etermine the work directory to use. "unction OOMEWor1-irBC A# Strin -i! #F -i! oPat(Settin# oPat(Settin# 6 Create0noSer:iceB"co!&#un&#tar&util&Pat(Settin#"C #F 6 oPat(Settin#&Wor1 I$ # 6 "" 3(en # 6 JetPat(SeparatorBC El#eI$ Ri(tB#=>C ED "+" AH- Ri(tB#=>C ED "\\" 3(en I$ ,e$tB#= <C 6 "$ile:" 3(en # 6 # 4 "+" El#e # 6 # 4 JetPat(SeparatorBC End I$ End I$ OOMEWor1-irBC 6 # 4 "OOMEWor1" 4 JetPat(SeparatorBC End "unction A macro t"at creates temporary fi*es or directories for e3amp*e purposes %i** use Listin$ 16A to create and remoe t"e %or(in$ directory& Listing 165. /reate and remove the OOM$ work directory. "unction CreateOOMEWor1-irBC A# Boolean CreateOOMEWor1-irBC 6 "al#e -i! #F # 6 OOMEWor1-irBC I$ HO3 "ileExi#t#B#C 3(en M1-ir # End I$ CreateOOMEWor1-irBC 6 "ileExi#t#B#C End "unction "unction R!OOMEWor1-irBC A# Boolean R!OOMEWor1-irBC 6 "al#e -i! #F # 6 OOMEWor1-irBC I$ "ileExi#t#B#C 3(en R!-ir # End I$ R!OOMEWor1-irBC 6 HO3 "ileExi#t#B#C 185 End "unction T"e documentation *ists properties t"at are supported& +y inspectin$ t"e ob/ect, ) found more properties t"an t"ose t"at are documented& Table 69. #ocumented 9ath*ettings properties. Property %m2er /6ic6 Directory Addin Sin$*e #ontains spreads"eet add9ins t"at use t"e o*d add9in A')& Auto#orrect Mu*tip*e #ontains t"e settin$s for t"e Auto#orrect dia*o$& AutoTe3t Mu*tip*e #ontains t"e AutoTe3t modu*es& +ac(up Sin$*e ;"ere automatic document bac(ups are stored& +asic Mu*tip*e #ontains +asic fi*es used by t"e Auto'i*ots& +itmap Sin$*e #ontains t"e e3terna* icons for t"e too*bars& #onfi$ Sin$*e #ontains confi$uration fi*es& T"is property is not isib*e in t"e pat" options dia*o$ and cannot be modified& Dictionary Sin$*e #ontains t"e 1pen1ffice&or$ dictionaries& 0aorite Sin$*e #ontains t"e saed fo*der boo(mar(s& 0i*ter Sin$*e ;"ere t"e fi*ters are stored& Ja**ery Mu*tip*e #ontains t"e Ja**ery database and mu*timedia fi*es& Jrap"ic Sin$*e Disp*ayed %"en t"e dia*o$ for openin$ a $rap"ic or sain$ a ne% $rap"ic is used& Ee*p Sin$*e #ontains t"e 11o "e*p fi*es& Lin$uistic Sin$*e #ontains t"e 11o spe**c"ec( fi*es& Modu*e Sin$*e #ontains t"e 11o modu*es& 'a*ette Sin$*e #ontains t"e pa*ette fi*es t"at contain user9defined co*ors and patterns ,\&S1+ and \&S10.& '*u$in Mu*tip*e #ontains t"e '*u$ins& Stora$e Sin$*e ;"ere information about mai*, ne%s, and 0T' serers is stored& Temp Sin$*e #ontains t"e 11o temp9fi*es& Temp*ate Mu*tip*e #ontains t"e 11o document temp*ates& 5)#onfi$ Mu*tip*e J*oba* directories for user interface confi$uration fi*es& T"e user interface confi$uration is mer$ed %it" t"e user settin$s stored in t"e directory specified by 5ser#onfi$& 5ser#onfi$ Sin$*e #ontains t"e user settin$s, inc*udin$ t"e user interface confi$uration fi*es for menus, too*bars, acce*erators and status bars& 5serDictionary Sin$*e #ontains t"e custom dictionaries& ;or( Sin$*e T"e %or( fo*der& T"is pat" can be modified accordin$ to t"e userVs needs and can be seen in t"e 1pen or Sae dia*o$& To see t"e pat" settin$s on your computer, run t"e macro in Listin$ 166& 1n my computer, ) find numerous e3tra pat"s suc" as ;or(=interna*, ;or(=user, ;or(=%ritab*e& Disp*ay'at"Settin$s demonstrates numerous adanced tec"ni8ues t"at are not e3p*ained in t"is c"apter& #reatin$ and usin$ an 11o serice& #reatin$ a ne% document& 186 )nsertin$ te3t into a document& Settin$ para$rap" sty*e& )nsertin$ para$rap" brea(s into a te3t ob/ect& T"e fo**o%in$ macro %as ori$ina**y %ritten by Danny +re%er, %"o did muc" to adance t"e (no%*ed$e of 11o macros before "e %ent on to ot"er t"in$s& ) modified t"e macro so t"at it dec*ares a** ariab*es and "and*es property types returned as array a*ues& Listing 166. #isplay the 9ath*ettings in a new te.t document. Sub -i#pla.Pat(Settin# -i! oPat(Settin# ) Pat(Settin# #er:ice& -i! oPropert.SetIn$o ) Acce## t(e #er:ice propertie#& -i! aPropertie# ) Contain# all o$ t(e #er:ice propertie#& -i! o-oc ) Re$erence a ne*l. created docu!ent& -i! o3ext ) -ocu!ent)# text obNect& -i! oCur#or ) Cur#or in t(e text obNect& -i! oPropert. ) A propert. o$ t(e #er:ice& -i! cPropert.Ha!eF ) Propert. na!e& -i! cPropert.Oalue ) Propert. :alue !a. be an arra. or !ultiple #trin#& -i! aPat(# ) 3(e pat(# a# an arra.& -i! cPat(F ) A #inle pat( $ro! t(e arra.& -i! N A# Inteer ) Index :ariable& -i! i A# Inteer ) Index :ariable&
oPat(Settin# 6 Create0noSer:iceB "co!&#un&#tar&util&Pat(Settin#" C ) Exa!ple o$ (o* to et a #inle propert. .ou are a$ter& )oPat(Settin#&Wor1 ) Jet in$or!ation about t(e propertie# o$ t(e pat( #ettin#& oPropert.SetIn$o 6 oPat(Settin#&etPropert.SetIn$oBC
) Jet an arra. o$ t(e propertie#& aPropertie# 6 oPropert.SetIn$o&etPropertie#BC
) Create an output docu!ent& o-oc 6 Star-e#1top&loadCo!ponent"ro!0R,B "pri:ate:$actor.+#*riter"= 5 "5blan1"= 7= Arra.BC C o3ext 6 o-oc&et3extBC oCur#or 6 o3ext&create3extCur#orBC
o3ext&in#ertStrinB oCur#or= "Pat( Settin#"= "al#e C oCur#or&ParaSt.leHa!e 6 "Headin >" o3ext&in#ertControlC(aracterB oCur#or= 5 co!&#un&#tar&text&ControlC(aracter&PARAJRAPH5BREA^= "al#e C ) Iterate o:er t(e arra. o$ propertie#= ) and *rite in$or!ation about eac( propert. to t(e output& "or i 6 ,BoundB aPropertie# C 3o 0BoundB aPropertie# C oPropert. 6 aPropertie#B i C cPropert.Ha!e 6 oPropert.&Ha!e 187 cPropert.Oalue 6 oPat(Settin#&etPropert.OalueB cPropert.Ha!e C
o3ext&in#ertStrinB oCur#or= cPropert.Ha!e= "al#e C oCur#or&ParaSt.leHa!e 6 "Headin %" o3ext&in#ertControlC(aracterB oCur#or= 5 co!&#un&#tar&text&ControlC(aracter&PARAJRAPH5BREA^= "al#e C I$ I#Arra.BcPropert.OalueC 3(en ) Multiple 0R,# are #o!ti!e# returned a# an arra.& aPat(# 6 cPropert.Oalue El#eI$ ,enB cPropert.Oalue C D 7 3(en ) Multiple 0R,# are #o!ti!e# #eparated b. a #e!icolon& ) Split t(e! up into an arra. o$ #trin#& aPat(# 6 SplitB cPropert.Oalue= "\" C El#e aPat(# 6 Arra.BC End I$ "or N 6 ,BoundB aPat(# C 3o 0BoundB aPat(# C cPat( 6 aPat(#B N C o3ext&in#ertStrinB oCur#or= cPat(= "al#e C o3ext&in#ertControlC(aracterB oCur#or= 5 co!&#un&#tar&text&ControlC(aracter&PARAJRAPH5BREA^= "al#e C Hext
o3ext&in#ertControlC(aracterB oCur#or= 5 co!&#un&#tar&text&ControlC(aracter&PARAJRAPH5BREA^= "al#e C Hext i End Sub Settin$ a pat" a*ue is triia**y done usin$ eit"er direct assi$nment, or by usin$ t"e property set information ob/ect& 11o re8uires t"ese a*ues to be correct, so, if you %rite bad a*ues, it %i** ne$atie*y affect 11o& oPat(Settin#&Wor1 6 Con:ert3o0rlB"C:\M.Wor1-ir"C oPat(Settin#&#etPropert.OalueB"Wor1"= "C:\M.Wor1-ir"C T"e properties supported by t"e 'at"Settin$ serice are stored, at *east on my computer, in t"e fi*e: openoffice&or$-basis3&2-s"are-re$istry-sc"ema-or$-openoffice-1ffice-#ommon&3cs& T"e documentation sti** references t"e o*d fi*ename #ommon&3m*, %"ic" caused me some *ee* of consternation& 0.2.2. <ath ubstitution My fi*e #ommon&3cs contains entries suc" as Y,userpat".-store and Y,%or(., %"ic" are ery different from %"at is returned by t"e 'at"Settin$s serice& T"is is because t"e pat" settin$ serice c"an$es s"ortcuts suc" as Y,userpat". to t"e rea* a*ue before returnin$ a strin$& Ana*o$ous*y, it substitutes t"e s"ortcuts bac( into t"e strin$ before storin$ t"e a*ue& 6ou can ca** t"e 'at"Substitution serice direct*y to ma(e your o%n substitutions& Table 70. 9ath substitution variables. %ame Description Y,inst. )nsta**ation pat" of t"e 11o +asis *ayer& Y,pro$. 'ro$ram pat" of t"e 11o +asis *ayer& Y,brandbaseur*. )nsta**ation pat" of t"e t"e 11o +rand *ayer& Y,user. T"e user insta**ation directory& 188 %ame Description Y,%or(. T"e %or( directory of t"e user7ZMyDocumentsZ for ;indo%s, t"e userVs "ome9directory for Linu3& Y,"ome. T"e userVs "ome directory7 Documents and Settin$s for ;indo%s, t"e userVs "ome9directory for Linu3& Y,temp. T"e current temporary directory& Y,pat". T"e a*ue of 'ATE enironment ariab*e& Y,*an$. T"e country code used by 11o7 01?en$*is"& Y,*an$id. T"e *an$ua$e code used by 11o7 1033?en$*is" us& Y,*an$. T"e *an$ua$e used by 11o as a strin$& Li(e Zen95SZ for a 5S 2n$*is" 11o& 5se $etSubstituteOariab*eOa*ue to conert one name at a time& )f t"e name is not (no%n, a run9time error occurs& Listing 167. *ubstitute one variable with 9ath*ubstitution. Sub 0#ePat(Sub#titutionBC -i! oPat(Sub ) Pat(Sub#titution #er:ice& -i! na!e# ) ,i#t o$ na!e# to #ub#titute& -i! #ubHa!eF ) Sinle na!e to c(ec1& -i! i A# Inteer ) Index :ariable& -i! #F ) Accu!ulate t(e :alue to print&
oPat(Sub 6 Create0noSer:iceB "co!&#un&#tar&util&Pat(Sub#titution" C
) 0#e etSub#tituteOariableOalue *it( a #inle :ariable& ) Runti!e error i$ t(e na!e i# not 1no*&
)Print oPat(Sub&etSub#tituteOariableOalueB"FBin#tC"C "or i 6 ,BoundBna!e#C 3o 0BoundBna!e#C #ubHa!e 6 "FB" 4 na!e#BiC 4 "C" # 6 # 4 na!e#BiC 4 " 6 " # 6 # 4 oPat(Sub&etSub#tituteOariableOalueB#ubHa!eC 4 CHRFB>7C Hext M#Box #= 7= "Supported Ha!e#" End Sub 5se substituteOariab*es to substitute mu*tip*e a*ues at t"e same time& 5se reSubstituteOariab*es to p*ace t"e ariab*e names bac( into a re$u*ar strin$& Listing 168. Re*ubstitute variables. Sub 0#ePat(ReSub#titutionBC -i! oPat(Sub ) Pat(Sub#titution #er:ice& -i! #F ) Accu!ulate t(e :alue to print& -i! #3e!pF
189 oPat(Sub 6 Create0noSer:iceB "co!&#un&#tar&util&Pat(Sub#titution" C ) 3(ere are t*o :ariable# to #ub#titute& ) "al#e !ean# do not enerate an error ) i$ an un1no*n :ariable i# u#ed& # 6 "FBte!pC+OOME+ or FB*or1C" #3e!p 6 oPat(Sub&#ub#tituteOariable#B#= "al#eC # 6 # 4 " 6 " 4 #3e!p 4 CHRFB>7C
) 3(i# direction encode# t(e entire t(in a# t(ou( it *ere a #inle ) pat(& 3(i# !ean# t(at #pace# are encoded in 0R, notation& # 6 # 4 #3e!p 4 " 6 " 4 oPat(Sub&reSub#tituteOariable#B#3e!pC 4 CHRFB>7C M#Box # End Sub Figure 61. 9ath*ubstitution service. 0.2.#. imple +ile )ccess ;"en 11o accesses fi*es, it does not use t"e same routines supported by +asic& 1ne of t"e serices used is Simp*e0i*eAccess, %"ic" supports Table 71. Methods supported by *imple+ile-ccess. )et6od Description copy,from5RL, to5RL. #opy a fi*e& moe,from5RL, to5RL. Moe a fi*e& (i**,ur*. De*ete a fi*e or directory, een if t"e fo*der is not empty& is0o*der,ur*. Return true if t"e 5RL represents a fo*der& isRead1n*y,ur*. Return true if t"e fi*e is read9on*y& setRead1n*y,ur*, boo*. Set fi*e as read9on*y if t"e boo*ean ar$ument is true, ot"er%ise, c*ear t"e read9on*y f*a$& create0o*der,ur*. #reates a ne% 0o*der& $etSiCe,ur*. Returns t"e siCe of a fi*e as a *on$ inte$er& $et#ontentType,ur*. Return t"e content type of a fi*e as a strin$& 1n my computer, an odt fi*e "as type app*ication-nd&sun&staroffice&fsys9fi*e& $etDateTimeModified,ur*. Return t"e *ast modified date for t"e fi*e as a com&sun&star&uti*&DateTime structure, %"ic" supports t"e properties: Eundredt"Seconds, Seconds, Minutes, Eours, Day, Mont", and 6ear& $et0o*der#ontents,ur*, boo*. Returns t"e contents of a fo*der as an array of strin$s& 2ac" strin$ is t"e fu** pat" as a 5RL& )f t"e boo* is True, t"en fi*es and directories are *isted& )f t"e boo* is 0a*se, t"en on*y fi*es are returned& 190 )et6od Description e3ists,ur*. Return true if a fi*e or directory e3ists& open0i*eRead,ur*. 1pen fi*e to read, return an input stream& open0i*e;rite,ur*. 1pen fi*e to %rite, return an output stream& open0i*eRead;rite,ur*. 1pen fi*e to read and %rite, return a stream& set)nteractionEand*er,"and*er. Set an interaction "and*er to be used for furt"er operations& T"is is a more adanced topic and ) %i** not discuss t"is "ere& %rite0i*e,to5r*, inputStream. 1er%rite t"e fi*e content %it" t"e $ien data& 0.2.$. treams A stream supports readin$ and %ritin$ data from some input source to some output source t"at may $o beyond a fi*e system& As an e3amp*e, ) use streams to transfer entire fi*es bet%een t"e re$u*ar fi*e system and a fie*d in a database& )n ot"er %ords, streams are po%erfu* and %ort" (no%in$ and understandin$& T"is section does not coer a** of t"e stream capabi*ities and does not een touc" on Mar(ab*e streams and 1b/ect streams& Streams support a** sorts of fancy t"in$s suc" as *isteners t"at are automatica**y ca**ed %"en specific eents occur& A motiated reader %i** read t"e streams document: "ttp:--ud(&openoffice&or$-common-man-concept-streams&"tm* "ttp:--api&openoffice&or$-docs-common-ref-com-sun-star-io-modu*e9i3&"tm* TIP T"e readLine,. met"od does not remoe t"e end of *ine c"aracter if t"e end of fi*e is reac"ed& Table 72. *tream methods. )et6od Stream Description aai*ab*e,. )nputStream Returns t"e number of aai*ab*e bytes as a *on$& c*ose)nput,. )nputStream #*ose t"e input stream& c*ose1utput,. 1utputStream #*ose t"e stream& f*us",. 1utputStream 0*us" buffers& $etLen$t",. ISee(ab*e Jet *en$t" of t"e stream& $et'osition,. ISee(ab*e Return t"e stream offset as a 6!9bit inte$er& is210,. Te3t)nputStream Returns true if t"e end of fi*e "as been reac"ed& read+oo*ean,. Data)nputStream Read an @ bit a*ue and return a byte& 0 means 0ALS27 a** ot"er a*ues mean TR52& read+yte,. Data)nputStream Read and return an @ bit a*ue and return a byte& read+ytes,byteArray, *on$. )nputStream Read t"e specified number of bytes and return t"e number of bytes read& )f t"e number of bytes re8uested %as not read, t"en t"e end of fi*e "as been reac"ed& read#"ar,. Data)nputStream Read and return a 169bit 5nicode c"aracter& readDoub*e,. Data)nputStream Read and return a 6!9bit )222 doub*e& read0*oat,. Data)nputStream Read and return a 329bit )222 f*oat& readEyper,. Data)nputStream Read and return a 6!9bit bi$ endian inte$er& 191 )et6od Stream Description readLine,. Te3t)nputStream Read te3t unti* a *ine brea( ,#R, L0, or #R-L0. or 210 is found and returns it as strin$ ,%it"out #R, L0.& readLon$,. Data)nputStream Read and return a 329bit bi$ endian inte$er& readS"ort,. Data)nputStream Read and return a 169bit bi$ endian inte$er& readSome+ytes,byteArray, *on$. )nputStream Read up to t"e specified number of bytes and return t"e number of bytes read& )f t"e number of bytes read is Cero, t"en t"e end of fi*e "as been reac"ed& readStrin$,c"arArray, boo*ean. Te3t)nputStream Read te3t unti* one of t"e $ien de*imiter c"aracters or 210 is found and returns it as strin$& T"e boo*ean ar$ument determines if t"e de*imiter is returned ,fa*se. or remoed ,true.& read5T0,. Data)nputStream Read and return a strin$ of 5T0 encoded c"aracters& see( , )4T6! . ISee(ab*e #"an$e t"e stream pointer to t"e specified *ocation& set2ncodin$,strin$. Te3t)nputStream Set t"e c"aracter encodin$ ,see "ttp:--%%%&iana&or$-assi$nments-c"aracter9sets.& s(ip+ytes,*on$. )nputStream S(ips t"e specified number of bytes& truncate,. ITruncate Set t"e siCe of t"e fi*e to Cero& %rite+oo*ean,boo*ean. Data1utputStream ;rite a boo*ean as an @ bit a*ue& 0 means 0ALS27 a** ot"er a*ues mean TR52& %rite+yte,byte. Data1utputStream ;rite an @ bit a*ue and return a byte& %rite+ytes,byteArray,.. 1utputStream ;rite a** bytes to t"e stream& %rite#"ar,c"ar. Data1utputStream ;rite a 169bit 5nicode c"aracter& %riteDoub*e,doub*e. Data1utputStream ;rite a 6!9bit )222 doub*e& %rite0*oat,f*oat. Data1utputStream ;rite a 329bit )222 f*oat& %riteEyper,)4T6!. Data1utputStream ;rite a 6!9bit bi$ endian inte$er& %riteLon$,*on$. Data1utputStream ;rite a 329bit bi$ endian inte$er& %riteS"ort,s"ort. Data1utputStream ;rite a 169bit bi$ endian inte$er& T"ere are many different types of stream serices and interfaces ,see Tab*e M2.& A simp*e stream returned by Simp*e0i*eAccess on*y supports readin$ and %ritin$ ra% bytes and you must conert t"e data to an array of bytes& )t is more common to manua**y create an appropriate stream ,suc" as Data1utputStream or Te3t)nputStream. and use t"at to %rap t"e simp*e stream returned by Simp*e0i*eAccess& Listing 169. Using *imple+ile-ccess to read and write te.t files. Sub Exa!pleSi!ple"ileAcce## -i! oS"A ) Si!ple"ileAcce## #er:ice& -i! #"ileHa!eF ) Ha!e o$ $ile to open& -i! oStrea! ) Strea! returned $ro! Si!ple"ileAcce##& -i! o3extStrea! ) 3extStrea! #er:ice& -i! #Strin# ) Strin# to te#t *rite + read& -i! #InputF ) 3(e #trin t(at i# read& -i! #F ) Accu!ulate re#ult to print& -i! iG ) Index :ariable&
) I$ t(e EO" i# reac(ed t(en t(e ne* line deli!iter# are ) not re!o:ed& I con#ider t(i# a bu& I$ o3extStrea!&i#EO"BC 3(en I$ Ri(tB#Input= >C 6 CHRFB>7C 3(en #Input 6 ,e$tB#Input= ,enB#InputC 9 >C End I$ End I$
) Oeri$. t(at t(e read #trin i# t(e #a!e a# t(e *ritten #trin& I$ #Input ED #Strin#BiC 3(en # 6 # 4 " : BA- " El#e # 6 # 4 " : O^ " End I$ # 6 # 4 "B" 4 #Strin#BiC 4 "C" 193 # 6 # 4 "B" 4 #Input 4 "C" 4 CHRFB>7C Hext o3extStrea!&clo#eInputBC M#Box # End Sub Figure 62. e.t files with *imple+ile-ccess. 0.2.,. <ipes A pipe is an output stream and an input stream& Data %ritten to t"e outputstream is buffered unti* it is read from t"e input stream& T"e 'ipe serice a**o%s an outputstream to be conerted into an input stream at t"e cost of an additiona* buffer& )t is simp*e to create and c*ose a pipe& A*t"ou$" #reate'ipe in Listin$ 1M0 creates data streams, a ery simp*e c"an$e %ou*d use a te3t stream instead& Listing 170. /reate and close a pipe. "unction CreatePipeBC A# ObNect -i! oPipe ) Pipe Ser:ice& -i! o-ataInp ) -ataInputStrea! Ser:ice& -i! o-ataOut ) -ataOutputStrea! Ser:ice& oPipe 6 create0HOSer:ice B"co!&#un&#tar&io&Pipe"C o-ataInp 6 create0HOSer:ice B"co!&#un&#tar&io&-ataInputStrea!"C o-ataOut 6 create0HOSer:ice B"co!&#un&#tar&io&-ataOutputStrea!"C o-ataInp&#etInputStrea!BoPipeC o-ataOut&#etOutputStrea!BoPipeC CreatePipe 6 oPipe End "unction Sub Clo#ePipeBoPipeC oPipe&Succe##or&clo#eInput oPipe&Predece##or&clo#eOutput oPipe&clo#eInput oPipe&clo#eOutput End Sub Test'ipes in Listin$ 1M1 uses a pipe to conert a byte array to a doub*e and a doub*e to a byte array& Listing 171. /onvert a byte array to a double and a double to a binary array. Sub 3e#tPipe# -i! oPipe ) Pipe #er:ice& -i! d A# -ouble -i! i A# Inteer -i! #F 194 oPipe 6 CreatePipeBC
) Ho*= read t(e pipe& d 6 oPipe&Succe##or&read-oubleBC # 6 "Read t(e arra. o$ b.te# a#: " 4 CStrBdC 4 CHRFB>7C 4 CHRFB>7C ) Ho* read t(e double t(at *a# *ritten a# a #erie# o$ b.te#& # 6 # 4 "'&A 6 " -o W(ile oPipe&Succe##or&a:ailableBC D 7 i 6 oPipe&Succe##or&readB.teBC REM In ca#e t(e b.te *a# neati:e i 6 i AH- '<< I$ i E >A 3(en # 6 # 4 "7" # 6 # 4 HexBiC 4 " " ,oop Clo#ePipeBoPipeC M#Box # End Sub &.1+. Conclusion T"e fi*e and directory functions in 11o +asic are ab*e to manipu*ate directories and fi*es& ;it" t"e e3ception of readin$ and %ritin$ binary and random fi*es, t"e directory and fi*e manipu*ation functions %or( %it" fe% surprises& 1n t"e ot"er "and, some of t"e functions are bro(en and "ae been bro(en for years7 you may need to use more adanced met"ods, suc" as Streams and Simp*e0i*eAccess for anyt"in$ ot"er t"an simp*e fi*e readin$ and %ritin$& 195 2. Miscellaneous 6outines T"is c"apter introduces t"e subroutines and functions supported by 1pen1ffice&or$ +asic t"at do not easi*y fit into anot"er *ar$er cate$ory L for e3amp*e, routines re*ated to f*o% contro*, user input, user output, error "and*in$, inspectin$ ariab*es, co*or, and disp*ay " as well as a fe% routines t"at you s"ou*d not use& ) %as tempted to ca** t"is c"apter DLeftoersF because it contains t"e routines t"at %ere *eft oer after ) $rouped t"e ot"ers into c"apters& A*t"ou$" t"e %ord D*eftoersF fre8uent*y "as a ne$atie connotation, t"is is certain*y not t"e case for t"e routines discussed in t"is c"apter& T"e ec*ectic mi3 of routines inc*udes some of t"e more interestin$ and usefu* routines t"at are aried enou$" to preent boredom from *u**in$ you off to s*eep& (.1. "ispla' and color T"e 11o +asic functions re*ated to co*or manipu*ations and determinin$ screen metrics are s"o%n in Tab*e M3& T"e screen metrics proide t"e siCe of eac" pi3e* so t"at you can %rite macros to create ob/ects at a $ien siCe and position ob/ects more precise*y& Table 73. #isplay4 and color4related functions in OOo !asic. !nction Description +*ue,co*or. Jet t"e b*ue component JetJuiType Jet t"e J5) type: Mac, ;indo%s, 5ni3 Jreen,co*or. Jet t"e $reen component _+#o*or,dos=co*or. Return RJ+ for standard co*or Red,co*or. Jet t"e red component RJ+,red, $reen, b*ue. RJ+ to co*or4umber T%ips'er'i3e*I ;idt" of eac" pi3e* in t%ips T%ips'er'i3e*6 Eei$"t of eac" pi3e* in t%ips 2.1.1. (etermine the G9I t"pe T"e JetJuiType function returns an inte$er correspondin$ to t"e $rap"ica* user interface ,J5).& )n ot"er %ords, you can find out %"at type of computer is runnin$ t"e macro &&& %e**, sort of& T"is function on*y mentions t"e J5) type, not t"e operatin$ system L for e3amp*e, /ust ;indo%s, not ;indo%s B@ or ;indo%s I'& T"e function JetJuiType is on*y inc*uded for bac(%ard compatibi*ity %it" preious ersions of 11o +asic& 1ne of my associates runs 1pen1ffice&or$ as a serer on "is computer at "ome& Ee t"en connects to "is "ome computer from %or( as a c*ient& T"e a*ue returned by JetJuiType is not defined %"i*e 11o is runnin$ in a c*ient-serer enironment& Tab*e M! s"o%s t"e return a*ues, as documented by t"e 11o "e*p and seen in t"e source code as of ersion 3&2&1& 196 Table 74. Return values from <et<uiype. 4 OOo Help Sorce Code 1 ;indo%s ;indo%s ,sometimes 1S-2, %"ic" runs ;indo%s. 2 4ot mentioned 1S-2 3 4ot mentioned 5sed to be Mac, not returned& ! 5ni3 5ni3 91 Mentioned as an undefined a*ue 5nsupported 1S T"e macro in Listin$ 1M2 demonstrates t"e JetJuiType function& Listing 172. #isplay the <U" type as a string. Sub -i#pla.J0I3.peBC -i! # A# Strin Select Ca#e JetJ0I3.peBC Ca#e > # 6 "Windo*#" Ca#e ' # 6 "OS+'" ) Set in t(e #ource code= but no loner docu!ented& Ca#e % # 6 "Mac OS" ) 0#ed to be docu!ented= ne:er #upported= I expect Mac to return ?& Ca#e ? # 6 "0HI/" Ca#e El#e # 6 "0n1no*n :alue " 4 CStrBJetJ0I3.peBCC 4 CHRFB>7C 45 "Probabl. runnin in Client+Ser:er !ode" End Select M#Box "J0I t.pe i# " 4 #= 7= "JetJ0I3.peBC" End Sub T"e a*ue 91 is returned if t"e type is not (no%n, but t"at is not specifica**y documented& T"is probab*y means t"at you are runnin$ in a c*ient - serer mode, but, ) "ae not c"ec(ed t"at& 2.1.2. (etermine pixel si=e >in t1ips? 11o +asic "as t%o functions to determine t"e siCe of eac" disp*ay pi3e* ,dot. in t%ips: T%ips'er'i3e*I and T%ips'er'i3e*6& T"e %ord Dt%ipF is s"ort for Dt%entiet" of a 'ostScript point&F T"ere are M2 'ostScript points in an inc", t"us 1!!0 t%ips in an inc"& )n 1@@6, t"e American Typefounders Association proposed a unit of measure for typesettin$ ca**ed t"e DAmerican 'rinterGs 'oint&F T"ere are appro3imate*y M2&2M0000M2 'rinterGs 'oints in an inc"& 6ears *ater %"i*e dee*opin$ t"e 'ostScript pa$e description *an$ua$e for Adobe Systems, Kim ;arnoc( and #"ar*es Jesc"(e defined t"e 'ostScript point as e3act*y M2 points to an inc"& ;"en dot9matri3 printers %ere re*eased, t"ey cou*d print at eit"er 10 or 12 c"aracters per inc"& T%ips %ere created as a unit of measure t"at %or(ed %e** for bot" dot9matri3 printers and 'ostScript points& TIP T"ere are 1!!0 t%ips in an inc"& T"is number is important because 11o uses t%ips for many measurements& 197 T%ips are t"e standard on %"ic" a** Microsoft ;indo%s $rap"ics routines are based& T%ips are used in t"e Ric" Te3t 0ormat, printer driers, screen driers, and many ot"er products and p*atforms L inc*udin$ 1pen1ffice&or$& T"e macro in Listin$ 1M3 obtains t"e number of t%ips per pi3e* in bot" t"e I and 6 direction ,"oriConta* and ertica*. and disp*ays t"e number of pi3e*s per inc"& Listing 173. #etermine how many pi.els per inch. Sub -i#pla.PixelSi8e -i! # A# Strin # 6 # 4 3*ip#PerPixel/BC 4 " 3*ip# per /9Pixel or " 45 CStrB>??7 \ 3*ip#PerPixel/BCC 4 " /9Pixel# per Inc(" 4 CHRFB>7C # 6 # 4 3*ip#PerPixelPBC 4 " 3*ip# per P9Pixel or " 45 CStrB>??7 \ 3*ip#PerPixelPBCC 4 " P9Pixel# per Inc(" M#Box #= 7= "Pixel Si8e" End Sub Figure 63. Number of pi.els per inch on my computer. 5nfortunate*y, it is not c*ear to me %"at is returned %"en t"ere are mu*tip*e monitors %it" different a*ues& T"e source code returns a*ues from t"e DDefau*t DeiceF& 2.1.#. 9se color functions #o*ors on computer monitors, di$ita* cameras, scanners L and t"ose seen by t"e "uman eye L are produced by addin$ t"e t"ree primary co*ors of *i$"t: red, $reen, and b*ue ,RJ+.& ;"en printin$ or paintin$, co*or is produced by absorbin$ some co*ors and ref*ectin$ ot"ers& #o*or printin$ uses a different set of co*ors, ca**ed primary pi$ments: cyan, ma$enta, ye**o%, and b*ac( ,#M6<.& T"ese t%o different systems are based on rea* p"ysica* mode*s& T"e RJ+ mode* is based on "o% *i$"t combines to form co*ors& T"e #M6< mode* is based on %"at "appens %"en you mi3 paint of different co*ors& 11o +asic uses t"e RJ+ mode*, a**o%in$ for 2A6 different s"ades of eac" of t"e primary co*ors& T"is number is stored as a Lon$ )nte$er& 5se t"e functions Red, Jreen, and +*ue to e3tract t"e red, $reen, and b*ue components from a co*or in 11o& 5se t"e RJ+ function to combine t"e indiidua* co*or components and obtain t"e *on$ inte$er used by 11o& T"e RJ+ function accepts t"ree ar$uments, eac" representin$ one of t"e primary co*ors& 2ac" of t"e co*or components must be a a*ue from 0 t"rou$" 2AA& T"e RJ+ function performs no a*idity c"ec(in$, so consider t"e resu*ts undefined if you brea( t"e ru*es& )n summary, 11o +asic represents RJ+ co*ors as a sin$*e inte$er7 t"e functions Red, Jreen, and +*ue e3tract t"e red, $reen and b*ue components7 and t"e function RJ+ accepts t"e red, $reen, and b*ue components and returns t"e 11o +asic representation of t"e RJ+ co*or& -i! nRed A# Inteer )Can onl. be 7 t(rou( '<< -i! nJreen A# Inteer )Can onl. be 7 t(rou( '<< -i! nBlue A# Inteer )Can onl. be 7 t(rou( '<< -i! nOOoColor A# ,on )Can onl. be 7 t(rou( >A=<Q>=%2< nOOoColor 6 RJBB>'Q= %= >7>C )Q=%Q@=?22 nRed 6 RedBnOOoColorC )>'Q nJreen 6 JreenBnOOoColorC )% 198 nBlue 6 BlueBnOOoColorC )>7> )n t"e o*d days of D1S, +AS)# supported 16 co*ors& )n Tab*e MA, %"ic" s"o%s t"e co*or name and t"e D1S t"e number used by D1S to represent t"e co*or& T"e 11o #o*or co*umn contains t"e correspondin$ number as represented by 11o& T"e Red, Jreen, and +*ue co*umns contain t"e a*ues returned by t"e correspondin$ 11o +asic functions& T"e _+#o*or function is desi$ned to accept t"e D1S #o*or as an ar$ument and return t"e correspondin$ 11o #o*or& Listing 174. #emonstrate ;!/olor values. Sub -i#pla.[BColor -i! iG -i! #F "or i 6 7 3o >< # 6 # 4 i 4 " 6 " 4 [BColorBiC 4 " 6 B" # 6 # 4 RedB[BColorBiCC 4 "= " # 6 # 4 JreenB[BColorBiCC 4 "= " # 6 # 4 BlueB[BColorBiCC 4 "C" # 6 # 4 CHRFB>7C Hext M#Box # End Sub Figure 64. Results from ;</olor. 199 Table 75. /olor representation in OpenOffice.org. DOS Color OOo Color &ed -reen Ble 0 0 0 0 0 ! 12@ 0 0 12@ 2 32M6@ 0 12@ 0 6 32@B6 0 12@ 12@ 1 @3@@60@ 12@ 0 0 A @3@@M36 12@ 0 12@ 3 @!213M6 12@ 12@ 0 @ @!21A0! 12@ 12@ 12@ M 126322A6 1B2 1B2 1B2 12 2AA 0 0 2AA 10 6A2@0 0 2AA 0 1! 6AA3A 0 2AA 2AA B 16M116@0 2AA 0 0 13 16M11B3A 2AA 0 2AA 11 16MM6B60 2AA 2AA 0 1A 16MMM21A 2AA 2AA 2AA (.2. Clow control T"e f*o%9contro* functions *isted in Tab*e M6 eit"er direct f*o% or proide functiona*ity simi*ar to f*o% contro*& 0or e3amp*e, t"e ))0 ,immediate if. function proides functiona*ity t"at %ou*d ot"er%ise re8uire an )f9T"en92*se statement& Table 76. OOo !asic functions related to flow control. !nction Description #"oose,number, ar$ument=*ist. 0*o% contro* ))0,condition, True23pression, 0a*se23pression. 0*o% contro* Stop Stop e3ecution no% ;ait,mi**iseconds. 'ause t"e macro for a s"ort time ;ait5nti*,aTime. ;ait unti* a time "as been reac"ed& Dec*are Dec*are a DLL t"at you %ant to ca** DD223ecute,nDD2#"anne*, command. 23ecute a DD2 command DD2)nitiate,Serer, Topic. 1pen a DD2 c"anne* DD2'o(e,nDD2#"anne*, item, data. Set data on t"e DD2 serer t"rou$" t"e c"anne* DD2Re8uest,nDD2#"anne*, item. 'ost a DD2 re8uest oer an open c"anne* DD2TerminateA**,. #*ose a** DD2 connections 0reeLibrary 0ree a DLL *ibrary S"e** Run a command t"rou$" t"e command s"e** 200 2.2.1. 6eturn an argument T"e ))0 function ,)mmediate )f. and t"e #"oose function bot" return an ar$ument based on t"e a*ue of t"e first ar$ument& T"e ))0 function returns one of t%o a*ues based on a conditiona* e3pression& T"is %or(s as a $reat one9*ine )f9T"en92*se statement& !ax5ae 6 II"BNo(n#5ae D bill#5ae= No(n#5ae= bill#5aeC T"e ))0 function ta(es t"ree ar$uments& T"e first ar$ument is a +oo*ean a*ue, %"ic" determines %"at ar$ument to return7 one of t"e ne3t t%o ar$uments is returned& Listin$ 1MA s"o%s "o% you can %rite t"e ))0 function yourse*f& Listing 175. he ""+ function) if you wrote it yourself. "unction !.II"Bconditional= true5ar= $al#e5arC A# Oariant I$ CBoolBconditionalC 3(en !.II" 6 true5ar El#e !.II" 6 $al#e5ar End I$ End "unction A** ar$uments to a routine are ea*uated before t"e routine is ca**ed& +ecause ))0 is a function, a** ar$uments are ea*uated %"en t"e function runs& ;it" an )f statement, t"e conditiona* code runs on*y if necessary& See Listin$ 1M6& Listing 176. "f the denominator is zero) the division does not occur. I$ deno!inator ED 7 3(en re#ult 6 nu!erator + deno!inator el#e re#ult 6 7 End I$ )n Listin$ 1M6, if t"e denominator is Cero, t"e diision is not done and Cero is returned instead& )n case your mat"ematica* s(i**s are a *itt*e rusty, it is not a*id to diide a number by Cero7 a run9time error occurs& 1n t"e ot"er "and, if your mat"ematica* s(i**s are not rusty, you (no% t"at returnin$ Cero %"en t"e denominator is Cero isnGt rea**y correct, eit"er& T"e macro in Listin$ 1MM demonstrates t"at t"e functions f1 and f2 are bot" ca**ed, een t"ou$" on*y t"e a*ue from f2 is returned& )n ot"er %ords, ))0,3 [R 0, 1-3, 0. causes a diision9by9Cero error if 3 is Cero& Listing 177. -ll ""+ arguments are called. Sub Exa!pleII" REM 3(i# de!on#trate# t(at A,, expre##ion# are e:aluated REM 3(i# print# REM "I a! in $unction $>" REM "I a! in $unction $'" REM "$'" Print II"B>D'= $>BC= $'BCC End Sub "unction $>F Print "I a! in $unction $>" $> 6 "$>" 201 End "unction "unction $'F Print "I a! in $unction $'" $' 6 "$'" End "unction T"e #"oose function is simi*ar to t"e ))0 function in t"at it returns an ar$ument based on t"e a*ue in t"e first ar$ument& Eo%eer, it differs because it can "ae more t"an t%o possib*e return a*ues, and t"e first ar$ument is an inte$er, rat"er t"an a +oo*ean, t"at indicates %"ic" of t"ose possib*y many ar$uments to return& C(oo#e Bexpre##ion= Select5>X= Select5'= &&& X=Select5nYYC T"e #"oose statement returns a nu** if t"e e3pression is *ess t"an 1 or $reater t"an t"e number of se*ection ar$uments& #"oose returns Se*ect=1 if t"e e3pression ea*uates to 1 and Se*ect=2 if t"e e3pression ea*uates to 2& T"e resu*t is simi*ar to storin$ t"e se*ections in an array %it" a *o%er bound of 1 and t"en inde3in$ into t"e array& 2ac" ar$ument is ea*uated re$ard*ess of %"ic" one is returned& See Listin$ 1M@& Listing 178. #emonstrate the /hoose statement. Sub Exa!pleC(oo#e -i! iG= : iG 6 CStrBInputBoxB"Enter an inteer >a? Bneati:e nu!ber i# an errorC"CC : 6 C(oo#eBi= "one"= "t*o"= "t(ree"= "$our"C I$ I#HullB:C 3(en Print "O i# null" El#e Print CStrB:C End I$ End Sub 2.2.2. <ause or end the macro T"e Stop command causes t"e macro to stop runnin$& T"atGs it, it is done, finis"edT 6ou must start a$ain& T"e ;ait statement, on t"e ot"er "and, on*y pauses macro e3ecution ,see Listin$ 1MB.& After t"e specified number of mi**iseconds, t"e macro starts runnin$ a$ain& A run9time error occurs if t"e number of mi**iseconds to %ait is ne$atie& Listing 179. #emonstrate the wait function. Sub Exa!pleWait On Error Joto BadInput -i! nMilli# A# ,on -i! nStart A# ,on -i! nEnd A# ,on -i! nElap#ed A# ,on nMilli# 6 C,nBInputBoxB"Ho* !an. !illi#econd# to *aitU"CC nStart 6 JetS.#te!3ic1#BC WaitBnMilli#C nEnd 6 JetS.#te!3ic1#BC nElap#ed 6 nEnd 9 nStart M#Box "Pou re;ue#ted to *ait $or " 4 nMilli# 4 " !illi#econd#" 45 CHRFB>7C 4 "Waited $or " 4 nElap#ed 4 " !illi#econd#"= 7= "Exa!ple Wait" BadInput: I$ Err ED 7 3(en 202 Print ErrorBC 4 " at line " 4 Erl End I$ On Error Joto 7 End Sub )n a** of my e3periments, t"e ;ait statement "as been accurate& T"e macro %aits and t"en starts %"en it s"ou*d& )n preious ersions of 11o, t"e ;ait statement %as inefficient and it used a *ot of #'5 time %"i*e runnin$& T"is prob*em "as been fi3ed in t"e current ersions of 11o& ;ait5nti* is ne% and proides more compatibi*ity %it" O+& T"e fo**o%in$ code %aits t%o seconds& Wait0ntil Ho* W 3i!eOalueB"77:77:7'"C 2.2.#. ("namic !ink !ibraries ;"i*e a macro runs, it may direct*y ca** numerous subroutines and functions& A macro can a*so ca** routines and app*ications t"at are not re*ated to 1pen1ffice&or$& A Dynamic Lin( Library ,DLL. is a co**ection of routines, or pro$rams, t"at can be ca**ed %"en re8uired& 2ac" DLL is pac(a$ed into a sin$*e fi*e %it" t"e e3tension DLL L t"e fi*e does not a*%ays "ae t"e suffi3 D&d**F, but it usua**y does& T"ere are t%o ery nice t"in$s about DLL fi*es: Many pro$rams can s"are a sin$*e DLL, and t"ey are not usua**y *oaded into memory unti* t"ey are needed& T"e usa$e of DLLs promotes code reuse and does not %aste memory& To te** 11o +asic about a routine in a DLL, use t"e Dec*are statement& TIP DLLs are not supported on Linu3& -eclare Sub Ha!e ,ib ",ibHa!e" Baru!ent#C -eclare "unction Ha!e ,ib ",ibHa!e" Baru!ent#C A# 3.pe Lib4ame is t"e name of t"e DLL t"at contains t"e routine named 4ame& )t is common to use a DLL t"at you did not %rite, so you often "ae no contro* oer t"e name of t"e routine t"at you ca**& 4amin$ can be a prob*em if your macro a*ready contains a routine %it" t"e same name or if you ca** anot"er routine by t"e same name in anot"er DLL& As a resu*t, t"e Dec*are statement supports t"e A*ias (ey%ord, %"ic" you can use to oercome t"is "urd*e& )n t"is case, t"e Rea*4ame is t"e name used by t"e DLL, and my4ame is t"e name used by your macro& -eclare Sub !.Ha!e ,ib ",ibHa!e" Alia# "RealHa!e" Baru!ent#C -eclare "unction !.Ha!e ,ib ",ibna!e" Alia# "RealHa!e" Baru!ent#C A# 3.pe 0or functions, t"e type dec*aration s"ou*d use t"e standard types& 6ou must, of course, (no% t"e type so t"at you can dec*are it& T"e ar$ument *ist contains t"e ar$uments t"at are passed to t"e e3terna* routine& 6ou must use t"e (ey%ord +yOa* if an ar$ument is passed by a*ue rat"er t"an by reference& Listin$ 1@0 ca**s a DLL& TIP +y defau*t 11o +asic passes ar$uments by reference& T"is means t"at if t"e ca**ed subroutine c"an$es t"e ar$ument, it is a*so c"an$ed in t"e ca**in$ pro$ram& T"e +yOa* (ey%ord causes an ar$ument to be passed by a*ue rat"er t"an by reference& Listing 180. /all a #LL. his will only work on windows 6and if the #LL is present7. -eclare Sub M.Me##aeBeep ,ib "u#er%'&dll" Alia# "Me##aeBeep" B ,on C -eclare "unction C(ar0pper ,ib "u#er%'&dll" Alia# "C(ar0pperA"5 BB.Oal lp#8 A# StrinC A# Strin Sub Exa!pleCall-,, REM Con:ert a #trin to upperca#e 203 -i! #trIn A# Strin -i! #trOut A# Strin #trIn 6 "i Ha:e 0pper and ,o*er" #trOut 6 C(ar0pperB#trInC M#Box "Con:erted:" 4 CHRFB>7C 4 #trIn 4 CHRFB>7C 45 "3o:" 4 CHRFB>7C 4 #trOut= 7= "Call a -,, "unction" REM On !. co!puter= t(i# pla.# a #.#te! #ound -i! nBeep,en A# ,on nBeep,en 6 <777 M.Me##aeBeepBnBeep,enC "ree,ibrar.B"u#er%'&dll" C End Sub A DLL is not *oaded unti* a routine in t"e DLL is ca**ed& To remoe t"e DLL from memory, use t"e 0reeLibrary statement& T"e 0reeLibrary statement accepts one ar$ument: t"e name of t"e DLL to un*oad& 2.2.$. Calling external applications 5se t"e S"e** statement to run an e3terna* app*ication& T"e S"e** command is disab*ed for users connectin$ by a irtua* porta* un*ess t"ey "appen to be t"e same user t"at started 11o in t"e first p*ace& T"is statement does not obtain any information from an app*ication7 it simp*y runs anot"er app*ication or command& S(ellBPat(na!e= Windo*#t.le= Para!= bS.ncC TIP T"e S"e** command is a potentia* security "o*e& T"e on*y re8uired ar$ument is t"e first7 t"e rest are optiona*& T"e first ar$ument is t"e fu** pat" name of t"e e3terna* app*ication& T"e app*ication pat" may be in 5RL notation, but need not be& T"e S"e** statement "as prob*ems if t"e pat" or app*ication name contains a space& 6ou can so*e t"is prob*em t"e same %ay t"at your ;eb bro%ser so*es it: Substitute DX20F for eac" space& T"e AS#)) a*ue of a space is 32, %"ic" is 20 in "e3adecima*& T"is tec"ni8ue can a*so be used to substitute ot"er c"aracters if t"ey cause you prob*ems& S(ellB"$ile:+++CS+And.+M.G'7-ocu!ent#+oo+t!p+(&bat"='C )0R, notation u#e# + S(ellB"C:\And.\M.G'7-ocu!ent#\oo\t!p\(&bat"='C )Windo*# notation u#e# \ T"e second ar$ument ,optiona*. indicates t"e %indo% sty*e of t"e started app*ication& Tab*e MM *ists a*id a*ues for t"e S"e** %indo% sty*e ar$ument& Table 77. 'indow styles for the *hell statement. Style Description 0 0ocus is on t"e "idden pro$ram %indo%& 1 0ocus is on t"e pro$ram %indo% in standard siCe& 2 0ocus is on t"e minimiCed pro$ram %indo%& 3 0ocus is on t"e ma3imiCed pro$ram %indo%& ! Standard siCe pro$ram %indo%, %it"out focus& 6 MinimiCed pro$ram %indo%, but focus remains on t"e actie %indo%& 10 0u**9screen disp*ay& 204 T"e t"ird ar$ument ,optiona*. is a strin$ t"at is passed to t"e app*ication& 2ac" space in t"e ar$ument strin$ is read by t"e ca**ed app*ication as de*imitin$ a separate ar$ument& To pass an ar$ument %it" an embedded space, p*ace an e3tra set of doub*e 8uotation mar(s around t"e ar$uments& S(ellB"+(o!e+and.+$oo&1#("= >7= """one aru!ent"" anot(er"C ) t*o aru!ent# TIP T"e strin$ ZZZone ar$umentZZ anot"erZ is correct and as intended7 t"in( about itT T"e fina* optiona* ar$ument determines if t"e S"e** command returns immediate*y %"i*e t"e app*ication is runnin$ ,t"e defau*t be"aior. or if it %aits unti* t"e app*ication is finis"ed& Settin$ t"e fina* ar$ument to True causes t"e S"e** statement to %ait& Sub Exa!pleS(ell -i! rc A# ,on rc 6 S(ellB"C:\and.\3SEProWin\%'&exe"= '= "c:\Macro&txt"C Print "I Nu#t returned and t(e returned code i# " 4 rc ) rc 6 7 Re! 3(e#e t*o (a:e #pace# in t(eir na!e# S(ellB"$ile:+++CS+And.+M.G'7-ocu!ent#+oo+t!p+(&bat"='C S(ellB"C:\And.\M.G'7-ocu!ent#\oo\t!p\(&bat"='C End Sub T"e S"e** function returns a *on$ %it" t"e a*ue Cero& )f t"e pro$ram does not e3ist, a run9time error occurs and not"in$ is returned& ;"en some app*ications run, t"ey return a a*ue t"at can be used to indicate an error& T"is a*ue is not aai*ab*e from t"e S"e** command& )ntuitie*y, it isnGt possib*e to obtain t"e fina* return a*ue from an app*ication %"en t"e S"e** function returns before t"e app*ication is finis"ed runnin$& TIP )n Oisua* +asic, t"e ar$uments for t"e S"e** function are different: S"e**,pat", %indo%=sty*e, bsync, Timeout.& T"e Timeout a*ue indicates "o% *on$ to %ait for t"e e3terna* app*ication to finis"& Ar$uments fo**o% t"e app*ication name as part of t"e same strin$, de*imited by spaces& O+ does not use a separate ar$ument to specify t"e ar$uments to send to t"e app*ication *aunc"ed by t"e S"e** command& )nstead, t"e ar$uments fo**o% t"e name of t"e app*ication, separated by spaces, inside t"e same 8uotation mar(s t"at contain t"e function pat" and name& T"is met"od a*so %or(s %it" 11o +asic, as an a*ternatie %ay to specify t"e S"e** command ar$uments& )f on*y function, ar$uments, and %indo% sty*e are re8uired, t"is a*ternatie %ay to %rite t"e S"e** command a**o%s you to "ae identica* statements for O+ or 11o routines& )f you %ant to specify bsync or Timeout ar$uments, t"e O+ and 11o enironments are not compatib*e& S(ellB"+(o!e+and.+$oo&1#( (ello .ou"C ) t*o aru!ent#= "(ello" and ".ou" 2.2.,. ("namic (ata Exchange Dynamic Data 23c"an$e ,DD2. is a mec"anism t"at a**o%s information to be s"ared bet%een pro$rams& Data may be updated in rea* time or it may %or( as a re8uest response& A*t"ou$" t"e DD2 commands accepted by a DD2 serer are specific to t"e indiidua* serer, t"e $enera* synta3 is t"e same& Most DD2 commands re8uire a Serer, Topic, and )tem& T"e Serer is t"e DD2 name for t"e app*ication t"at contains t"e data& T"e Topic, usua**y a fi*e name, contains t"e *ocation of t"e referenced )tem& T"e e3amp*e in Listin$ 1@1 uses t"e DD2 function in a #a*c spreads"eet to e3tract data in ce** A1 from an 23ce* spreads"eet& Listing 181. Use ##$ as a /alc function to e.tract cell -( from a document. 6--EB"#o$$ice"\"+(o!e+and.+t#tdoc&xl#"\"a>"C )--E in Calc to obtain a cell 205 6)$ile:+++(o!e+and.+3S3)LF#(eet>&A> )-irect re$erence to a cell T"e second *ine s"o%s "o% a ce** can be direct*y referenced in anot"er #a*c spreads"eet %it"out usin$ DD2& 11o +asic supports DD2 commands direct*y ,see Tab*e M@.& Table 78. ##$ commands supported by OOo !asic. Command Description DD223ecute,nDD2#"anne*, command. 23ecute a DD2 command& DD2)nitiate,Serer, Topic. 1pen a DD2 c"anne* and return t"e c"anne* number& DD2'o(e,nDD2#"anne*, item, data. Set data on t"e DD2 serer& DD2Re8uest,nDD2#"anne*, item. 'ost a DD2 re8uest oer an open c"anne*& DD2TerminateA**,. #*ose a** DD2 connections& 0irst, t"e DD2)nitiate function ma(es a connection to t"e DD2 serer& T"e first ar$ument is t"e name of t"e serer L for e3amp*e, DsofficeF or De3ce*F& T"e second ar$ument specifies t"e c"anne* to use& A common a*ue for a c"anne* is a fi*e name& T"e opened c"anne* is identified by an inte$er, %"ic" is returned by t"e DD2)nitiate command& A c"anne* number of 0 indicates t"at t"e c"anne* %as not opened& Attemptin$ to estab*is" a DD2 connection to 11o for a fi*e t"at is not current*y open returns 0 for t"e c"anne*& See Listin$ 1@2& Listing 182. Use ##$ to access a /alc document. Sub Exa!ple--E -i! n--EC(annel A# Inteer -i! # A# Strin REM OOo !u#t (a:e t(e $ile open or t(e c(annel *ill not be opened n--EC(annel 6 --EInitiateB"#o$$ice"= "c:\3S3"C I$ n--EC(annel 6 7 3(en Print "Sorr.= $ailed to open a --E c(annel" El#e Print "0#in c(annel " 4 n--EC(annel 4 " to re;ue#t cell A>" # 6 --ERe;ue#tBn--EC(annel= "A>"C Print "Returned " 4 # --E3er!inateBn--EC(annelC End I$ End Sub T"e usab*e commands and synta3 for eac" serer are serer dependent, so a comp*ete coera$e of DD2 is beyond t"e scope of t"is boo(& TIP Listin$ 1@2 runs and returns a a*ue, but it cras"es 11o %"en ) run it& (.3. )ser input and output 11o +asic proides a ery simp*e mec"anism for presentin$ information to t"e user and obtainin$ information from t"e user at run time ,see Tab*e MB.& T"ese routines arenGt used to access fi*es7 t"eyGre used strict*y for user input from t"e (eyboard and output to t"e screen& 206 Table 79. User input and output functions. !nction Description )nput+o3,Ms$, Tit*e, Defau*t, 3=pos, y=pos. Re8uest user input as a Strin$& Ms$+o3 ,Messa$e, Type, Tit*e. Disp*ay a messa$e in a nice dia*o$& 'rint e3pression17 e3pression2, e3pression37&&& 'rint e3pressions& 2.#.1. imple output 5se t"e 'rint statement for simp*e, sin$*e9*ine output& A *ist of e3pressions fo**o%s t"e 'rint statement& )f t%o e3pressions are separated by a semico*on, t"e e3pressions are printed ad/acent to eac" ot"er& )f t%o e3pressions are separated by a comma, t"e e3pressions are printed %it" a tab bet%een t"em7 you cannot c"an$e t"e siCe of t"e tabs& Print expre##ion>= expre##ion'= &&& ) Print *it( tab# bet*een expre##ion# Print expre##ion>\ expre##ion'\ &&& ) Print *it( not(in bet*een expre##ion# Print >=Ho*\"(ello"="aain"\%?&% ) Mixin #e!icolon# and co!!a# i# $ine Ar$uments are conerted to a *oca*e9specific strin$ representation before t"ey are printed& )n ot"er %ords, dates and numbers appear as you e3pect based on t"e *oca*e set in your confi$uration ,Too*s a 1ptions a Lan$ua$e Settin$s a Lan$ua$es.& +oo*ean a*ues, "o%eer, a*%ays print t"e te3t True or 0a*se& T"e "e*p inc*uded %it" 11o *ists t%o specia* e3pressions t"at %or( %it" t"e 'rint statement: Spc and Tab& )n 11o +asic, t"e Spc function %or(s t"e same as t"e Space function& )t accepts one numeric ar$ument and returns a strin$ composed comp*ete*y of spaces& T"e Tab function, a*t"ou$" documented, does not e3ist& See Listin$ 1@3 for a 'rint e3amp*e& TIP A*t"ou$" t"e Tab function "as been documented since 11o ersion 1, as of ersion 3&2, t"e Tab function sti** does not e3ist and it is sti** documented& Listing 183. #emonstrate the *pc67 function. Sub Exa!plePrint Print "It i# no*"\SpcB>'C\Ho*BC End Sub T"e 'rint statement is usua**y used for simp*e, sin$*e9*ine output %"i*e debu$$in$, because it a**o%s you to stop a macro from runnin$ by c*ic(in$ t"e #ance* button ,see 0i$ure 6A.& T"is is a $reat too* for debu$$in$& '*ace a 'rint statement before or after *ines t"at may cause a prob*em& )f t"e a*ues donGt appear to be correct, you can c*ic( t"e #ance* button to stop t"e macro& TIP T"e print statement is nice because you can cause a macro to stop runnin$ by c*ic(in$ #ance*& An adanta$e, and a disadanta$e, "o%eer, is t"at it *eaes t"e user in t"e )D2 at t"e print statement& Figure 65. he *pc function returns a string with spaces. 207 ;"en usin$ many 'rint statements for debu$$in$ purposes, print e3p*anatory information %it" t"e data to remind yourse*f %"at it is& Print "Be$ore t(e loop= x6 "\x "or i67 3o >7 Print "In t(e loop= i 6 "\i\" and x 6 "\x ;"en you print a strin$ t"at contains a ne%9*ine c"aracter ,AS#)) 10 or 13., a ne% dia*o$ is disp*ayed for eac" ne% *ine& T"e code in Listin$ 1@! disp*ays t"ree consecutie dia*o$s %it" te3t t"at reads DoneF, Dt%oF, and Dt"reeF& T"e 'rint dia*o$ is ab*e to print usin$ more t"an one *ine& )f a sin$*e *ine of te3t becomes too *on$, t"e *ine %raps and appears on more t"an one *ine& )n ot"er %ords, a*t"ou$" 'rint %i** %rap by itse*f, t"e user "as no %ay to force a ne% *ine in t"e dia*o$& Listing 184. New lines print in their own dialog. Print "one" 4 CHRFB>7C 4 "t*o" 4 CHRFB>%C 4 "t(ree" ) -i#pla.# t(ree dialo# T"e 'rint statement uses a simp*e, defined protoco* for numeric formattin$& 'ositie numeric e3pressions contain a *eadin$ space& 4e$atie numeric e3pressions contain a *eadin$ minus si$n& 4umbers %it" a decima* are printed in e3ponentia* notation if t"ey become too *ar$e& T"e 'rint statement disp*ays a print dia*o$ eac" time, un*ess t"e statement ends %it" eit"er a semico*on or a comma& )n t"is case it stores t"e te3t from eac" 'rint statement and adds to it unti* it encounters a 'rint statement t"at doesnGt end %it" a semico*on or a comma& Print "one"= )-o not print .et= end# *it( a co!!a Print "t*o" )Print "one t*o" Print "t(ree"=)-o not print .et= end# *it( a co!!a Print "$our"\ )-o not print .et= end# *it( a #e!icolon Print )Print "t(ree $our" 2.#.2. Multi7line output T"e Ms$+o3 statement proides more contro* oer t"e dia*o$ t"at is disp*ayed t"an does t"e 'rint statement, but can print on*y one strin$ e3pression at a time& Strin$ e3pressions t"at contain a ne%9*ine c"aracter ,AS#)) 10 or 13. are printed in t"e same dia*o$& 2ac" ne%9*ine c"aracter starts a ne% *ine in t"e dia*o$& Listing 185. #isplay a simple message bo. with a new line. Sub Exa!pleM#BoxWit(Return M#Box "one" 4 CHRFB>7C 4 "t*o" End Sub Figure 66. his simple Msg!o. dialog contains only an OM button. T"e dia*o$ in 0i$ure 66 is ery simp*e& T"e Ms$+o3 function accepts t%o ne% ar$uments, as s"o%n in Listin$ 1@6& T"e Dia*o$Tit*e is disp*ayed as t"e tit*e *ine of t"e dia*o$& Oa*id a*ues for Dia*o$Type are s"o%n in Tab*e @0& T"e Dia*o$Type determines %"ic" buttons are disp*ayed in t"e dia*o$, %"ic" button is t"e defau*t button, and %"ic" icon is disp*ayed on t"e dia*o$& 208 Listing 186. he Msg!o. function can accept a type and a dialog title. M#BoxBMe##aeC M#BoxBMe##ae= -ialo3.peC M#BoxBMe##ae= -ialo3.pe= -ialo3itleC Table 80. 3alid values for #ialogype. Vale Description 0 Disp*ay 1< button on*y& 1 Disp*ay 1< and #ance* buttons& 2 Disp*ay Abort, Retry and )$nore buttons& 3 Disp*ay 6es, 4o, and #ance* buttons& ! Disp*ay 6es and 4o buttons& A Disp*ay Retry and #ance* buttons& 16 Add t"e Stop icon to t"e dia*o$& 32 Add t"e _uestion icon to t"e dia*o$& !@ Add t"e 23c*amation 'oint icon to t"e dia*o$& 6! Add t"e )nformation icon to t"e dia*o$& 12@ 0irst button in t"e dia*o$ is t"e defau*t button& T"is is t"e defau*t be"aior& 2A6 Second button in t"e dia*o$ is t"e defau*t button& A12 T"ird button in t"e dia*o$ is t"e defau*t button& Listing 187. #emonstrate the Msg!o. type behavior. Sub M#BoxExa!ple#BC -i! iG -i! :alue# :alue# 6 Arra.B7= >= '= %= ?= <C "or i 6 ,BoundB:alue#C 3o 0BoundB:alue#C M#Box B"-ialo 3.pe: " W :alue#BiC= :alue#BiCC Hext :alue# 6 Arra.B>A= %'= ?Q= A?= >'Q= '<A= <>'C "or i 6 ,BoundB:alue#C 3o 0BoundB:alue#C M#Box B"Pe#= Ho= Cancel= *it( 3.pe: " W :alue#BiC= :alue#BiC W %C Hext End Sub 6ou can use more t"an one Dia*o$Type at t"e same time to ac"iee your desired buttons, icon, and defau*t be"aior& T"e disp*ay c"oices are encoded in t"e first four bits ,a*ues 091A are binary 000091111.7 t"e icons and defau*t be"aior are encoded in "i$"er bits ,for e3amp*e, 6! is 01000000 in binary.& To combine attributes, use 1R or add t"e a*ues to$et"er& ,T"is is simi*ar to t"e be"aior described for fi*e attributes&. A*t"ou$" you can disp*ay a dia*o$ %it" a #ance* button, t"is %onGt cause t"e macro to stop runnin$, as "appens %it" t"e 'rint statement& )nstead, t"e Ms$+o3 function returns an inte$er t"at identifies t"e se*ected button ,see Tab*e @1.& #*ic(in$ t"e #ance* button returns t"e a*ue 2, and t"e Abort button returns a 3, %"ic" can t"en be tested by your code7 t"en you ,in your code. can decide %"et"er or not you rea**y %ant to cance* t"e macro& 209 Table 81. Return values from Msg!o.. Vale Description 1 1< 2 #ance* 3 Abort ! Retry A )$nore 6 6es M 4o )n ot"er %ords, if you %ant t"e macro to stop %"en a user c*ic(s t"e #ance* button, you must c"ec( t"e return a*ue, as demonstrated in Listin$ 1@@& T"e messa$e contains a ne%9*ine c"aracter so t"e messa$e contains t%o *ines of te3t& T"e dia*o$ type re8uests t"ree buttons and an icon, and sets t"e second button to be defau*t ,see 0i$ure 6M.& T"e macro does different t"in$s based on t"e se*ected button& Listing 188. #emonstrate how Msg!o. works. Sub Exa!pleM#Box -i! nReturnCode A# Inteer -i! n-ialo3.pe A# Inteer -i! #Me##ae A# Strin #Me##ae 6 "An error occurredK" 4 CHRFB>7C 4 "-o t(e i!portant *or1 an.*a.U" REM % !ean# Pe#= Ho= Cancel REM ?Q di#pla.# an Excla!ation Point icon REM '<A #econd button i# de$ault& n-ialo3.pe 6 % OR ?Q OR '<A nReturnCode 6 M#BoxB#Me##ae= n-ialo3.pe= "M. 3itle"C I$ nReturnCode 6 ' 3(en Print "Stoppin t(e !acro no*K" Stop El#eI$ nReturnCode 6 A 3(en Print "Pou c(o#e Pe#" El#eI$ nReturnCode 6 2 3(en Print "Pou c(o#e Ho" El#e Print "I *ill ne:er et (ereK"=nReturnCode End I$ Print "Read. to exit t(e #ubroutine" End Sub Figure 67. +ancy Msg!o. with an icon and multiple buttons. 210 2.#.#. <rompting for input 5se t"e )nput+o3 function to prompt users for input& 6ou can specify t"e dia*o$ tit*e& )f a Defau*t a*ue is proided, itGs disp*ayed in t"e input bo3& T"e disp*ayed dia*o$ contains a te3t9input bo3, an 1< button, and a #ance* button& T"e )nput+o3 function returns a strin$ to t"e ca**in$ statement& #*ic(in$ #ance* returns a Cero9*en$t" strin$& InputBoxBMe##aeC InputBoxBMe##ae= 3itleC InputBoxBMe##ae= 3itle= -e$aultC InputBoxBMe##ae= 3itle= -e$ault= x5po#= .5po#C T"e position ar$uments are in t%ips and are re*atie to t"e upper9*eft corner of t"e current %indo%7 one inc" is 1!!0 t%ips& )f t"e position is not specified, t"e dia*o$ is centered bot" "oriConta**y and ertica**y oer t"e current %indo%& T"e e3amp*e in Listin$ 1@B disp*ays t"e input bo3 t%o inc"es from t"e *eft ed$e of t"e %indo% and four inc"es from t"e top& T"e siCe of t"e )nput+o3 is defined automatica**y from t"e Messa$e and buttons7 11o confi$ures t"e *ayout of t"is bo3, as it does for t"e ot"er basic input and output dia*o$s& Listing 189. #emonstrate "nput!o.. Sub Exa!pleInputBox -i! #Return A# Strin )Return :alue -i! #M# A# Strin )Hold# t(e pro!pt -i! #3itle A# Strin )Windo* title -i! #-e$ault A# Strin )-e$ault :alue -i! n/Po# A# Inteer )3*ip# $ro! le$t ede -i! nPPo# A# Inteer )3*ip# $ro! top ede n/Po# 6 >??7 * ' )3*o inc(e# $ro! le$t ede o$ t(e *indo* nPPo# 6 >??7 * ? )"our inc(e# $ro! top o$ t(e *indo* #M# 6 "Plea#e enter #o!e !eanin$ul text" #3itle 6 "Meanin$ul 3itle" #-e$ault 6 "Hello" #Return 6 InputBoxB#M#= #3itle= #-e$ault= n/Po#= nPPo#C I$ #Return ED "" 3(en REM Print t(e entered #trin #urrounded b. double ;uote# Print "Pou entered """\#Return\"""" El#e Print "Pou eit(er entered an e!pt. #trin or c(o#e Cancel" End I$ End Sub 0i$ure 6@ s"o%s t"e dia*o$ %"en it is first disp*ayed& 'ressin$ any (ey rep*aces t"e defau*t te3t, because t"is te3t is "i$"*i$"ted %"en t"e dia*o$ first opens& T"e macro in Listin$ 1@B inspects t"e return a*ue and c"ec(s for a Cero9*en$t" strin$& A Cero9*en$t" strin$ cou*d mean t"at t"e #ance* button %as used to c*ose t"e dia*o$, or it cou*d mean t"at t"e user entered a Cero9*en$t" strin$ and t"en used t"e 1< button to c*ose t"e dia*o$& T"ese t%o cases are not distin$uis"ab*e from eac" ot"er& 211 Figure 68. "nput!o. with default te.t selected. (.4. Error9related routines T"e error9re*ated routines ,see Tab*e @2. in 11o +asic return information re*ated to t"e *ast error& T"ese routines are used to determine %"at "appened and %"ere& T"e error information is reset %"en t"e error "and*er is c*eared, so sae t"e error information if your macro pro$ram %i** re8uire it *ater& Table 82. $rror functions in OOo !asic. !nction Description #O2rr #onert an e3pression to an error ob/ect& 2r* Line number of *ast error& 2rr 2rror number of *ast error& 2rror 2rror,error=number. Jet error messa$e eit"er for t"e *ast error or for t"e specified error messa$e& T"e macro in Listin$ 1B0 c"ec(s for an error before t"e error "and*er is reset& 2rror information is t"en saed& A*t"ou$" t"e macro in Listin$ 1B0 does not sae t"e error messa$e, t"e 2rror function accepts an error number as an optiona* ar$ument for %"ic" t"e error messa$e is returned& A*so see 0i$ure 6B& Listing 190. #emonstrate error related statements. Sub Exa!pleError On Error Joto BadError )Set up t(e error (andler Print >+ CIntB7&'C )-o a di:i#ion b. 8ero BadError: )Error (andler #tart# (ere -i! # A# Strin )Accu!ulate t(e !e##ae -i! oldError A# Inteer )Sa:e t(e error nu!ber -i! lineHu! A# Inteer )Sa:e t(e line nu!ber I$ Err ED 7 3(en )I$ an error occurred oldError 6 Err )Sa:e t(e error nu!ber lineHu! 6 Erl )Sa:e t(e error line nu!ber # 6 "Be$ore clearin t(e error (andler" 4 CHRFB>7C 45 "Error nu!ber " 4 Err 4 " Occurred at line nu!ber " 4 Erl 4 CHRFB>7C 45 "Err !e##ae: " 4 ErrorBC 4 CHRFB>7C End I$ On Error Joto 7 )Re#et t(e error (andler
REM 3(ere i# no* no in$or!ation to print # 6 # 4 CHRFB>7C 4 "A$ter clearin (andler:" 4 CHRFB>7C 45 "Error nu!ber " 4 Err 4 " Occurred at line nu!ber " 4 Erl 4 CHRFB>7C 212
REM 0#e t(e #a:ed in$or!ation # 6 # 4 CHRFB>7C 4 "Error in$o *a# #a:ed #o:" 4 CHRFB>7C 45 "Error nu!ber " 4 oldError 4 " Occurred at line nu!ber " 45 lineHu! 4 CHRFB>7C 4 "Err !e##ae: " 4 ErrorBoldErrorC M#Box #= 7= "Error Handlin" End Sub Figure 69. $rror information must be saved if it is used after resetting the error handler. (.. Miscellaneous routines T"e misce**aneous routines described in t"is section are $enera*9purpose routines t"at arenGt necessari*y re*ated to eac" ot"er ,see Tab*e @3.& Table 83. Miscellaneous functions in OOo !asic. !nction Description +eep Ma(e a system9dependent beep& #+oo*,e3pression. #onert an inte$er or strin$ to +oo*ean& 2niron,strin$. Return an enironment ariab*e& JetSo*arOersion )nterna* runnin$ ersion& #reate1b/ect,ob/=type. Dynamic ersion of DDim As 4e%F& 2rase,ob/. 0ree an ob/ects memory& T"e +eep statement $enerates a system9dependent beep& 6ou canGt c"an$e t"e pitc" or t"e *en$t" of t"e $enerated beep& 1n some systems, t"is p*ays a confi$urab*e sound fi*e t"rou$" t"e bui*t9in spea(er, and on ot"ers it $enerates a system eent t"at p*ays a system9defined sound t"rou$" *o%9*ee* interna* "ard%are& Beep )Jenerate a noi#e WaitB<77C )Wait >+' #econd Beep )Jenerate a noi#e 5se t"e #+oo* function to conert a strin$ or a number to a +oo*ean a*ue& Any numeric e3pression t"at ea*uates to 0 returns 0a*se& 4umeric e3pressions t"at are not 0 return True& Strin$ e3pressions t"at ea*uate to DTrueF or D0a*seF return True or 0a*se respectie*y7 case does not matter& A strin$ t"at does not ea*uate 213 e3act*y to True or 0a*se is ea*uated as a number& )f t"e strin$ doesnGt contain a number or t"e te3t DtrueF or Dfa*seF, a run9time error occurs& Print CBoolB"al#eC )"al#e Print CBoolB>%C )3rue Print CBoolB">%"C )3rue Print CBoolB"tr0e"C )3rue Print CBoolB"4(>"C )3rue Print CBoolB">%xx"C )run9ti!e error Print CboolB"3ruee"C )run9ti!e error 5se t"e 2niron function to retriee enironment ariab*es& )f t"e enironment ariab*e does not e3ist, an empty strin$ is returned& 4o met"od is proided to set or c"an$e enironment ariab*es& Print En:ironB"PA3H"C Print En:ironB"3EMP"C 5se $etSo*arOersion to obtain t"e inte$er interna* bui*d number of 11o& 6ou can %rite your macro to %or( around (no%n issues, based on re*ease documentation or discoered bu$s for different ersions of 11o& Print JetSolarOer#ion T"e #reate1b/ect function a**o%s ob/ects to be created dynamica**y& )f an ob/ect can be created usin$ DDim As 4e%F, it can be created %it" t"e #reate1b/ect function& )n ot"er %ords, if an ob/ect can be created as a user9defined type, #reate1b/ect can create one& T"e 11o under*yin$ specia* data ob/ects, %"ic" are coered in dept" *ater, are ca**ed 5niersa* 4et%or( 1b/ects ,541.& T"ese ob/ects cannot be created usin$ #reate1b/ect& 11o does define structures t"at are not 541 ob/ects t"at can be created usin$ Dim As 4e% and #reate1b/ect ,see Listin$ 1B1.& Listing 191. /reate an ob%ect using /reateOb%ect or #im -s New. -i! oProp A# He* co!&#un&#tar&bean#&Propert.Oalue -i! o A# ObNect o 6 CreateObNectB"co!&#un&#tar&bean#&Propert.Oalue"C Listin$ 1B1 demonstrates creatin$ a ariab*e type defined by 11o t"at is *i(e a user9defined type& T"e actua* type name of t"e ob/ect is Dcom&sun&star&beans&'ropertyOa*ueF& Many of t"e ob/ects in 11o "ae simi*ar*y *on$ and cumbersome names& ;"i*e %ritin$ about or discussin$ ariab*e types suc" as t"is, itGs common to abbreiate t"e type name as t"e *ast portion of t"e name& 0or e3amp*e, set t"e 4ame property of t"e 'ropertyOa*ue ariab*e ,see Listin$ 1B2.& 1b/ects of type 'ropertyOa*ue "ae t%o properties: 4ame as a Strin$ and Oa*ue as a Oariant& Listing 192. #im a 9roperty3alue and use /reateOb%ect to create a new one. -i! aProp A# He* co!&#un&#tar&bean#&Propert.Oalue aProp&Ha!e 6 ""ir#tHa!e" )Set t(e Ha!e propert. aProp&Oalue 6 "Paterton" )Set t(e Oalue propert. Era#e aProp Print I#HullBaPropC )3rue REM Create a ne* oneK -i! aPropr aPropr 6 CreateObNectB"co!&#un&#tar&bean#&Propert.Oalue"C Era#e aProp Print I#HullBaPropC )3rue Print I#E!pt.BaPropC )"al#e 214 -i! a a 6 arra.B"(ello"= 'C Era#e a Print I#HullBaC )"al#e Print I#E!pt.BaC )3rue -i! bBC A# Strin Re-i! bB7 3o >C A# Strin bB7C 6 "Hello" : bB>C 6 "Pou" )bBC 6 "(ello" )Runti!e error= :ariable not #et BExpectedC )Print bBC )Runti!e error= :ariable not #et BExpectedC )Era#e bBC )S.ntax Error= not too #urpri#ed Era#e b )I did not expect t(i# to *or1& Print I#HullBbBCC )"al#e Print I#E!pt.BbBCC )"al#e Print I#Arra.BbBCC )"al#e= 3(i# i# probabl. bad& )Print ,BoundBbBCC )Error= :ariable not #et& bBC 6 "(ello" )Odd= no* I can treat bBC a# a #trin :ariable Print bBC )(ello Listin$ 1B2 demonstrates t"e 2rase statement, introduced %it" 11o ersion 2&0& 5se t"e 2rase statement to free memory t"at %i** no *on$er be used& Do not use 2rase un*ess you are finis"ed %it" t"e ariab*e& 5se t"e #reate1b/ect function to create an ob/ect dynamica**y L in ot"er %ords, %"en you donGt %ant to create t"e ob/ect %"en itGs dec*ared& 6ou can use #reate1b/ect to create on*y one ob/ect at a time& 5se t"e Dim As 4e% construction to create an array of a particu*ar type ,see Listin$ 1B3.& 6ou can een c"an$e t"e dimension of t"e array and presere t"e data& )t is more cumbersome to dec*are an array and t"en fi** it %it" t"e appropriate a*ues indiidua**y ,see Listin$ 1B!.& Listing 193. #emonstrate Re#im with 9reserve Sub Exa!pleRe-i!Pre#er:eProp REM t(i# i# ea#. to create t(i# *a. -i! oProp#B'C A# He* co!&#un&#tar&bean#&Propert.Oalue oProp#B7C&Ha!e 6 ""ir#tHa!e" : oProp#B7C&Oalue 6 "Moe" oProp#B>C&Ha!e 6 ",a#tHa!e" : oProp#B>C&Oalue 6 "Blat(er" oProp#B'C&Ha!e 6 "Ae" : oProp#B>C&Oalue 6 <% Re-i! Pre#er:e oProp#B%C A# He* co!&#un&#tar&bean#&Propert.Oalue oProp#B%C&Ha!e 6 "Wei(t" : oProp#B%C&:alue 6 @2 Print oProp#B'C&Ha!e )Ae End Sub Listing 194. Nou can add 9roperty3alue variables to a declared array. REM 3(i# i# !ore cu!ber#o!e= but .ou can #till do it&&& -i! oProp#B'C oProp#B7C 6 CreateObNectB"co!&#un&#tar&bean#&Propert.Oalue"C oProp#B>C 6 CreateObNectB"co!&#un&#tar&bean#&Propert.Oalue"C oProp#B'C 6 CreateObNectB"co!&#un&#tar&bean#&Propert.Oalue"C oProp#B7C&Ha!e 6 ""ir#tHa!e" : oProp#B7C&Oalue 6 "Moe" oProp#B>C&Ha!e 6 ",a#tHa!e" : oProp#B>C&Oalue 6 "Blat(er" oProp#B'C&Ha!e 6 "Ae" : oProp#B>C&Oalue 6 <% Assi$nin$ one array to anot"er assi$ns a reference so t"at bot" arrays reference t"e same array ob/ect& ;it" ariab*e types suc" as )nte$er and 'ropertyOa*ue, assi$nment ma(es a copy& 0ai*ure to understand %"ic" types copy by a*ue and %"ic" types copy by reference is a common source of errors& Structures and inte$ra* 215 types ,suc" as )nte$er and Strin$. copy as a a*ue, but arrays and 541 ariab*es, as %i** be discussed *ater, copy as a reference& #opyin$ by a*ue is demonstrated in an obious %ay in Listin$ 1BA& Listing 195. 9roperties copy by value. Sub Exa!pleCop.A#Oalue -i! aProp> -i! aProp' aProp> 6 CreateObNectB"co!&#un&#tar&bean#&Propert.Oalue"C aProp>&Ha!e 6 "Ae" )Set Ha!e Propert. on one aProp>&Oalue 6 '2 )Set Oalue Propert. on one aProp' 6 aProp> )Ma1e a cop. aProp'&Ha!e 6 "Wei(t")Set Ha!e Propert. on t*o aProp'&Oalue 6 @2 )Set Oalue Propert. on t*o Print aProp>&Ha!e= aProp'&Ha!e )Ae Wei(t End Sub TIP Standard ob/ect ariab*es copy by a*ue, and 541 ariab*es copy by reference& ;"en one inte$er ariab*e is assi$ned to anot"er, it is understood t"at t"e a*ue %as copied and not"in$ more& T"e t%o ariab*es are sti** independent of eac" ot"er& T"is is a*so true for structures& Te3t cursors, discussed *ater, contain a property ca**ed #"arLoca*e, %"ic" specifies t"e country and *an$ua$e for t"e te3t se*ected by t"e te3t cursor& T"e common, incorrect met"od to set t"e *oca*e is to access t"e ariab*e direct*y& T"is sets t"e *an$ua$e and country on a copy of t"e #"arLoca*e property rat"er t"an on t"e copy used by t"e te3t cursor& ) see t"is type of error often& oCur#or&C(ar,ocale&,anuae 6 "$r" )#et lanuae to "renc( on a cop. oCur#or&C(ar,ocale&Countr. 6 "CH" )#et countr. to S*it8erland on a cop. 1ne correct met"od to set t"e *oca*e is to create a ne% Loca*e structure, modify t"e ne% structure, and copy t"e ne% structure to t"e te3t cursor& -i! a,ocale A# He* co!&#un&#tar&lan&,ocale a,ocale&,anuae 6 "$r" )Set ,ocale to u#e t(e "renc( lanuae a,ocale&Countr. 6 "CH" )Set ,ocale to u#e S*it8erland a# t(e countr. oCur#or&C(ar,ocale 6 a,ocale )A##in t(e :alue bac1 6ou can a*so obtain a copy of t"e structure, modify t"e copied structure, and copy t"e modified structure to t"e te3t cursor& -i! a,ocale a,ocale 6 oCur#or&C(ar,ocale )Or u#e a cop. a,ocale&,anuae 6 "$r" )Set ,ocale to u#e t(e "renc( lanuae a,ocale&Countr. 6 "CH" )Set ,ocale to u#e S*it8erland a# t(e countr. oCur#or&C(ar,ocale 6 a,ocale )A##in t(e :alue bac1 (.#. 3artition 'artition is not documented and %as *i(e*y added for O+ compatibi*ity& 'artition return a Oariant ,Strin$. indicatin$ %"ere a number occurs in a ca*cu*ated series of ran$es& PartitionBnu!ber= #tart5:alue= #top5:alue= inter:alC #onsider t"e fo**o%in$ a*ues: #tart5:alue 6 7 216 #top5:alue 6 >2 inter:al 6 < T"e fo**o%in$ DpartitionsF are assumed: 1. D :91F 2eryt"in$ before 0 2. D0:!F 0ie numbers from 0 to !& 3. DA:BF 0ie numbers from A to B& !. D10:1!F 0ie numbers from 10 to 1!& A. D1A:1MF T"ree numbers from 1A to 1M& 6. D1@: F 2eryt"in$ after 1M& T"e e3amp*e in Listin$ 1B6 tests numbers before and after t"e intera*& As e3pected, a*ues before t"e first intera* run from D :91F& Oa*ues t"at fa** into an intera* are nice*y identified& T"e on*y tric(y part is t"at t"e fina* intera* c*aims to inc*ude a*ues from D1A:1BF een t"ou$" 1@ and 1B are not in t"e intera*& Listing 196. Run partition through a series of values. Sub Exa!plePartition -i! iG -i! #F "or i 6 9' 3o '7 # 6 # 4 "PartitionB" 4 i 4 "= 7= >2= <C 6 " 4 5 PartitionBi= 7= >2= <C 4 CHRFB>7C Hext M#Box # End Sub 217 Figure 70. 9artition shows the interval containing a number. T"e a*ues returned by 'artition are carefu**y formatted& T"e *o%er a*ue and upper a*ue "ae t"e same number of c"aracters, %"ic" means t"at t"ey %i** sort proper*y if you c"oose to do so& T"is a*so "e*ps if you %ant to parse t"e returned a*ues& (.$. !nspection and identification of variables 11o +asic contains numerous functions to inspect and identify ariab*es ,see Tab*e @!.& T"ese routines are fre8uent*y used %"en you ca** a function and arenGt certain of t"e return type& T"ese routines are a*so usefu* for debu$$in$& 0or e3amp*e, you cou*d use t"ese functions to erify t"at a return type is a*id& 218 Table 84. 3ariable inspection functions in OOo !asic. !nction Description )sArray )s t"e ariab*e an array> )sDate Does t"e strin$ contain a a*id date> )s2mpty )s t"e ariab*e an empty Oariant ariab*e> )sMissin$ )s t"e ariab*e a missin$ ar$ument> )s4u** )s t"e ariab*e an unassi$ned ob/ect> )s4umeric Does t"e strin$ contain a a*id number> )s1b/ect )s t"e ariab*e an ob/ect> )s5noStruct )s t"e ariab*e a 541 structure> TypeLen Space used by t"e ariab*e type& Type4ame Return t"e type name of t"e ob/ect as a Strin$& OarType Return t"e ariab*e type as an )nte$er& 5se )sArray to see if a ariab*e is an array ,see Listin$ 1BM.& )f )sArray returns True, it does not imp*y t"at t"e ariab*e "as data or een t"at it is dimensioned L mere*y t"at it e3ists and is defined as an array& T"e 5+ound and L+ound functions, as a*ready discussed, return t"e upper and *o%er bounds of t"e array& Listing 197. Use "s-rray to see if a variable is an array. -i! n A# ,on )3(i# i# HO3 an arra. -i! aBC A# Strin )3(i# i# an arra. -i! bB<C )3(i# i# an arra. -i! : A# Oariant )3(i# i# not an arra. .et Print I#Arra.B:C )"al#e Print I#Arra.BnC )"al#e Print I#Arra.BaC )3rue Print I#Arra.BbBCC )3rue Re-i! :B%C )It i# an arra. no*K Print I#Arra.B:BCC )3rue 5se t"e )sDate function to test if a strin$ contains a a*id date ,see Listin$ 1B@.& T"e ar$uments are conerted to a strin$ before t"ey are used, so numeric ar$uments return 0a*se& T"e )sDate function tests more t"an /ust synta37 it c"ec(s to see if t"e strin$ contains a a*id date& T"e same c"ec( is not made on t"e time component of t"e strin$& Listing 198. "s#ate verifies that a string contains a valid date. Print I#-ateB"-ece!ber >= ><Q' ':>%:?'"C )3rue Print I#-ateB"':>%:?'"C )3rue Print I#-ateB">'+>+><Q'"C )3rue Print I#-ateBHo*C )3rue Print I#-ateB"'A:A>:>>'"C )3rue Print I#-ateB3rueC )"al#e con:ert# to #trin $ir#t Print I#-ateB%'AQA&''%%'C )"al#e con:ert# to #trin $ir#t Print I#-ateB"7'+'@+'77%"C )"al#e= onl. 'Q da.# in "ebruar. '77% 219 Li(e t"e )sDate function, t"e )s4umeric function *oo(s at strin$s ,see Listin$ 1BB.& )f t"e ar$ument is not entire*y a so*itary a*id number, e3cept for *eadin$ or trai*in$ spaces and enc*osin$ 8uotation mar(s, it returns 0a*se& Listing 199. "sNumeric is very picky about what it accepts. Print I#Hu!ericB" >'%"C )3rue Print I#Hu!ericB" >' %"C )"al#e Print I#Hu!ericB>&'%C )3rue Print I#Hu!ericB>='%C )3rue Print I#Hu!ericB">'%abc"C )"al#e Print I#Hu!ericB3rueC )"al#e Print I#Hu!ericBHo*C )"al#e Oariant ariab*es start %it" no a*ue at a**7 t"ey are initia**y empty& 1b/ect ariab*es are initia*iCed %it" t"e a*ue nu**& 5se t"e functions )s2mpty and )s4u** to test t"ese conditions& 5se t"e )s1b/ect function to determine if a ariab*e is an ob/ect& -i! : A# Oariant )Start# a# not initiali8ed= E!pt. -i! o A# ObNect )Initiali8ed to null Print I#ObNectB:C )"al#e Ho= a Oariant i# not an ObNect Print I#ObNectBoC )3rue Pe#= t(i# i# an ObNect Print I#E!pt.B:C )3rue Oariant# #tart a# E!pt.= not initiali8ed Print I#HullB:C )"al#e 3o be null= a Oariant !u#t contain #o!et(in Print I#E!pt.BoC )"al#e Oariant# #tart a# E!pt.= not ObNect# Print I#HullBoC )3rue ObNect# #tart a# null : 6 o Print I#ObNectB:C )3rue 3(e :ariant Nu#t beca!e an ObNect& Print I#E!pt.B:C )"al#e Oariant no* contain# a :alue Ban ObNectC Print I#HullB:C )3rue Oariant contain# a null ObNect 5se t"e )sMissin$ function to determine if an optiona* ar$ument is missin$& 5sua**y, some defau*t a*ue is used if an ar$ument is missin$& Sub 3e#tOptional Print "Ar i# "\Exa!pleOptionalBC )Ar i# !i##in Print "Ar i# "\Exa!pleOptionalB"(ello"C )Ar i# (ello End Sub "unction Exa!pleOptionalBOptional xC A# Strin Exa!pleOptional 6 II"BI#Mi##inBxC= "Mi##in"= CStrBxCC End "unction 5se t"e function )s5noStruct to determine if a ariab*e contains a structure defined by 1pen1ffice&or$& -i! : Print I#0noStructB:C )"al#e : 6 Create0noStructB"co!&#un&#tar&bean#&Propert."C )Create a 0HO Print I#0noStructB:C )3rue 5se t"e Type4ame function for a strin$ representation of t"e ariab*eGs type& T"e OarType function returns an inte$er correspondin$ to t"e ariab*e type& Tab*e @A contains a *ist of t"e possib*e types& T"e first co*umn, 220 *abe*ed +AS)#, indicates if t"e type is common to +AS)# and t"erefore *i(e*y to be seen& T"e ot"er a*ues represent types t"at are interna* to 11o& 11o +asic typica**y maps interna* types to standard 11o +asic types, so you arenGt *i(e*y to see t"ese ot"er types& T"ey are, "o%eer, contained in t"e source code and t"ey are inc*uded for comp*eteness& Table 85. 3ariable types and names. B$SIC VarType Type%ame Len Description yes 0 2mpty 0 Oariant ariab*e is not initia*iCed yes 1 4u** 0 4o a*id data in an 1b/ect ariab*e yes 2 )nte$er 2 )nte$er ariab*e yes 3 Lon$ ! Lon$ )nte$er ariab*e yes ! Sin$*e ! Sin$*e f*oatin$9point ariab*e yes A Doub*e @ Doub*e f*oatin$9point ariab*e yes 6 #urrency @ #urrency ariab*e yes M Date @ Date ariab*e yes @ Strin$ str*en Strin$ ariab*e yes B 1b/ect 0 1b/ect ariab*e no 10 2rror 2 )nterna* 11o type yes 11 +oo*ean 1 +oo*ean ariab*e yes 12 Oariant 0 Oariant ariab*es act *i(e any type no 13 Data1b/ect 0 )nterna* 11o type no 1! 5n(no%n Type 0 )nterna* 11o type no 1A 5n(no%n Type 0 )nterna* 11o type no 16 #"ar 1 )nterna* 11o type, a sin$*e te3t c"aracter yes 1M +yte 1 )nterna* 11o type, but you can use #+yte to create one no 1@ 5S"ort 2 )nterna* 11o type, unsi$ned s"ort inte$er ,16 bits. no 1B 5Lon$ ! )nterna* 11o type, unsi$ned *on$ ,32 bits. no 20 Lon$6! @ )nterna* 11o type, *on$ ,6! bits. no 21 5Lon$6! @ )nterna* 11o type, unsi$ned *on$ ,6! bits. no 22 )nt 2 )nterna* 11o type, inte$er ,16 bits. no 23 5)nt 2 )nterna* 11o type, unsi$ned inte$er ,16 bits. no 2! Ooid 0 )nterna* 11o type, no a*ue no 2A EResu*t 0 )nterna* 11o type no 26 'ointer 0 )nterna* 11o type, pointer to somet"in$ no 2M DimArray 0 )nterna* 11o type no 2@ #Array 0 )nterna* 11o type no 2B 5serdef 0 )nterna* 11o type, user9defined no 30 Lpstr str*en )nterna* 11o type, *on$ pointer to a strin$ no 31 Lp%str str*en )nterna* 11o type, *on$ pointer to a D;ideF 5nicode strin$ 221 B$SIC VarType Type%ame Len Description no 32 5n(no%n Type 0 )nterna* core strin$ type no 33 ;Strin$ str*en )nterna* 11o type, D;ideF 5nicode strin$ no 3! ;#"ar 2 )nterna* 11o type, D;ideF 5nicode c"aracter no 3A )nt6! @ )nterna* 11o type, inte$er ,6! bits. no 36 5)nt6! @ )nterna* 11o type, unsi$ned inte$er ,6! bits. no 3M Decima* 1L2 Automation type aai*ab*e in O+& 5se t"e TypeLen function to determine "o% many bytes a ariab*e uses& T"e returned a*ue is "ard coded for eery a*ue e3cept for t"e strin$s, %"ic" return t"e *en$t" of t"e strin$& Array ariab*es a*%ays return a *en$t" of Cero& T"e macro in Listin$ 200 $enerates a** of t"e standard +AS)# types, p*aces t"em into an array, and bui*ds a strin$ containin$ t"e type, *en$t", and type name, as s"o%n in 0i$ure M1& Listing 200. *how type information for standard types. Sub Exa!ple3.pe# -i! b A# Boolean -i! c A# Currenc. -i! t A# -ate -i! d A# -ouble -i! i A# Inteer -i! l A# ,on -i! o A# ObNect -i! $ A# Sinle -i! # A# Strin -i! : A# Oariant -i! n A# Oariant -i! taBC -i! ##F n 6 null taBC 6 Arra.B:= n= i= l= $= d= c= t= #= o= b= CB.teB%C 5 Create0noOalueB"un#ined lon"= >7CCC "or i 6 ,BoundBtaBCC 3o 0BoundBtaBCC ## 6 ## 4 A-P3.peStrinBtaBiCC Hext M#Box ##= 7= "3.pe= ,ent(= and Ha!e" End Sub "unction A-P3.peStrinB:C A# Strin -i! # A# Strin )Hold t(e return #trin -i! i A# Inteer )-u!!. inteer :alue # 6 # 4 "3.pe 6 " ),eadin t.pe #trin i 6 Oar3.peB:C )Jet t(e t.pe I$ i E >7 3(en # 6 S 4 "7" ),eadin 8ero i$ re;uired # 6 # 4 CStrBiC )Add t(e t.pe nu!ber I$ I#Arra.B:C 3(en # 6 # 4 " B" i 6 i AH- HO3 Q>@' I$ i E >7 3(en # 6 S 4 "7" ),eadin 8ero i$ re;uired # 6 # 4 CStrBiC 4 "C" )Add t(e t.pe nu!ber 222 El#e # 6 # 4 " ,en 6 " ),eadin lent( #trin i 6 3.pe,enB:C )W(at i# t(e lent( I$ i E >7 3(en # 6 S 4 "7" ),eadin 8ero i$ re;uired # 6 # 4 CStrBiC )Add in t(e lent( End I$ # 6 # 4 " Ha!e 6 " ),eadin Ha!e #trin # 6 # 4 3.peHa!eB:C4 CHRFB>7C)Add in t(e na!e and a ne*9line c(aracter A-P3.peStrin 6 # )Return :alue $or t(e $unction End "unction Figure 71. 3ariable types) lengths) and names. T"e function AD'TypeStrin$ does t"e %or( of $eneratin$ t"e disp*ay strin$& )t $ies specia* "and*in$ to arrays, because t"e returned type numbers for arrays are comp*ete*y different t"an t"e type numbers for t"e standard ariab*es& At *east t"ey seem t"at %ay unti* you start *oo(in$ ery c*ose*y at t"e numbers& )f t"e t"ou$"t of t%idd*in$ bits ma(es you tremb*e, s(ip t"e rest of t"is para$rap"& T"e a*ue returned by OarType for an array a*%ays "as bit 1! set L a 1 fo**o%ed by 13 Ceros in binary& T"is is @1B2 in decima* and 2000 in "e3adecima*& T"e )sArray function is imp*emented by c"ec(in$ bit 1! of t"e OarType& )f you c*ear bit 1!, t"e number t"at remains te**s you %"at numeric type is used for t"e array& T"e 41T operator c*ears eery bit t"at is set and sets eery bit t"at is c*ear, so 41T @1B2 proides t"e number %it" eery bit set e3cept for bit 1!& )f you A4D t"is %it" t"e type, it c*ears bit 1!, *eain$ t"e rest of t"e bits intact& i 6 i AH- HO3 Q>@' T"e *en$t" of an array is a*%ays returned as Cero, so ) didnGt inc*ude t"is by OarType in Listin$ 200& T"e code in Listin$ 201 is simi*ar to Listin$ 200 but t"e types are arrays& 4otice t"at t"e type name for array types contains parent"eses D,.F fo**o%in$ t"e name ,see 0i$ure M2.& Listing 201. *how type information for arrays. Sub Exa!ple3.pe#Arra. -i! bBC A# Boolean -i! cBC A# Currenc. -i! tBC A# -ate -i! dBC A# -ouble -i! iBC A# Inteer -i! lBC A# ,on 223 -i! oBC A# ObNect -i! $BC A# Sinle -i! #BC A# Strin -i! :BC A# Oariant -i! taBC= NG -i! ##F taBC 6 Arra.Bi= l= $= d= c= t= #= o= b= :C "or NG 6 ,BoundBtaBCC 3o 0BoundBtaBCC ## 6 ## 4 A-P3.peStrinBtaBNGCC Hext M#Box ##= 7= "3.pe= ,ent(= and Ha!e" End Sub Figure 72. ypes) lengths) and names for array variables. (.&. %outines 'ou should not use and other curiosities ) first "eard my $ood friend Manfred say t"at Dt"e boo( t"at is forbidden to read turns one reader into t"ree&F Do not app*y t"is *o$ic to t"e routines out*ined in t"is section& T"ese routines are not officia**y documented7 een if t"ey %or( no%, t"ey may stop %or(in$ in t"e near future& Deprecated routines may sti** e3ist and t"ey may %or(& T"ey may a*so be remoed at any time& 2mpty stubs e3ist, compi*e, and run, but do not"in$& 6ou may find o*der code t"at uses t"ese *e$acy functions ,see Tab*e @6.& ) inc*ude #Dec in t"e *ist because it is on*y *isted on t"e ;indo%s p*atform, %"ic" is /ust p*ain si**y& 224 Table 86. #eprecated and 8uestionable routines. &otine Comment AboutStar+asic Deprecated empty stub t"at used to be an information dia*o$& Send<eys Deprecated, $enerates an error& DumpA**1b/ects,pat", boo*. )nterna* debu$$in$ routine7 no typica* use (no%n& Load,1b/ect. Deprecated& 5n*oad,1b/ect. Deprecated& Load'icture,pat". Deprecated& Loads an ima$e fi*e& Sae'icture,ob/, pat". Deprecated& 0ai*s to sae an ima$e fi*e& #reate'ropertySet,ob/ect. Deprecated& 2ar*y 541 support function& #Dec,e3pression. Jenerate a Decima* type7 on*y imp*emented on ;indo%s& JetJ5)Oersion,. Deprecated, returns 91& DumpA**1b/ects is an interna* debu$$in$ routine t"at accepts t%o ar$uments& T"e first ar$ument is a fi*e name t"at %i** contain t"e te3t output& T"e second ar$ument is a +oo*ean a*ue t"at determines if eac" ob/ect s"ou*d be fu**y *oaded before it is dumped& 0or performance reasons, some properties are not created unti* t"ey are accessed for t"e first time& T"is is true, een for +AS)# ob/ects t"at %rap 541 ob/ects& -u!pAllObNect#B"C:\$oo&txt"= trueC )"ull. load all obNect# be$ore du!pin T"e Load'icture and Sae'icture routines refer to t"e o*d +AS)# dia*o$s t"at are not imp*emented usin$ 541& T"e ob/ect returned by Load'icture %as used to set a picture on an ima$e contro*& T"ere is no% an ima$e contro* t"at uses t"e 541 A') to set t"e picture& -i! : : 6 ,oadPictureB"C:\te#t>&Np"C )3(i# #ee!# to load t(e picture Sa:ePictureB:= "C:\te#t'&Np"C )3(i# *rite# a 8ero lent( $ile T"e #reate'ropertySet function accepts an ob/ect as an ar$ument and returns a property set& T"e property set is empty and not ery usefu*& T"is function %as created %"en t"e 541 functiona*ity %as first introduced, and %i** be remoed from t"e source code in t"e future& )f you find code t"at uses t"is function, ) recommend t"at you c"an$e it& : 6 CreatePropert.SetB3(i#Co!ponent&3extC (.(. %outines ! do not understand ) find functions by readin$ t"e source code, some ) understand and some ) do not& T"is section contains t"e functions t"at ) "ae not been ab*e to satisfactori*y document& 225 Table 87. +unctions " do not fully understand. !nction Description 2nab*eResc"edu*e,boo*. Me RTL JetDia*o$Poom0actorI,. T"e factor by %"ic" a dia*o$ is sca*ed in t"e I direction& 5sed %"i*e determinin$ "o% to sca*e an ima$e for preie%& JetDia*o$Poom0actor6,. T"e factor by %"ic" a dia*o$ is sca*ed in t"e 6 direction& 2nab*eResc"edu*e accepts a boo*ean ar$ument& ) "ae found neit"er usa$e nor documentation for t"is met"od, so, ) "ae on*y specu*ation as to its purpose& ) specu*ate t"at 11o sometimes resc"edu*es t"in$s, per"aps eents, and t"at sometimes resc"edu*in$ s"ou*d not be a**o%ed7 say durin$ a ca**bac(& 5se 2nab*eResc"edu*e to enab*e, or disab*e, t"e interna* resc"edu*e f*a$& )t is prob*ematic t"at t"ere is no met"od to determine t"e current state, so you cannot set it and t"en restore it& )t appears, "o%eer, t"at t"e defau*t state is enab*ed& Me is aai*ab*e in t"e &4et %or*d to reference t"e c*ass or structure in %"ic" t"e code is e3ecutin$& )t is not c*ear to me "o% to $enerate a a*id ca** usin$ Me at t"is point& )f Me is not used in t"e correct conte3t, an error occurs& RTL appears to return a reference of t"e run time *ibrary, but, ) am not c*ear on t"is point& My $uess is t"at if ) cou*d use t"is, t"en ) mi$"t be ab*e to do t"in$s suc" as access met"ods of t"e RTL and ca** t"em7 but t"at is a %i*d $uess& JetDia*o$Poom0actorI and JetDia*o$Poom0actor6 appear to be used to determine t"e sca*e factor to use so t"at a preie% ima$e %i** be proper*y disp*ayed& )n t"e ery fe% e3amp*es t"at ) "ae found, ) a*%ays see code simi*ar to t"e fo**o%in$: *idt(3o0#e 6 Jet-ialoVoo!"actor/Bi!aeWidt(C * i!aeWidt( (ei(t3o0#e 6 Jet-ialoVoo!"actorPBi!aeHei(tC * i!aeHei(t +rus" up on your Jerman and t"en read t"is: "ttp:--%%%&"er$er&net-staroffice-sbinteam-os-preie%2&"tm& )t is my opinion t"at you probab*y do not re8uire t"ese met"ods, but, ) cou*d be %ron$& (.1+. Conclusion T"is c"apter contains a *ot of subt*e information& )f you are usin$ 11o +asic for t"e first time, consider readin$ t"e c"apter a$ain after you "ae more e3perience& T"e routines for inspectin$ ariab*es are usefu* %"i*e ea*uatin$ returned ob/ects& <no%*ed$e of t%ips is re8uired %"i*e tryin$ to determine spacin$ and ima$e siCes& +e certain to %atc" for deprecated routines so t"at can aoid usin$ t"em& 226 13. 9ni'ersal -et1ork Ob4ects T"e interna*s of 1pen1ffice&or$ are based on 5niersa* 4et%or( 1b/ects ,541.& T"is c"apter introduces t"e subroutines and functions supported by 1pen1ffice&or$ +asic t"at are re*ated to 541& T"is c"apter coers met"ods t"at create and inspect ob/ects t"at are ita* to t"e interna*s of 1pen1ffice&or$& 5p to t"is point, ) "ae most*y dea*t %it" simp*e sin$*e a*ue t"in$s suc" as strin$ and inte$er& )n $enera*, "o%eer, an ob/ect may contain mu*tip*e pieces data and met"ods7 for e3amp*e, you can access a document as a ariab*e and access information about t"e document ,data or properties., and ca** met"ods t"at manipu*ate t"e document& )n t"is c"apter, ) be$in to discuss t"in$s re*ated to t"e actua* imp*ementation of 11o L t"in$s t"at a**o% you to e3p*oit t"e interna* capabi*ities of 11o& 6ouG** a*so be$in to see more detai*s about "o% 11o is imp*emented L %"ic" you need to bui*d t"e rea**y coo* stuff& Are you a pro$rammer or a "i$"*y tec"nica* person> )f not, s(ip t"is para$rap" and $o direct*y to t"e tip& Sti** readin$> Jreat, so 541 is: T"e interface based component mode* for 11o& 2nab*es interoperabi*ity bet%een pro$rammin$ *an$ua$es, ob/ect mode*s and "ard%are arc"itectures, eit"er in process or oer process boundaries, as %e** as in t"e intranet or t"e )nternet& 4e% *an$ua$es are supported by addin$ a *an$ua$e bindin$& T"is is a*so stated as addin$ a Dbrid$eF or DadapterF& T"is paradi$m ma(es it easier to support mu*tip*e *an$ua$es& 541 components may be imp*emented in, and accessed from, any pro$rammin$ *an$ua$e %it" a comp*ete *an$ua$e bindin$& TIP 6ou can %rite po%erfu* macros %it"out fu**y understand 5niersa* 4et%or( 1b/ects& Kust t"in( of a 541 as any ob/ect t"at is used interna**y by 11o& Stated more simp*y: T"e interna* parts of 11o are used as 5niersa* 4et%or( 1b/ects& +y usin$ 541s, it is possib*e to access an instance of 11o runnin$ on a different computer and operatin$ system& A a$ue understandin$ of 5niersa* 4et%or( 1b/ects is important because most of t"e interna*s of 1pen1ffice&or$ are imp*emented usin$ 541& Tab*e @@ *ists t"e 11o +asic functions used to dea* %it" 541& 227 Table 88. +unctions related to Universal Network Ob%ects in OOo !asic. !nction Description +asicLibraries Access +asic *ibraries stored in a document& #reate1b/ect,ob/=type. Ab*e to create any standard type, more f*e3ib*e t"an #reate5noStruct and #reate5noSerice& #reate5noDia*o$,. #reate an e3istin$ dia*o$& #reate5noListener,. #reate a *istener& #reate5noSerice,. #reate a 5niersa* 4et%or( 1b/ect Serice& #reate5noStruct,. #reate a 5niersa* 4et%or( 1b/ect& #reate5noOa*ue,. #reate a 5niersa* 4et%or( 1b/ect a*ue& Dia*o$Libraries Access dia*o$ *ibraries stored in a document& 28ua*5411b/ects,. Determine if t%o 541 ob/ects reference t"e same instance& +indOb%ect67 +ind a named ob%ectE do not use. +ind9ropertyOb%ect67 +ind ob%ect property based on nameE do not use. JetDefau*t#onte3t,. Jet a copy of t"e defau*t conte3t& Jet'rocessSericeMana$er,. Jet serice mana$er& J*oba*Scope App*ication9*ee* *ibraries& Eas5no)nterfaces,. Does an ob/ect support specified interfaces> )s5noStruct,. )s t"is ariab*e a 5niersa* 4et%or( 1b/ect> StarDes(top Specia* ariab*e representin$ t"e des(top ob/ect& T"is#omponent Specia* ariab*e representin$ t"e current document& 1+.1. Base t'pes and structures Most of t"e interna* data used by 11o is based on standard types suc" as strin$s and numbers& T"ese types are combined into structures ,ca**ed structs., %"ic" act *i(e user9defined data types& T"e structures are combined to form more comp*e3 541 ob/ects& A struct supports properties but not met"ods& A structure proides a met"od of p*acin$ more t"an one a*ue into a sin$*e ariab*e& 6ou access t"e a*ues in a structure based on a name t"at is decided %"en t"e struct type is desi$ned by a pro$rammer& A common*y used struct is t"e 'ropertyOa*ue, %"ose primary purpose is to "o*d a strin$ name and a ariant a*ue& T"e fo**o%in$ *istin$ demonstrates creatin$ a 'ropertyOa*ue structure and t"en settin$ t"e name and t"e a*ue& T"e contained properties are accessed by p*acin$ a period bet%een t"e ariab*e and t"e property name& Listing 202. Use #im -s New to create a UNO structure. -i! aProp A# He* co!&#un&#tar&bean#&Propert.Oalue aProp&Ha!e 6 ""ir#tHa!e" )Set t(e Ha!e propert. aProp&Oalue 6 "Paterton" )Set t(e Oalue propert. TIP 11o ob/ects "ae *on$ names suc" as com&sun&star&beans&'ropertyOa*ue7 in t"e te3t ) usua**y abbreiate t"e name and simp*y %rite 'ropertyOa*ue, but your macros must use t"e fu** name& 228 6ou must create ,or obtain. a 541 structure before you can use it& T"e most common met"od to create a 541 structure is to use Dim As 4e% ,see Listin$ 202.& 6ou can a*so use Dim to create an array of structures& Listing 203. Use #im -s New to create an array of UNO structures. -i! aPropB?C A# He* co!&#un&#tar&bean#&Propert.Oalue aPropB7C&Ha!e 6 ""ir#tHa!e" )Set t(e Ha!e propert. aPropB7C&Oalue 6 "Cl.de" )Set t(e Oalue propert. 5se t"e #reate5noStruct function to create a 541 structure %"en it is needed rat"er t"an dec*are it a"ead of time& Dynamica**y creatin$ a 541 structure a**o%s t"e name of t"e structure to be proided at run time rat"er t"an compi*e time& 'roidin$ a name at run time is s"o%n in Listin$ 20! and Listin$ 20M& 'roidin$ a name at compi*e time is s"o%n in Listin$ 202& Listing 204. Use /reateUno*truct to create a UNO structure. -i! aProp aProp 6 Create0noStructB"co!&#un&#tar&bean#&Propert.Oalue"C aProp&Ha!e 6 ""ir#tHa!e" )Set t(e Ha!e propert. aProp&Oalue 6 "Andre*" )Set t(e Oalue propert. T"e ;it" statement simp*ifies t"e process of settin$ t"e properties of a structure& Listing 205. Use 'ith to simplify setting properties on structures. -i! aPropB?C A# He* co!&#un&#tar&bean#&Propert.Oalue Wit( aPropB7C &Ha!e 6 ""ir#tHa!e" )Set t(e Ha!e propert. &Oalue 6 "Paterton" )Set t(e Oalue propert. End Wit( T"e function #reate5noStruct used to be t"e on*y met"od to create a 541 structure& )t is used *ess since t"e introduction of t"e DDim As 4e%F synta3& T"e #reate1b/ect function is a more $enera* function t"an #reate5noStruct& )t is ab*e to create instances of a** types supported by t"e +asic interna* factory mec"anism& T"is inc*udes user9defined types& Listing 206. /reate a user4defined type with /reateOb%ect or #im -s. 3.pe Per#on3.pe "ir#tHa!e A# Strin ,a#tHa!e A# Strin End 3.pe Sub Exa!pleCreateHe*3.pe -i! Per#on A# Per#on3.pe Per#on&"ir#tHa!e 6 "Andre*" Per#on&,a#tHa!e 6 "Piton.a1" PrintPer#onBPer#onC -i! Me A# ObNect Me 6 CreateObNectB"Per#on3.pe"C Me&"ir#tHa!e 6 "And." Me&,a#tHa!e 6 "Piton.a1" PrintPer#onBMeC End Sub Sub PrintPer#onBxC 229 Print "Per#on 6 " 4 x&"ir#tHa!e 4 " " 4 x&,a#tHa!e End Sub TIP 0or a user9defined type, DDim As 4e%F and DDim AsF bot" %or(& 0or a 541 struct, "o%eer, you must use DDim As 4e%F& T"e #reate1b/ect function accepts t"e same ar$uments as #reate5noStruct, but it %or(s for a** supported types, %"ereas #reate5noStruct %or(s on*y for 541 structures& T"erefore, t"ere is no reason to use #reate5noStruct rat"er t"an #reate1b/ect& Listing 207. Use /reateOb%ect to create a UNO structure. -i! aProp aProp 6 CreateObNectB"co!&#un&#tar&bean#&Propert.Oalue"C aProp&Ha!e 6 ""ir#tHa!e" )Set t(e Ha!e propert. aProp&Oalue 6 "Paterton" )Set t(e Oalue propert. TIP #reate1b/ect offers more f*e3ibi*ity t"an #reate5noStruct to dynamica**y create ob/ects based on a name& ) %rote a sma** test pro$ram t"at created 20000 structs& #reate5noStruct and #reate1b/ect too( about t"e same amount of time& 5sin$ Dim As 4e%, "o%eer, used A00 c*oc( tic(s *ess, %"ic" is usefu* if you %ant to ma(e a macro run as fast as possib*e& T"e Type4ame function indicates t"at a 541 structure is an ob/ect& 5se t"e )s5noStruct function to determine if a ariab*e is a 541 structure& Listing 208. Use "sUno*truct to check if an ob%ect is an UNO *truct. -i! aProp A# He* co!&#un&#tar&bean#&Propert.Oalue Print 3.peHa!eBaPropC )ObNect Print I#0noStructBaPropC )3rue 1+.2. )@O interface An interface defines "o% somet"in$ interacts %it" its enironment& A 541 interface resemb*es a $roup of subroutine and function dec*arations7 ar$uments and return types are specified a*on$ %it" functiona*ity& 6ou can use t"e interface to retriee data from an ob/ect, set data in an ob/ect, or te** an ob/ect to do somet"in$& T"e interface indicates "o% an ob/ect can be used, but it says not"in$ about t"e imp*ementation& 0or e3amp*e, if an interface contains t"e met"od JetEei$"t t"at returns an inte$er, itGs natura* to assume t"at t"e ob/ect contains an inte$er property named Eei$"t& )tGs possib*e, "o%eer, t"at t"e "ei$"t is deried or ca*cu*ated from ot"er properties& T"e interface does not specify "o% t"e "ei$"t is obtained, /ust t"at it is aai*ab*e& A 541 structure, "o%eer, contains properties t"at are accessed direct*y7 t"e interna* representation is not "idden& TIP 541 interface names start %it" t"e capita* *etter I& ;"en you %ant to (no% %"at met"ods are supported by an ob/ect, c"ec( t"e interfaces& 541 interface names start %it" t"e capita* *etter I, %"ic" ma(es it easy to reco$niCe an interface7 for e3amp*e, t"e interface com&sun&star&te3t&ITe3tRan$e specifies a section of te3t %it" bot" a start and end position& 1b/ects t"at support t"e ITe3tRan$e interface are a*so used to identify an ob/ectGs position in te3t document& T"e start and end positions may be t"e same& T"e ITe3tRan$e interface defines t"e met"ods in Tab*e @B& 230 Table 89. Methods defined by the com.sun.star.te.t.:e.tRange interface. )et6od Description $etTe3t,. Return t"e com&sun&star&te3t&ITe3t interface t"at contains t"is ITe3tRan$e& $etStart,. Return a com&sun&star&te3t&ITe3tRan$e t"at references on*y t"e start position& $et2nd,. Return a com&sun&star&te3t&ITe3tRan$e t"at references on*y t"e end position& $etStrin$,. Return a strin$ t"at inc*udes t"e te3t inside t"is te3t ran$e& setStrin$,str. Set t"e strin$ for t"is te3t ran$e, rep*acin$ e3istin$ te3t and c*earin$ a** sty*es& TIP A 541 interface may be deried from anot"er& 2ery 541 interface is re8uired to be deried from com&sun&star&uno&I)nterface& A ne% 541 interface may be deried from anot"er& T"is is not somet"in$ t"at you do, but rat"er itGs somet"in$ t"at is done by t"e desi$ner of t"e interface& T"e deried interface supports a** of t"e met"ods defined in t"e interface from %"ic" it is deried& 0or e3amp*e, t"e com&sun&star&te3t&ITe3t#ursor e3tends t"e ITe3tRan$e interface to a**o% it to c"an$e t"e ran$e, %"ic" ma(es sense if you t"in( about %"at you do %it" a cursor& Any ob/ect t"at imp*ements t"e ITe3t#ursor interface, supports t"e met"ods in Tab*e @B and t"e ne% met"ods introduced by t"e ITe3t#ursor interface& T"e main points re$ardin$ interfaces ,so far. are: 1. An interface defines met"ods& )n ot"er %ords, an interface defines %"at an ob/ect can do7 inc*udin$ $ettin$ and settin$ interna* properties& 2. An interface may be deried from anot"er interface& 3. T"e *ast portion of an interface name be$ins %it" an I& )n 541, ob/ects are accessed by t"eir interface& Many of t"e pro$rammin$ *an$ua$es, suc" as Kaa and #NN, force you to perform a *itt*e 541 ma$ic and e3tract t"e correct interface before you can ca** t"e met"ods defined in t"e interface& 11o +asic "ides t"ese detai*s for you so t"at you can direct*y ca** met"ods and access properties direct*y& TIP 11o +asic "ides many of t"e comp*icated detai*s, so, for most t"in$s, it is easier to %rite an 11o +asic pro$ram t"an to %rite a Kaa script& 1+.3. )@O service A serice abstract*y defines an ob/ect by combinin$ interfaces and properties to encapsu*ate some usefu* functiona*ity& A 541 interface defines "o% an ob/ect interacts %it" t"e outside %or*d7 a 541 structure defines a co**ection of data7 and a 541 serice combines t"em to$et"er& Li(e a 541 interface, a 541 serice does not specify t"e imp*ementation& )t on*y specifies "o% to interact %it" t"e ob/ect& A*most eery 541 ob/ect is defined by a serice, so 541 ob/ects are ca**ed serices& Strict*y spea(in$, "o%eer, Da sericeF is t"e ob/ect definition& T"e 541 ob/ect is t"e actua* ob/ect created as defined by t"e serice& A serice may inc*ude mu*tip*e serices and interfaces& An interface usua**y defines a sin$*e aspect of a serice and t"erefore is usua**y sma**er in scope& Many serices "ae a name simi*ar to an interface name7 for e3amp*e, one of t"e interfaces e3ported by t"e Te3t#ursor serice is t"e ITe3t#ursor interface& An interface or property may be dec*ared as optiona* for a 231 serice& T"e I;ord#ursor interface is mar(ed as optiona* for t"e Te3t#ursor serice& T"e imp*ication is t"at not a** te3t cursors support t"e %ord cursor interface& )n practice, you *earn %"ic" te3t cursors support %"ic" interfaces and t"en simp*y t"em& T"ere are t%o typica* met"ods for obtainin$ a serice& Jet a reference to an e3istin$ ob/ect7 for e3amp*e, retriein$ t"e first te3t tab*e in t"e current document& As( a serice factory to create an instance of an ob/ect7 for e3amp*e, if ) %ant to insert a ne% te3t tab*e into a document, ) as( t"e document to $ie me a ne% empty tab*e, %"ic" ) t"en confi$ure and insert into t"e document& A serice factory returns ob/ects based on t"e name& T"e process serice mana$er is t"e main ob/ect factory for 1pen1ffice&or$& T"e factory is $ien t"e serice name, and t"e factory decides %"at to return& A factory may return a brand ne% instance of an ob/ect, or, it may return an e3istin$ instance& 5se Jet'rocessSericeMana$er,. to obtain a reference to t"e process serice mana$er& 5se #reate)nstance to create a serice from t"e process serice mana$er as s"o%n in Listin$ 20B& Listing 209. Use process service manager to create a service. Sub ManaerCreate#ASer:ice -i! :"ileAcce## -i! # A# Strin -i! :Manaer :Manaer 6 JetProce##Ser:iceManaerBC :"ileAcce## 6 :Manaer&CreateIn#tanceB"co!&#un&#tar&ucb&Si!ple"ileAcce##"C # 6 :"ileAcce##&etContent3.peB"(ttp:++***&piton.a1&or+Andre*Macro&odt"C Print # End Sub T"e code in Listin$ 20B obtains t"e process serice mana$er, creates an instance of t"e Simp*e0i*eAccess serice, and t"en uses t"e created serice& T"e #reate5noSerice function is a s"ortcut for creatin$ a 541 serice ,see Listin$ 210.& T"e purpose of Listin$ 210 is to demonstrate t"e #reate5noSerice function, s"o%in$ t"at itGs simp*er t"an creatin$ a serice mana$er& Listin$ 210 a*so demonstrates some usefu* functiona*ity, usin$ a dia*o$ to c"oose a fi*e& Listing 210. *elect a file on disk. "unction C(oo#eA"ileHa!eBC A# Strin -i! :"ile-ialo )"ilePic1er #er:ice in#tance -i! :"ileAcce## )Si!ple"ileAcce## #er:ice in#tance -i! iAccept a# Inteer )Re#pon#e to t(e "ilePic1er -i! #InitPat( a# Strin )Hold t(e initial pat( )Hote: 3(e $ollo*in #er:ice# M0S3 be called in t(e $ollo*in order )or Ba#ic *ill not re!o:e t(e "ile-ialo Ser:ice :"ile-ialo 6 Create0noSer:iceB"co!&#un&#tar&ui&dialo#&"ilePic1er"C :"ileAcce## 6 Create0noSer:iceB"co!&#un&#tar&ucb&Si!ple"ileAcce##"C )Set t(e initial pat( (ereK #InitPat( 6 Con:ert3o0rlBCur-irC I$ :"ileAcce##&Exi#t#B#InitPat(C 3(en :"ile-ialo&Set-i#pla.-irector.B#InitPat(C End I$
iAccept 6 :"ile-ialo&ExecuteBC )Run t(e $ile c(oo#er dialo 232 I$ iAccept 6 > 3(en )W(at *a# t(e return :alueU C(oo#eA"ileHa!e 6 :"ile-ialo&"ile#B7C )Set $ile na!e i$ it *a# not canceled End I$ :"ile-ialo&-i#po#eBC )-i#po#e o$ t(e dialo End "unction A directory can be c"osen simi*ar*y& Listing 211. *elect a directory. REM #InPat( #peci$ie# t(e initial director.& I$ t(e initial director. REM i# not #peci$ied= t(en t(e u#er)# de$ault *or1 director. i# u#ed& REM 3(e #elected director. i# returned a# a 0R,& "unction C(oo#eA-irector.BOptional #InPat(FC A# Strin -i! o-ialo A# ObNect -i! oS"A A# ObNect -i! # A# Strin -i! oPat(Settin# o-ialo 6 Create0noSer:iceB"co!&#un&#tar&ui&dialo#&"olderPic1er"C )o-ialo 6 Create0noSer:iceB"co!&#un&#tar&ui&dialo#&O$$ice"olderPic1er"C oS"A 6 create0noSer:iceB"co!&#un&#tar&ucb&Si!ple"ileAcce##"C
I$ o-ialo&ExecuteBC 6 > 3(en C(oo#eA-irector.BC 6 o-ialo&et-irector.BC End I$ End "unction TIP T"e fi*e pic(er and fo*der pic(er dia*o$s can use eit"er t"e operatin$ system supp*ied defau*t dia*o$s, or 11o specific dia*o$s& T"e operatin$ system specific dia*o$s proide *ess functiona*ity7 for e3amp*e, you cannot set t"e initia* disp*ayed directory& 5se Tools > Options > OpenOffice.org > #eneral and p*acea c"ec( ne3t to Z5se 1pen1ffice&or$ dia*o$sZ& T"e code in Listin$ 210 creates t%o 541 serices by usin$ t"e function #reate5noSerice& T"ere are times, "o%eer, %"en t"e serice mana$er is re8uired& 0or e3amp*e, t"e serice mana$er "as met"ods to create a serice %it" ar$uments, #reate)nstance;it"Ar$uments, and to obtain a *ist of a** supported serices, $etAai*ab*eSerice4ames,.& T"e code in Listin$ 212 obtains a *ist of t"e supported serice names7 t"ere are 1003 serices on my computer usin$ 11o ersion 3&2&17 up from A62 %it" 11o ersion 1& Listing 212. *ervice manager supports services. Sub Ho*Man.Ser:ice#Supported -i! o-oc ) -ocu!ent created to (old t(e $ilter na!e#& -i! o3ext ) -ocu!ent text obNect& -i! oS- ) Sort-e#criptor created $or t(e docu!ent& 233 -i! oCur#or ) 3ext cur#or u#ed $or #ortin& -i! iG ) Index Oariable& -i! #Ser:ice# #Ser:ice# 6 JetProce##Ser:iceManaerBC&etA:ailableSer:iceHa!e#BC Print "Ser:ice !anaer #upport# "\0BoundB#Ser:ice#C\" #er:ice#" ) Create a Writer docu!ent& o-oc 6 Star-e#1top&loadCo!ponent"ro!0R,B "pri:ate:$actor.+#*riter"= "5blan1"= 7= Arra.BC C o3ext 6 o-oc&et3extBC
) Print t(e $ilter na!e# into a Writer docu!ent& "or i 6 ,BoundB #Ser:ice# C 3o 0BoundB #Ser:ice# C o3ext&in#ertStrinB o3ext&etEndBC= #Ser:ice#BiC= "al#e C ) -o not in#ert a blan1 line at t(e end& o3ext&in#ertControlC(aracterB o3ext&etEndBC= 5 co!&#un&#tar&text&ControlC(aracter&PARAJRAPH5BREA^= "al#e C Hext
o3ext&in#ertStrinB o3ext&etStartBC= 5 "Ser:ice !anaer #upport# "40BoundB#Ser:ice#C4" #er:ice#"= "al#e C End Sub )t is usefu* to *oo( at t"e *ist of supported serices& T"is proides insi$"t into aai*ab*e functiona*ity t"at you can e3p*ore& 1+.4. Conte:t A conte3t is a co**ection of name9a*ue pairs& 11o maintains a defau*t conte3t t"at is aai*ab*e %it" t"e function JetDefau*t#onte3t& A*t"ou$" a conte3t is re8uired %"en a serice is created, 11o +asic automatica**y uses t"e defau*t conte3t %"en ca**in$ #reate5noSerice7 yet anot"er reason %"y 11o +asic is easier to use t"an ot"er *an$ua$es& Listing 213. 3iew conte.t element names. M#Box MoinBJet-e$aultContextBC&etEle!entHa!e#BC= CHRFB>7CC 1+.. !nspecting )niversal @etwor* ObGects ;"i*e %ritin$ an 11o +asic macro, ) donGt a*%ays understand t"e a*ues returned from interna* 11o functions L for e3amp*e, inspectin$ t"e a*ue returned by JetDefau*t#onte3t& ) %rite test code to e3amine t"e return a*ues so t"at ) can ma(e appropriate decisions& ) t"en fre8uent*y add more test code to furt"er inspect t"e returned ob/ect& T"e initia* inspection uses routines t"at you probab*y (no% ,see Tab*e B0.& Table 90. "nitial inspection routines. &otine Comment )sMissin$,ob/. 5se t"is for optiona* ar$uments to see if t"ey are missin$& )s4u**,ob/. 6ou cannot inspect a nu** ob/ect, but you (no% t"at it is nu**& 234 &otine Comment )s2mpty,ob/. 6ou cannot inspect an empty ob/ect, but you (no% t"at it is empty& )sArray,ob/. 5se array9inspection met"ods to *earn more about t"e array& Type4ame,ob/. Determine if t"is is a simp*e type suc" as a Strin$ or an )nte$er& )f t"is is an 1b/ect, it is probab*y a 541 structure or a 541 serice& )s5noStruct,ob/. Determine if t"is is a 541 structure& T"e code in Listin$ 21! demonstrates an initia* use of t"e functions in Tab*e B0& Listing 214. "nspect the e.tables ob%ect on the current document. -i! : : 6 3(i#co!ponent&et3ext3able#BC Print I#ObNectB:C )3rue Print I#HullB:C )"al#e Print I#E!pt.B:C )"al#e Print I#Arra.B:C )"al#e Print I#0noStructB:C )"al#e Print 3.peHa!eB:C )ObNect M#Box :&db5!et(od# )3(i# propert. i# di#cu##ed later )f t"e returned ob/ect "as a type name of 1b/ect and it isnGt a 541 structure, it is probab*y a 541 serice& 5se t"e Eas5no)nterfaces function to determine if a 541 ob/ect supports a set of interfaces& T"e first ar$ument is t"e ob/ect to test& T"e ar$uments fo**o%in$ t"e first are a *ist of interface names& )f a** of t"e *isted interfaces are supported, t"e function returns True, ot"er%ise it returns 0a*se& More t"an one interface may be c"ec(ed at t"e same time& Ha#0noInter$ace#BobN= inter$ace>C Ha#0noInter$ace#BobN= inter$ace>X= inter$ace'X= inter$ace%X= &&&YYYC To distin$uis" bet%een a 541 structure, an arbitrary ob/ect, and a 541 serice, first c"ec( to see if t"e ariab*e is an ob/ect& T"is is easi*y done usin$ t"e Type4ame function& )f t"e Type4ame contains t"e %ord 1b/ect, t"en you (no% itGs an ob/ect of some sort& T"e ne3t step is to see if t"e ob/ect is a 541 structure, by usin$ t"e function )s5noStruct& 0ina**y, if t"e ob/ect supports an interface ,any interface %i** do., you (no% itGs a 541 serice& 2ery interface is deried from com&sun&star&uno&I)nterface, so it suffices to see if t"e ob/ect supports t"e I)nterface interface& T"e code in Listin$ 21A uses t"e 11o +asic ariab*e T"is#omponent, %"ic" represents t"e current document& Listing 215. Use &asUno"nterfaces and "sUno*truct to determine the UNO type. -i! aProp A# He* co!&#un&#tar&bean#&Propert.Oalue Print I#0noStructBaPropC )3rue Print Ha#0noInter$ace#BaProp= "co!&#un&#tar&uno&/Inter$ace"C )"al#e Print I#0noStructB3(i#Co!ponentC )"al#e Print Ha#0noInter$ace#B3(i#Co!ponent= "co!&#un&#tar&uno&/Inter$ace"C )3rue TIP )f t"e first ar$ument to t"e function Eas5no)nterfaces is not an ob/ect, a run9time error occurs& T"e ob/ect may be nu**, but it must be an ob/ect& )f t"e ar$ument is a ariant, it must contain an ob/ect7 it cannot be empty& Most 541 serices a*so support t"e com&sun&star&*an$&ISerice)nfo interface, %"ic" a**o%s you to as( t"e ob/ect %"at serices it supports ,see Tab*e B1.& 235 Table 91. :*ervice"nfo methods. )et6od Description $et)mp*ementation4ame,. Returns a strin$ t"at uni8ue*y identifies t"e imp*ementation of t"e serice& 0or e3amp*e, S%ITe3tDocument is t"e name of a ;riter te3t document& $etSupportedSerice4ames,. Return a strin$ array of serices t"at t"e ob/ect supports& supportsSerice,serice4ame. Return True if t"e ob/ect supports t"e serice name& 11o supports different types of documents, suc" as ;riter ,%ord processin$. and #a*c ,spreads"eet.& 2ac" document type supports at *east one serice t"at is supported on*y by t"at document type ,see Tab*e B2.& 6ou can determine t"e document type by c"ec(in$ if it supports one of t"ese serices& 6ou can a*so use t"e met"od $et)mp*ementation4ame,., as s"o%n in Tab*e B1& T"e code in Listin$ 216 demonstrates "o% to erify t"at a ariab*e references a ;riter document& )f t"e ar$ument Doc does not support t"e ISerice)nfo interface, "o%eer, a run9time error occurs because t"e SupportsSerice met"od is not imp*emented& 5se appropriate error "and*in$ if t"is is re8uired, as s"o%n in Listin$ 21M7 t"is is used in Listin$ 222& )f t"e ar$ument is missin$, t"e current document is used& )f an error occurs or a reco$niCed serice is not supported, t"e te3t Dun(no%nF is returned& Table 92. Uni8ue service names based on document type. Docment Type Service Dra%in$ com&sun&star&dra%in$&Dra%Document ;riter com&sun&star&te3t&Te3tDocument ;riter ETML com&sun&star&te3t&;ebDocument #a*c com&sun&star&s"eet&Spreads"eetDocument Mat" com&sun&star&formu*a&0ormu*a'roperties 'resentation com&sun&star&presentation&'resentationDocument +ase com&sun&star&sdb&1fficeDatabaseDocument +ase Tab*e com&sun&star&sdb&DataSource+ro%ser +asic )D2 com&sun&star&script&+asic)D2 Listing 216. 3erify that the document is a 'riter document. Sub -oSo!et(in3oWrite-ocu!entB:-ocC I$ HO3 :-oc&#upport#Ser:iceB"co!&#un&#tar&text&3ext-ocu!ent"C 3(en M#Box "A Writer docu!ent i# re;uired"= ?Q= "Error" Exit Sub End I$ REM re#t o$ t(e #ubroutine #tart# (ere End Sub Listing 217. #etermine a documentPs type. "unction et-oc3.peBOptional :-ocC A# Strin On Error Jo3o Oop# I$ I#Mi##inB:-ocC 3(en :-oc 6 3(i#Co!ponent I$ :-oc&Support#Ser:iceB"co!&#un&#tar&#(eet&Spread#(eet-ocu!ent"C 3(en et-oc3.pe 6 "calc" 236 El#eI$ :-oc&Support#Ser:iceB"co!&#un&#tar&text&3ext-ocu!ent"C 3(en et-oc3.pe 6 "*riter" El#eI$ :-oc&Support#Ser:iceB"co!&#un&#tar&dra*in&-ra*in-ocu!ent"C 3(en et-oc3.pe 6 "dra*" El#eI$ :-oc&Support#Ser:iceB5 "co!&#un&#tar&pre#entation&Pre#entation-ocu!ent#"C 3(en et-oc3.pe 6 "pre#entation" El#eI$ :-oc&Support#Ser:iceB"co!&#un&#tar&$or!ula&"or!ulaPropertie#"C 3(en et-oc3.pe 6 "!at(" El#eI$ :-oc&Support#Ser:iceB"co!&#un&#tar&#db&O$$ice-ataba#e-ocu!ent"C 3(en et-oc3.pe 6 "ba#e" El#e et-oc3.pe 6 "un1no*n" End I$ Oop#: I$ Err ED 7 3(en et-oc3.pe 6 "un1no*n" On Error Jo3o 7 )3urn o$$ error (andlin A"3ER c(ec1in $or an error End "unction Some document types cannot be easi*y distin$uis"ed7 for e3amp*e, an I0orms document and a Master document bot" support t"e same serices as a re$u*ar te3t document& A** of t"e ;rite based documents support t"e serice com&sun&star&te3t&JenericTe3tDocument, and a** of t"e office type documents support t"e serice com&sun&star&document&1fficeDocument& ;"en ) %ant to (no% about an interface or serice, t"e first p*ace t"at ) *oo( is on*ine for t"e officia* documentation& 5nfortunate*y, on*y a partia* picture is easi*y produced ,for t"e Te3t#ursor serice, see "ttp:--api&openoffice&or$-docs-common-ref-com-sun-star-te3t-Te3t#ursor&"tm*.& T"ere are some issues: 1. T"e documentation does not present a unified picture, you must fo**o% many *in(s to determine %"at t"e ob/ect can do& A** supported and optiona* interfaces are *isted, but you must inspect eac" interface to (no% %"at eac" one does& 2. 2ac" interface "as its o%n pa$e& )f an interface is deried from anot"er, you must *oo( at anot"er pa$e to see t"e definition of t"e parent interface& 3. 6ou donGt (no% if t"e optiona* items are supported for a specific ob/ect instance %it"out inspectin$ t"e ob/ect& TIP 5se Joo$*e to searc" for Dsite:api&openoffice&or$ Te3t#ursorF to 8uic(*y find t"e documentation for t"e Te3t#ursor serice& TIP "ttp:--api&openoffice&or$-docs-common-ref-com-sun-star-te3t-modu*e9i3&"tm* *ists a** of t"e serices and interfaces at t"e com&sun&star&te3t *ee*& Most 541 serices contain t"e properties db$=properties, db$=met"ods, and db$=supported)nterfaces& 2ac" of t"ese properties is a strin$ t"at contains a *ist of t"e supported properties, met"ods, or supported interfaces& 2ac" strin$ starts %it" te3t simi*ar to D'roperties of 1b/ect ZT"is#omponentZ:F& T"e indiidua* items are separated by t"e de*imiter as s"o%n in Tab*e B3& Sometimes t"ere are e3tra spaces fo**o%in$ t"e de*imiter and sometimes t"ere are e3tra ne%9*ine c"aracters L #ERY,10.& 237 Table 93. UNO >dbgQA properties. Property Delimiter Description db$=properties D7F A** properties supported by t"e ob/ect& db$=met"ods D7F A** met"ods supported by t"e ob/ect& db$=supported)nterfaces #"rY,10. A** interfaces supported by t"e ob/ect& T"e code in Listin$ 21@ proides an easy met"od to see %"at an ob/ect supports& Sometimes, "o%eer, too many items are disp*ayed and portions of t"e dia*o$ do not fit on t"e screen& To aoid t"is prob*em, t"e code in Listin$ 21B sp*its t"e *ist into sma**er, easi*y mana$ed c"un(s& 0i$ure M3 is on*y one of t"e many dia*o$s t"at are disp*ayed by t"e macro in Listin$ 21B& +e %arned, t"e dia*o$s %i** not fit on t"e screen, so, /ust press enter to c*ose eac" dia*o$& Listing 218. he >dbgQA properties return useful information. M#Box :ObN&db5propertie# M#Box :ObN&db5!et(od# M#Box :ObN&db5#upportedInter$ace# Listing 219. #isplay information from one of the debug properties. Sub Exa!ple-i#pla.-bIn$oStrBC -i! :ObN :ObN 6 3(i#Co!ponent -i#pla.-bIn$oStrB:ObN&db5propertie#= "\"= ?7= "Propertie#"C -i#pla.-bIn$oStrB:ObN&db5!et(od#= "\"= ?7= "Met(od#"C -i#pla.-bIn$oStrB:ObN&db5#upportedInter$ace#= CHRFB>7C= ?7= "Inter$ace#"C End Sub Sub -i#pla.-bIn$oStrB#In$oF= #SepF= nC(un1#= #HeadinFC -i! aIn$oBC )Arra. to (old eac( #trin -i! i A# Inteer )Index :ariable -i! N A# Inteer )Mun1 inteer :ariable $or te!porar. :alue# -i! # A# Strin )(old# t(e portion t(at i# not co!pleted # 6 #In$oF N 6 InStrB#= ":"C )Initial colon I$ N D 7 3(en MidB#= >= N= ""C )Re!o:e portion up to t(e initial colon -o aIn$oBC 6 SplitB#= #SepF= nC(un1#C )Split #trin ba#ed on deli!iter& # 6 aIn$oB0BoundBaIn$oBCCC )Jrab t(e la#t piece& Contain# I$ InStrB#= #SepFC E > 3(en )t(e re#t i$ t(ere *ere too !an.& # 6 "" )I$ t(ere *ere not= t(en clear #& El#e )I$ t(ere *a# a deli!iter t(en Re-i! Pre#er:e aIn$oBnC(un1# 9 'C )c(ane arra. di!en#ion to End I$ )re!o:e t(e extra la#t piece& "or i 6 ,BoundBaIn$oBCC 3o 0BoundBaIn$oBCC),oo1 at eac( piece to re!o:e aIn$oBiC 6 3ri!BaIn$oBiCC )leadin and trailin #pace#& N 6 InStrBaIn$oBiC= CHRFB>7CC )So!e (a:e an extra I$ N D 7 3(en MidBaIn$oBiC= N= >= ""C )ne* line t(at #(ould be re!o:ed& Hext M#Box MoinBaIn$oBC= CHRFB>7CC= 7= #HeadinF ,oop 0ntil ,enB#C 6 7 238 End Sub ;"en a type is inc*uded in one of t"e Ddb$=F properties, it is preceded by t"e te3t DSb3F, as s"o%n in 0i$ure M3& T"ese names startin$ %it" Sb3 correspond to t"e interna* names used by 11o +asic& TIP A comp*ete ob/ect bro%ser is presented *ater t"at demonstrates a** of t"ese concepts&>> TIP A popu*ar ob/ect bro%ser, ca**ed Iray described at t"e fo**o%in$ *in(: "ttp:--%i(i&serices&openoffice&or$-%i(i-23tensions=dee*opment=basic Figure 73. - few properties in a 'riter documentE one dialog of many displayed. 1+.#. )se ObGect or -ariant )t is a*most a*%ays safe to use 1b/ect ariab*es to "o*d 541 serices& )t is so safe, apparent*y, t"at een t"e macro recorder uses 1b/ect ariab*es to "o*d 541 serices& 5nfortunate*y, it is not a*%ays safe& T"e 11o Dee*operGs Juide specifica**y states t"at Oariant ariab*es s"ou*d be used instead of 1b/ect ariab*es& A*%ays use t"e type Oariant to dec*are ariab*es for 541 serices, not t"e type 1b/ect& T"e 11o +asic type 1b/ect is tai*ored for pure 11o +asic ob/ects L in ot"er %ords, ob/ects t"at can be created %it" t"e Dim As 4e% synta3& T"e Oariant ariab*es are best for 541 serices to aoid prob*ems t"at can resu*t from t"e 11o +asic specific be"aior of t"e type 1b/ect& ) as(ed Andreas +re$as ,one of t"e primary dee*opers for t"e 11o +asic infrastructure. about t"is, and "e said t"at in most cases, bot" %or(& T"e 11o Dee*operGs Juide prefers Oariant because t"ere are some odd situations in %"ic" t"e usa$e of type 1b/ect *eads to an error due 239 to t"e o*d +asic 1b/ect type semantics& +ut if a +asic pro$ram uses type 1b/ect, it %i** a*most a*%ays run correct*y and t"ere s"ou*d be no prob*ems& )t is sufficient*y rare, "o%eer, t"at "e cou*d not remember an e3amp*e %"ere it %as a prob*em& 1n t"e ot"er "and, %it" 11o ersion 1, ) e3perienced a prob*em t"at corrected itse*f, %"en ) c"an$ed t"e ariab*e type from Oariant to 1b/ect& 1+.$. Comparing )@O variables 5se t"e 28ua*5no1b/ects function to determine if t%o 541 ob/ects are t"e same ob/ect& 541 structures are copied by a*ue but 541 serices are copied by reference& T"is means t"at 28ua*5no1b/ects s"ou*d a*%ays return 0a*se for t%o ariab*es t"at contain a structure, and it mi$"t return True for 541 serices& -i! :ObN :ObN 6 3(i#Co!ponent Print E;ual0noObNect#B:ObN= 3(i#Co!ponentC )3rue
-i! aProp A# He* co!&#un&#tar&bean#&Propert.Oalue :ObN 6 aProp Print E;ual0noObNect#B:ObN= aPropC )"al#e After usin$ 11o for many years, ) fina**y found a use for 28ua*5no1b/ects& +e %arned t"at t"is is an adance topics and ma(es use of constructs not %ide*y (no%n& T"e prob*em as posed is: D;"en a button is pressed in a #a*c document, ) %ant to (no% %"ic" ce** contains t"e button&F Eere are some bits of information to "e*p understand t"e prob*em: 2ac" document "as at *east one Ddra% pa$eF t"at contains $rap"ica* t"in$s suc" as ima$es imbedded in t"e document& 6ou can embed contro*s suc" as a button in a document& ;"en t"e button is pressed, and a macro is ca**ed, it is triia* to $et a reference to t"e contro* Ddata mode*F& 2ac" contro* "as a s"ape embedded in t"e dra% pa$e& 2ac" contro* a*so "as a Ddata mode*F t"at contains properties and ot"er simi*ar t"in$s& 0rom a contro* data mode* ) cannot easi*y obtain t"e s"ape or t"e ce** containin$ t"e contro*& 0rom a s"ape in a #a*c document, ) can easi*y find t"e ce** H if t"e contro* is anc"ored to a ce**& My so*ution %as to find t"e s"ape associated %it" a contro*& )t is easy to find t"e contro* name, but, a contro* name need not be uni8ue& ) opted to *oo( at eery s"ape on t"e dra% pa$e and t"en c"ec( to see if t"e contro* associated %it" t"at s"ape is t"e same ob/ect as t"e contro* in 8uestion& Listing 220. +ind the control shape for a specific control. "unction "indCellWit(ControlBo-ra*Pae= oControlC -i! oS(ape -i! oAnc(or oS(ape 6 "indS(ape"orControlBo-ra*Pae= oControlC I$ Hot I#E!pt.BoS(apeC 3(en I$ oS(ape&etAnc(orBC&#upport#Ser:iceB"co!&#un&#tar&#(eet&S(eetCell"C 3(en "indCellWit(Control 6 oS(ape&etAnc(orBC End I$ End I$ End "unction "unction "indS(ape"orControlBo-ra*Pae= oControlC 240 -i! i -i! oS(ape "or i 6 7 3o o-ra*Pae&etCountBC oS(ape 6 o-ra*Pae&etB.IndexBiC I$ oS(ape&#upport#Ser:iceB"co!&#un&#tar&dra*in&ControlS(ape"C 3(en I$ E;ual0HOObNect#BoControl= oS(ape&ControlC 3(en "indS(ape"orControl 6 oS(ape Exit "unction End I$ End I$ Hext End "unction ;"at does t"e eent "and*er ca**ed by t"e button *oo( *i(e> Sub ButtonHandlerBoE:entC -i! oControlModel -i! oParent -i! oCell
oCell 6 "indCellWit(ControlBoParent&etCurrentControllerBC&etActi:eS(eetBC&et-ra*PaeBC= oControlModelC I$ HO3 I#E!pt.BoCellC 3(en Print "Control i# in cell " 4 oCell&Ab#oluteHa!e El#e Print "0nable to $ind cell *it( control" EHd I$ End Sub 1+.&. Built9in global )@O variables 11o +asic contains bui*t9in $*oba* ariab*es t"at proide 8uic( access to fre8uent*y used components in 11o& T"e most common*y used ariab*e is T"is#omponent, %"ic" refers to t"e current*y actie document& To demonstrate usin$ t"e ariab*e T"is#omponent, t"e macro in Listin$ 221 disp*ays a** of t"e sty*es in t"e current document& 0i$ure M! is on*y one of t"e many dia*o$s t"at are disp*ayed %"i*e t"e macro runs& T"e fact t"at a sty*e e3ists in a document does not imp*y t"at t"e sty*e is actua**y used in t"e document& Listing 221. #isplay all styles known by this document. Sub -i#pla.AllSt.le# -i! :"a!ilie# A# Oariant )All t(e #t.le t.pe# -i! :"a!Ha!e# A# Oariant )Arra. *it( na!e# o$ t(e #t.le t.pe# -i! :St.le# A# Oariant )One #t.le t.pe #uc( a# Hu!ber or Pae St.le# -i! :StlHa!e# A# Oariant )Arra. *it( na!e# o$ #peci$ic #t.le# -i! # A# Strin )Me##ae to di#pla. -i! n A# Inteer )Iterate t(rou( t(e #t.le t.pe# -i! i A# Inteer )Iterate t(rou( t(e #t.le# 241
:"a!ilie# 6 3(i#Co!ponent&St.le"a!ilie# )Jet t(e #t.le# :"a!Ha!e# 6 :"a!ilie#&etEle!entHa!e#BC )W(at t.pe o$ #t.le#U "or n 6 ,BoundB:"a!Ha!e#C 3o 0BoundB:"a!Ha!e#C ),oo1 at all #t.le t.pe# # 6 "" :St.le# 6 :"a!ilie#&etB.Ha!eB:"a!Ha!e#BnCC )Jet #t.le# o$ a t.pe :StlHa!e# 6 :St.le#&etEle!entHa!e#BC )na!e# o$ #t.le# $or t.pe "or i 6 ,BoundB:StlHa!e#C 3o 0Bound B:StlHa!e#C )$or all #t.le# o$ a t.pe #6# 4 i 4 " : " 4 :StlHa!e#BiC 4 C(rFB>%C )Build a di#pla. #trin I$ BBi W >C Mod %< 6 7C 3(en )-i#pla. %< at a ti!e M#Box #=7=:"a!Ha!e#BnC )-i#pla. t(e! # 6 "" )Clear #trin= #tart o:er End I$ Hext i )Hext #t.le I$ ,enB#C D 7 3(en M#Box #=7=:"a!Ha!e#BnC ),e$to:er #t.le# $or t.pe Hext n )Hext #t.le t.pe End Sub Figure 74. +rame styles known by the current document. 1pen1ffice is based on t"e same code as Star1ffice, %"ic" "ad a des(top& A** of t"e indiidua* %indo%s %ere contained in t"is des(top& T"e des(top paradi$m is no% $one, but for *e$acy reasons a des(top ob/ect sti** acts as t"e $*oba* app*ication t"at ties a** of t"e documents to$et"er& A*t"ou$" ) fre8uent*y see code t"at creates a des(top serice by usin$ t"e function #reate5noSerice, t"is is not re8uired in 11o +asic& 11o +asic proides t"e ariab*e StarDes(top, %"ic" accesses t"e primary des(top serice in 11o& T"e macro in Listin$ 222 demonstrates t"e use of t"e StarDes(top by traersin$ a** of t"e current*y open documents& T"e $etDocType met"od is defined in Listin$ 21M& Listing 222. "nspect each open component. Sub Iterate3(rou(All-oc# On Error Re#u!e Hext )Inore t(e non9docu!ent co!ponent# -i! :Co!ponent# A# ObNect )All o$ t(e co!ponent# -i! :-oc# A# ObNect )Enu!eration o$ t(e docu!ent# -i! :-oc A# ObNect )A #inle docu!ent -i! # A# Strin JlobalScope&Ba#ic,ibrarie#&,oad,ibrar.B"3ool#"C)Contain# "ileHa!eOutO$Pat( :Co!ponent# 6 Star-e#1top&etCo!ponent#BC )Jet all t(e co!ponent# :-oc# 6 :Co!ponent#&createEnu!erationBC )Enu!erate t(e! 242 -o W(ile :-oc#&(a#MoreEle!ent#BC )W(ile t(ere are !ore :-oc 6 :-oc#&nextEle!entBC )Jet t(e next co!ponent # 6 # 4 et-oc3.peB:-ocC 4 " " )Add t(e docu!ent t.pe # 6 # 4 "ileHa!eOutO$Pat(B:-oc&et0R,BCC )Add t(e $ile na!e # 6 # 4 CHRFB>7C )Add a ne* line ,oop M#Box #= 7= "Currentl. Open Co!ponent#" End Sub TIP T"e primary isib*e %indo%s in 11o are ca**ed Dcomponents&F 2ery open document is a component, as is t"e +asic )D2 and t"e Ee*p %indo%& )n 11o, t"e %ord DcomponentF a*most a*%ays means an open document& ;"i*e iteratin$ t"rou$" t"e open documents ,components., you may find some une3pected documents& T"ese are component %indo%s suc" as t"e +asic )D2 and t"e Ee*p %indo%& T"e macro in Listin$ 222 uses t"e function 0i*e4ame1ut1f'at"& T"is is anot"er macro and is not a function t"at is bui*t into 11o +asic& T"is function is stored in t"e Strin$s modu*e of t"e app*ication9*ee* Too*s *ibrary& )f a *ibrary is not current*y *oaded, you cannot ca** t"e met"ods t"at it contains& T"e J*oba*Scope ariab*e references t"e app*ication9*ee* *ibraries and is used to *oad t"e Too*s *ibrary& Loadin$ a *ibrary *oads a** of t"e modu*es in t"e specified *ibrary& 11o contains *ibraries and modu*es t"at are not bui*t into 11o +asic& 5se t"e LoadLibrary met"od before you use t"e routines in t"e *ibraries& JlobalScope&Ba#ic,ibrarie#&,oad,ibrar.B"3ool#"C To access t"e +asic *ibraries in t"e current document, eit"er use t"e +asicLibraries $*oba* ariab*e or access t"e +asicLibraries property in t"e current document& Print E;ual0noObNect#B:ObN&Ba#ic,ibrarie#= Ba#ic,ibrarie#C )3rue 5se t"e Dia*o$Libraries ariab*e to access t"e dia*o$ *ibraries in t"e current document& 5n*i(e +asicLibraries, an indiidua* document does not contain a property ca**ed Dia*o$Libaries to direct*y obtain t"e dia*o$ *ibraries for a specific document& 6ou can easi*y obtain t"e dia*o$ and +asic *ibraries for a specific document t"rou$" a *ess direct route& 2ac" document "as a Library#ontainer property& 3(i#Co!ponent&,ibrar.Container&etB.Ha!eB"OOME5%7"C&etModuleContainerBC 3(i#Co!ponent&,ibrar.Container&etB.Ha!eB"OOME5%7"C&et-ialoContainerBC T"e $et+y4ame,. met"od on t"e Library#ontainer returns t"e named *ibrary& T"e $etModu*e#ontainer,. met"od returns t"e +asic container for t"e specified *ibrary, and t"e $etDia*o$#ontainer,. met"od returns t"e Dia*o$ container for t"e specified *ibrary& T"e code in Listin$ 223, "o%eer, uses t"e ariab*es Dia*o$Libraries and +asicLibraries to *ist t"e number of dia*o$s and modu*es in eac" *ibrary in t"e current document& 0i$ure MA s"o%s t"e resu*ts& Listing 223. 3iew the libraries and dialogs stored in the current document. Sub Exa!ine-ocu!ent,ibrarie# -i! :,ib# )Hold t(e librar. na!e# -i! :Mod )Hold t(e !odule#+dialo# obNect -i! nHu!Mod#G )Hu!ber o$ !odule# or dialo# in a librar. -i! iG )Scrap index :ariable -i! #F )Scrap #trin :ariable # 6 "*** -ialo ,ib# In -ocu!ent" 4 CHRFB>7C )Initiali8e # :,ib# 6 -ialo,ibrarie#&etEle!entHa!e#BC ),ibrar. na!e# "or i 6 ,BoundB:,ib#C 3o 0BoundB:,ib#C ),oo1 at eac( na!e :Mod 6 -ialo,ibrarie#&etB.Ha!eB:,ib#BiCC )Jet t(e dialo librar. 243 nHu!Mod# 6 0BoundB:Mod&etEle!entHa!e#BCC W > )Ho* !an. dialo# # 6 # 4 :,ib#BiC 4 " (a# " 4 nHu!Mod# 4 " dialo#" )Build #trin # 6 # 4 CHRFB>7C Hext i # 6 # 4 CHRFB>7C # 6 # 4 "*** Ba#ic ,ib# In -ocu!ent" 4 CHRFB>7C )Read. $or code lib# :,ib# 6 Ba#ic,ibrarie#&etEle!entHa!e#BC ),ibrar. na!e# "or i 6 ,BoundB:,ib#C 3o 0BoundB:,ib#C ),oo1 at eac( na!e :Mod 6 Ba#ic,ibrarie#&etB.Ha!eB:,ib#BiCC )Jet t(e code librar. nHu!Mod# 6 0BoundB:Mod&etEle!entHa!e#BCC W > )Hu!ber o$ !odule# # 6 # 4 :,ib#BiC 4 " (a# " 4 nHu!Mod# 4 " !odule#" )Build t(e #trin # 6 # 4 CHRFB>7C Hext i M#Box #= 7= ",ibrarie#" End Sub Figure 75. #ialog and !asic libraries in the current document. To ie% t"e *ibraries in t"e app*ication9*ee* *ibrary container, modify t"e code in Listin$ 223& Add J*oba*Scope before eac" occurrence of +asicLibraries and Dia*o$Libraries& T"is c"an$e "as a*ready been made in t"e 23amineJ*oba*Libraries routine in t"e 541 modu*e in t"is c"apterGs source code fi*es& 1+.(. Creating )@O values for OOo internals 11o +asic does an e3ce**ent /ob of conertin$ bet%een t"e natie +asic types and t"e types re8uired interna**y by 11o& Eo%eer, if you ca** a met"od on a 5niersa* 4et%or( 1b/ect and 11o +asic doesnGt (no% %"at t"e type s"ou*d be, it may not proper*y conert t"e type& 0or e3amp*e, t"e set'ropertyOa*ue met"od in t"e I'ropertySet interface accepts t%o ar$uments L a strin$ name of t"e property to set and t"e a*ue to set& T"e type of t"e a*ue to set depends on %"ic" property is set& 5se t"e function #reate5noOa*ue ,s"o%n in Listin$ 22!. to create a reference to a 5niersa* 4et%or( 1b/ect t"at contains t"e appropriate type if t"ere is a prob*em creatin$ t"e correct type& ) "ae neer seen t"is "appen, so donGt fret t"at muc" about your ar$uments7 you can a*most a*%ays trust 11o +asic to do t"e correct t"in$& Listing 224. Use /reateUno3alue to create a reference to an internal UNO value. -i! : : 6 Create0noOalueB"un#ined lon"= >7C : 6 Create0noOalueB"#trin"= "(ello"C : 6 Create0noOalueB"b.te"= >7C )A b.te i# $ro! 7 t(rou( '<< : 6 Create0noOalueB"XYb.te"= Arra.B%= '= >CC )Pou can e:en create arra.# ): 6 Create0noOalueB"B.te"= >7C )Ho #uc( ele!ent exception ): 6 Create0noOalueB"b.te"= >777C )Out o$ rane exception 244 ): 6 Create0noOalueB"uintA?"= >7C )Ho #uc( ele!ent exception T"e first ar$ument to #reate5noOa*ue is t"e data type t"at s"ou*d be created& T"e supported data types are oid, c"ar, boo*ean, byte, s"ort, unsi$ned s"ort, *on$, unsi$ned *on$, "yper, unsi$ned "yper, f*oat, doub*e, strin$, type, and any& T"e names are case sensitie and may be preceded by s8uare brac(ets to indicate an array& T"e a*ue returned by #reate541Oa*ue is not usab*e by 11o +asic7 it is on*y usefu* to t"e interna*s of 11o& )n ot"er %ords, do not create a DbyteF type and t"en e3pect to use it as a number& Listing 225. est types supported by /reateUno3alue. Sub 3e#tCreate0noOalue# -i! t.peHa!e# -i! : -i! iG t.peHa!e# 6 Arra.B":oid"= "boolean"= "c(ar"= "b.te"= "#trin"= 5 "#(ort"= "un#ined #(ort"= "lon"= "un#ined lon"= 5 "(.per"= "un#ined (.per"= "$loat"= "double"= "an."C
) I too1 t(e li#t o$ na!e# $ro! ) cppu+#ource+t.pelib+t.pelib&cxx "or i 6 ,BoundBt.peHa!e#C 3o 0BoundBt.peHa!e#C : 6 Create0noOalueBt.peHa!e#BiC= A<C ) Pou cannot directl. u#e t(e :alue becau#e it i# an 0HO t.pe= ) *(ic( i# onl. ood $or pa##in bac1 into 0HO& ) 3(in# li1e "Print :" or "CStrB:C" *ill $ail& Hext End Sub 1+.1+. Cinding obGects and properties 11o +asic "as functions to find ariab*es and t"eir properties based on t"eir names& T"is functiona*ity %as initia**y described to me as poor*y documented, possib*y deprecated, and bu$$y L and ) cannot disa$ree& 5se 0ind1b/ect to obtain a reference to a ariab*e %it" a $ien name, and 0ind'roperty1b/ect to obtain a reference to a named property of an ob/ect& T"e macro in Listin$ 226 demonstrates some of t"e idiosyncrasies of t"e 0ind1b/ect and 0ind'roperty1b/ect functions& TIP Do not use t"e functions 0ind1b/ect and 0ind'roperty1b/ect L t"ey are poor*y documented, bu$$y, and *i(e*y to be deprecated& ) on*y mention t"e met"ods to be comp*ete& Listing 226. est the +indOb%ect method. Sub 3e#t"indObNect -i! o3#t -i! o-oc -i! :ObN
Re! W(at doe# t(i# reall. !ean= $ound a null obNect and it i# null o3#t 6 "indObNectB"o-oc"C I$ I#HullBo3#tC 3(en Print ""ound o-oc but it I#Hull" )Pe# I$ o3#t IS o-oc 3(en Print "o3#t and o-oc are t(e #a!e" )Pe#
REM .e# I$ o-oc IS 3(i#Co!ponent 3(en Print "o-oc I# 3(i#Co!ponent a$ter a##in!ent" REM no I$ HO3 Bo3#t IS o-ocC 3(en Print "o3#t i# HO3 o-oc a$ter "indObNect" REM no I$ HO3 Bo3#t IS 3(i#Co!ponentC 3(en Print "o3#t i# HO3 3(i#Co!ponent" REM -o it aain= but do not #earc( $or o-oc o-oc 6 3(i#Co!ponent o3#t 6 "indObNectB"3(i#Co!ponent"C REM .e# I$ o3#t IS o-oc 3(en Print "o3#t and o-oc are t(e #a!e" REM .e# I$ o3#t IS 3(i#Co!ponent 3(en Print "o3#t and 3(i#Co!ponent are t(e #a!e" REM .e# I$ o-oc IS 3(i#Co!ponent 3(en Print "o-oc and 3(i#Co!ponent are t(e #a!e" REM 3(i#Co!ponent (a# a -ocu!entIn$o propert. o3#t 6 "indPropert.ObNectB3(i#Co!ponent= "-ocu!entIn$o"C Re! But it i# H0,, I$ I#HullBo3#tC 3(en Print "-ocu!entIn$o obNect I# Hull"
REM ,oad t(e Ji!!ic1# librar. JlobalScope&Ba#ic,ibrarie#&,oad,ibrar.B"Ji!!ic1#"C
REM "ind# t(e librar. e:en t(ou( it i# not a :ariable o-oc 6 "indObNectB"Ji!!ic1#"C
REM u#er$ield# i# a !odule in t(e Ji!!ic1# librar. o3#t 6 "indPropert.ObNectBo-oc= "0#er$ield#"C
REM but t(i# *or1# on librarie#K print Bo3#t I# Ji!!ic1#&0#er$ield#C )3rue
)3(e StartC(ane#0#er$ield# $unction i# in t(e !odule 0#er$ield# )Call t(e routine o-oc&0#er$ield#&StartC(ane#0#er$ield# End Sub )f t"ese functions sere your purposes, use t"em& ) tried to use t"ese to %rite an ob/ect inspector, but t"e 0ind'roperty1b/ect function did not %or( as ) e3pected& 1+.11. )@O listeners 11o uses *isteners to inform ot"er ob/ects %"at it is doin$& #onsider a "ospita* %or(er as an ana*o$y: +efore ) ,t"e "ospita* %or(er. do anyt"in$ interestin$ to treat patient 'ao*o, ) am re8uired first to ca** "is parents& 0or some t"in$s t"e parents may say Dno, you cannot do t"atF, and for ot"ers t"e parents are on*y informed ,status updates.& T"is is ery simi*ar to 541 *isteners& T"e code t"at you %rite is ca**ed t"e *istener, and t"e 246 t"in$ to %"ic" you *isten is ca**ed t"e broadcaster& )n t"e preious e3amp*e, t"e "ospita* %or(er is t"e broadcaster and 'ao*oGs parents are t"e *isteners& 6ou can *isten to t"e 11o ob/ects t"at act as a broadcaster& T"e routines re8uired to *isten to a specific 11o interface are specific to t"at interface& )n ot"er %ords, t"e set of subroutines and functions t"at can act as a *istener to printin$ eents is different t"an t"e set of subroutines and functions t"at can *isten to (eystro(e eents& TIP )f you do not imp*ement a re8uired met"od specified for t"e *istener interface, t"e *istener may cras" 11o& 13.11.1. @our first listener T"is *istener is presented %it" detai*s t"at are e3p*ained in t"e ne3t section, so, fo**o% t"e easy process and t"en find out %"y& A print *istener is demonstrated in section 13&1A&3& A #a*c e3amp*e %it" a 'rint *istener& A** *isteners must imp*ement t"e met"ods in t"e com&sun&star&*an$&I2entListener interface, %"ic" defines a one subroutine7 disposin$,2ent1b/ect.& T"e disposin$ met"od is ca**ed %"en t"e broadcaster is about to become unaai*ab*e& )n ot"er %ords, t"e broadcaster %i** no *on$er e3ist and you s"ou*d not use it& 0or e3amp*e, a print /ob is finis"ed so it is no *on$er re8uired or a document is c*osin$& Listin$ 22M demonstrates t"e most basic *istener possib*e, I2entListener7 4otice t"e strin$ prefi3 Dfirst=*isten=F before t"e re8uired name Ddisposin$F7 ) c"ose Dfirst=*isten=F because it is descriptie& Listing 227. *imple listener that does nothing. Sub $ir#t5li#ten5di#po#inB :Aru!ent C M#Box "-i#po#in In "ir#t ,i#tener" End Sub Listin$ 22M is a** t"at is re8uired for t"is simp*e *istener& 5se t"e #reate541Listener to create a 541 *istener t"at is associated %it" t"e macro in Listin$ 22M& T"e first ar$ument is t"e strin$ prefi3 and t"e second ar$ument is t"e name of t"e serice to create& T"e routine in Listin$ 22@ creates t"e 541 *istener and associates it %it" t"e routine in Listin$ 22M& ;"en t"e disposin$ met"od is ca**ed on Listener, it ca**s t"e routine in Listin$ 22M& TIP T"e code in Listin$ 21B creates a *istener and t"en ca**s t"e ob/ects disposin$ met"od& T"e *istener is imp*emented in Listin$ 21@, so, t"is u*timate*y ca**s first=*isten=disposin$ in Listin$ 21@& Listing 228. /reate a listener and then call the disposing method. Sub M."ir#t,i#tener -i! :,i#tener -i! :E:entObN A# He* co!&#un&#tar&lan&E:entObNect -i! #Pre$ixF -i! #Ser:iceF #Pre$ix 6 "$ir#t5li#ten5" #Ser:ice 6 "co!&#un&#tar&lan&/E:ent,i#tener" :,i#tener 6 Create0no,i#tenerB#Pre$ix= #Ser:iceC :,i#tener&di#po#inB:E:entObNC End Sub 247 13.11.2. ) complete listenerA selection change listener T"e t%o most difficu*t parts of creatin$ a *istener are determinin$ %"ic" broadcaster and %"ic" *istener interface to use& T"e rest of t"e steps are easier& 1. Determine t"e broadcaster to use& 2. Determine t"e *istener interface to imp*ement& 3. #reate $*oba* ariab*es for t"e *istener and maybe t"e broadcaster& Test your understandin$ and as( yourse*f %"y t"e ariab*e must be $*oba* before readin$ t"e tip be*o%& !. Determine t"e prefi3 t"at you %i** use7 ma(e it descriptie& A. ;rite a** of t"e subroutines and functions t"at imp*ement t"e *istener& 6. #reate t"e 541 *istener and sae it in t"e $*oba* ariab*e& M. Re$ister t"e *istener %it" t"e broadcaster& @. ;"en finis"ed, remoe t"e *istener from t"e broadcaster& TIP ;"y store t"e *istener in a $*oba* ariab*e> T"ere is usua**y a subroutine to create and re$ister t"e *istener %it" t"e broadcaster and t"en t"e macro ends& T"e *istener must e3ist %"en t"e macro stops runnin$& T"e on*y %ay to do t"is in +asic is to use a J*oba* ariab*e& Anot"er macro, run *atter, remoes t"e *istener from t"e broadcaster& T"e *atter macro must be ab*e to access t"e *istener& <no%in$ %"ic" broadcaster to use is not a*%ays an easy tas(& )t re8uires understandin$ "o% 11o is desi$ned7 t"is comes %it" e3perience& T"ere is usua**y an obious p*ace to start *oo(in$ L t"e current document, aai*ab*e from t"e ariab*e T"is#omponent, contains t"e document data& 0or e3amp*e, t"e document accepts an I'rintKobListener to monitor "o% printin$ is pro$ressin$& Most tas(s re*ated to user interactions L suc" as se*ectin$ te3t, moin$ t"e mouse, and enterin$ (eystro(es L a** $o t"rou$" t"e documentGs contro**er& After se*ectin$ t"e broadcaster *oo( c"ec( t"e broadcaster for met"ods %it" names *i(e Dadd *istenerF& ) %as as(ed "o% to preent a dia*o$ from c*osin$ %"en t"e user c*ic(s on t"e *itt*e I icon in t"e upper9ri$"t corner of a dia*o$& ) reasoned t"at t"e dia*o$ is probab*y t"e correct broadcaster to use, so ) created a dia*o$ and inspected t"e Ddb$=met"odsF property to see %"ic" *isteners it supports ,eac" supported *istener "as DsetF and DremoeF met"ods.& Anot"er option is to determine t"e eent type t"at is produced and t"en searc" for broadcasters support t"is eent type& ) usua**y do t"is by searc"in$ t"e 11o Dee*operGs Juide and t"e )nternet& ,)G** discuss effectie met"ods for findin$ information in #"apter >>, D>>Sources of )nformation&F. To *isten for a se*ection c"an$e eent, imp*ement an ISe*ection#"an$eListener and re$ister it %it" t"e current contro**er& T"e ISe*ection#"an$eListener interface defines on*y one subroutine t"at must be imp*emented L se*ection#"an$ed,1b/ect2ent.& A** eents are deried from t"e I2entListener so t"e disposin$,1b/ect2ent. met"od must a*so be imp*emented& T"e fastest %ay to determine %"ic" subroutines and functions must be imp*emented is to create an instance of t"e *istener by usin$ t"e function #reate541Listener and t"en inspect t"e db$=met"ods property ,see Listin$ 22B and 0i$ure M6.& Listing 229. *ee the methods supported by a specific listener. Sub In#pect,i#tenerMet(od# -i! #Pre$ixF -i! #Ser:iceF -i! :Ser:ice #Pre$ix 6 "#el5c(ane5" 248 #Ser:ice 6 "co!&#un&#tar&:ie*&/SelectionC(ane,i#tener" :Ser:ice 6 Create0no,i#tenerB#Pre$ix= #Ser:iceC -i#pla.-bIn$oStrB:Ser:ice&db5!et(od#= "\"= %<= "Met(od#"C End Sub Figure 76. "gnore the 8uery"nterface method. T"e 8uery)nterface met"od is from t"e interface com&sun&star&uno&I)nterface, %"ic" is in"erited from t"e I2entListener& 6ou can i$nore t"is met"od& Eo%eer, you must imp*ement t"e rest of t"e routines& #"oose a descriptie prefi3 so t"at t"e code can contain more t"an one *istener& See Listin$ 230& Listing 230. #isposing and selection changed. )All li#tener# !u#t #upport t(i# e:ent Sub #el5c(ane5di#po#inB:E:entC !#box "di#po#in t(e #election c(ane li#tener" End Sub Sub #el5c(ane5#electionC(anedB:E:entC -i! :CurrentSelection A# ObNect :CurrentSelection 6 :E:ent&#ource Print "Hu!ber o$ #elected area# 6 " 45 :CurrentSelection&etSelectionBC&etCountBC End Sub T"e routine in Listin$ 231 creates a *istener by ca**in$ t"e function #reate5noListener& ;"en ) tested t"is *istener, ) ran t"e macro and t"en t"e macro stopped runnin$& T"e *istener is sti** actie and ca**ed by t"e broadcaster een t"ou$" t"e macro is no *on$er runnin$& )n ot"er %ords, t"e routine in Listin$ 231 re$isters a *istener, and t"en it is finis"ed& T"e broadcaster ca**s t"e *istener %"en t"in$s occur& T"e *istener must be stored in a $*oba* ariab*e so t"at itGs aai*ab*e *ater L for e3amp*e, %"en itGs time to remoe t"e *istener from t"e ob/ect or %"en one of t"e met"ods is ca**ed& Listing 231. *tart listening for selection change events. Jlobal :SelC(ane,i#tener )Mu#t be lobal Jlobal :SelC(aneBroadCa#t )Run t(i# !acro to #tart e:ent interceptin Sub Start,i#tenin3oSelC(aneE:ent# -i! #Pre$ixF -i! #Ser:iceF #Pre$ix 6 "#el5c(ane5" #Ser:ice 6 "co!&#un&#tar&:ie*&/SelectionC(ane,i#tener"
REM to rei#ter $or a #election c(ane= .ou !u#t rei#ter *it( t(e REM current controller :SelC(aneBroadCa#t 6 3(i#Co!ponent&etCurrentController 249
)Create a li#tener to intercept t(e #election c(ane e:ent# :SelC(ane,i#tener 6 Create0no,i#tenerB#Pre$ix= #Ser:iceC
)Rei#ter t(e li#tener to t(e docu!ent controller :SelC(aneBroadCa#t&addSelectionC(ane,i#tenerB:SelC(ane,i#tenerC End Sub T"e be"aior of t"e code in Listin$ 231 is annoyin$& 2ery time a ne% se*ection is made, t"e code is ca**ed and it opens a dia*o$ on t"e screen& T"is interferes %it" se*ectin$ te3t& To remoe t"e *istener, use t"e code in Listin$ 232& Listing 232. *top listening for selection change events. Sub Stop,i#tenin3oSelC(aneE:ent# ) re!o:e# t(e li#tener :SelC(aneBroadCa#t&re!o:eSelectionC(ane,i#tenerB:SelC(ane,i#tenerC End Sub To test t"e *istener: 1. Start *istenin$& 2. Ma(e ery simp*e se*ection c"an$es suc" as: #*ic( somep*ace& S"iftN#*ic( to se*ect more& #tr*N#*ic( to ma(e a second se*ection& 3. Stop *istenin$& Sae a** open documents %"i*e testin$ *isteners, a simp*e error is *i(e*y to cause 11o to cras"& 1+.12. Creating a )@O dialog 5se #reate5noDia*o$ to create an e3istin$ dia*o$& T"is section introduces t"e function #reate5noDia*o$, it does not discuss "o% to create dia*o$s& #reate5noDia*o$ accepts a sin$*e ar$ument, t"e fu** pat" to t"e dia*o$ definition& Create0no-ialoBJlobalScope&Ba#ic,ibrarie#&,ibHa!e&-ialoHa!eC T"e ariab*e J*oba*Scope proides access to t"e app*ication9*ee* *ibraries L one of %"ic" is named D*$1er%riteA** and is inc*uded %it" 11o in t"e Too*s *ibrary& 6ou must *oad t"e *ibrary containin$ t"e dia*o$ before you can use t"e dia*o$& 6ou can manua**y *oad t"e *ibrary, or do it direct*y from t"e macro& 5se Tools > Macros > Organize $ialogs to open t"e +asic Macros 1r$aniCer dia*o$, %"ic" can be used To manua**y *oad *ibraries& 5se t"e LoadLibrary command to *oad a *ibrary usin$ a macro& JlobalScope&Ba#ic,ibrarie#&,oad,ibrar.B"3ool#"C Create0no-ialoBJlobalScope&Ba#ic,ibrarie#&3ool#&-lO:er*riteAllC )f t"e dia*o$ is defined inside a document, use t"e +asicLibraries ariab*e& Create0no-ialoBBa#ic,ibrarie#&,ibHa!e&-ialoHa!eC TIP An eent means t"at somet"in$ "appened& ;"en certain t"in$s "appen, an eent ob/ect is created t"at describes somet"in$ about %"at "appened& T"e eent ob/ect is sent to a *istener, or %"at eer routine is confi$ured to be ca**ed %"en t"e eent occurs& 6ou can %rite an DeentF routine t"at is ca**ed %"en somet"in$ "appens7 for e3amp*e, %"en a button is pressed& ;"en you create a dia*o$, you usua**y %rite eent "and*ers as subroutines in +asic7 for e3amp*e, a button in a dia*o$ does not"in$ un*ess eents are mapped to subroutines or functions t"at you %rite& 6ou can add a 250 c*ose button to a dia*o$ and map t"e buttonVs D23ecute actionF eent to a macro t"at c*oses t"e dia*o$& )f a macro ca**ed from an eent "and*er accesses a runnin$ dia*o$, t"en t"e dia*o$ must be stored in a ariab*e t"at t"e macro can access& ) $enera**y c"oose to create a priate ariab*e t"at "o*ds t"is type of data& See Listin$ 233& Listing 233. #isplay information about an ob%ect using a dialog. Pri:ate M.Sa!ple-ialo Sub -i#pla.ObNectIn$or!ationBOptional :OptionalObNC -i! :Control )I acce## t(e text control in t(e dialo -i! #F )3e!porar. #trin :ariable -i! :ObN )ObNect about *(ic( to di#pla. in$or!ation
REM I$ t(# obNect i# not pro:ided= u#e t(e current docu!ent I$ I#Mi##inB:OptionalObNC 3(en :ObN 6 3(i#Co!ponent El#e :ObN 6 :OptionalObN End I$
REM Create t(e dialo and #et t(e title M.Sa!ple-ialo 6 Create0no-ialoB-ialo,ibrarie#&OOME5%7&M."ir#t-ialoC M.Sa!ple-ialo&#et3itleB"Oariable 3.pe " 4 3.peHa!eB:ObNCC
REM Jet t(e text $ield $ro! t(e dialo REM I added t(i# text !anuall. :Control 6 M.Sa!ple-ialo&etControlB"3ext"ield>"C
I$ InStrB3.peHa!eB:ObNC= "ObNect"C E > 3(en REM I$ t(i# i# HO3 an obNect= #i!pl. di#pla. #i!ple in$or!ation :Control&#et3extB-l5JetObN3.peIn$oB:ObNCC
El#eI$ HO3 Ha#0noInter$ace#B:ObN= "co!&#un&#tar&uno&/Inter$ace"C 3(en REM It i# an obNect but it i# not a 0HO obNect REM I cannot call Ha#0noInter$ace# i$ it i# not an obNect :Control&#et3extB-l5JetObN3.peIn$oB:ObNCC
REM tell t(e dialo to #tart it#el$ M.Sa!ple-ialo&executeBC End Sub 251 TIP Store t"e dia*o$ in a priate ariab*e dec*ared as type 1b/ect& 5se a priate ariab*e so t"at it doesnGt need*ess*y affect ot"er modu*es& 1n at *east one occasion, a dia*o$ t"at ) created %or(ed %"en it %as "e*d in a ariab*e dec*ared as an 1b/ect, but fai*ed %"en "e*d in a ariab*e dec*ared as a Oariant7 so muc" for my recommendation to usua**y a ariant rat"er t"an an 1b/ect& T"e macro in Listin$ 233 disp*ays a dia*o$ t"at disp*ays information about t"e ob/ect t"at %as passed in as an ar$ument& ) use t"e Eas5no)nterfaces function to see if t"is is a 541 serice& ) first c"ec( to see if t"e ob/ectGs Type4ame contains t"e te3t D1b/ectF7 t"is te**s me if t"e ob/ect is rea**y an ob/ect& I$ InStrB3.peHa!eB:ObNC= "ObNect"C E > 3(en )f t"e ob/ect is not an ob/ect t"at supports a 541 interface, t"e ob/ect is inspected and information about it disp*ayed& Listin$ 23! s"o%s t"e te3t strin$ to do t"is& 0i$ure MM s"o%s t"e resu*ts& Listing 234. Return type information as a string. "unction -l5JetObN3.peIn$oB:ObNC A# Strin -i! # A# Strin # 6 "3.peHa!e 6 " 4 3.peHa!eB:ObNC 4 CHRFB>7C 45 "Oar3.pe 6 " 4 Oar3.peB:ObNC 4 CHRFB>7C I$ I#HullB:ObNC 3(en # 6 # 4 "I#Hull 6 3rue" El#eI$ I#E!pt.B:ObNC 3(en # 6 # 4 "I#E!pt. 6 3rue" El#e I$ I#ObNectB:ObNC 3(en # 6 # 4 "I#ObNect 6 3rue" 4 CHRFB>7C I$ I#0noStructB:ObNC 3(en # 6 # 4 "I#0noStruct 6 3rue" 4 CHRFB>7C I$ I#-ateB:ObNC 3(en # 6 # 4 "I#-ate 6 3rue" 4 CHRFB>7C I$ I#Hu!ericB:ObNC 3(en # 6 # 4 "I#Hu!eric 6 3rue" 4 CHRFB>7C I$ I#Arra.B:ObNC 3(en On ,ocal Error Joto -ebuBound#Error: -i! iG= #3e!pF # 6 # 4 "I#Arra. 6 3rue" 4 CHRFB>7C 4 "rane 6 B" -o W(ile BiG D6 7C iG 6 iG W > #3e!pF 6 ,BoundB:ObN= iGC 4 " 3o " 4 0BoundB:ObN= iGC I$ iG D > 3(en # 6 # 4 "= " # 6 # 4 #3e!pF ,oop -ebuBound#Error: On ,ocal Error Joto 7 # 6 # 4 "C" 4 CHRFB>7C End I$ End I$ -l5JetObN3.peIn$o 6 # End "unction 252 Figure 77. he variable is an array of strings )f t"e first ar$ument supports a 541 interface, t"e Ddb$=F properties are used to disp*ay a** of t"e met"ods, properties, and serices supported by t"is ob/ect ,see Listin$ 23A and 0i$ure M@.& T"is is ery simi*ar to t"e code in Listin$ 21B, e3cept t"at it returns a strin$ rat"er t"an disp*ayin$ a series of simp*e dia*o$s& T"is is an e3ce**ent %ay to 8uic(*y see %"at met"ods, properties, and interfaces an ob/ect supports& 4otice a*so t"at t"e ariab*e type is disp*ayed in t"e upper9*eft corner of t"e dia*o$& Listing 235. /onvert the debug string into one string with new line characters. "unction -l5-i#pla.-bIn$oStrB#In$oF= #SepFC A# Strin -i! aIn$oBC )Arra. to (old eac( #trin -i! i A# Inteer )Index :ariable -i! N A# Inteer )Mun1 inteer :ariable $or te!porar. :alue# -i! # A# Strin )(old# t(e portion t(at i# not co!pleted # 6 #In$oF N 6 InStrB#= ":"C )Initial colon I$ N D 7 3(en MidB#= >= N= ""C )Re!o:e portion up to t(e initial colon aIn$oBC 6 SplitB#= #SepFC )Split #trin ba#ed on deli!iter "or i 6 ,BoundBaIn$oBCC 3o 0boundBaIn$oBCC ),oo1 at eac( piece to re!o:e aIn$oBiC 6 3ri!BaIn$oBiCC )leadin and trailin #pace# N 6 InStrBaIn$oBiC= CHRFB>7CC )So!e (a:e an extra I$ N D 7 3(en MidBaIn$oBiC= N= >= ""C )ne* line t(at #(ould be re!o:ed Hext -l5-i#pla.-bIn$oStr 6 MoinBaIn$oBC= CHRFB>7CC End "unction 253 Figure 78. he variable is a 'riter document. 1+.13. Conclusion T"e subroutines and functions supp*ied %it" 11o +asic support a %ide ran$e of operations t"at are re8uired to access t"e interna*s of 11o& 5se t"e met"ods presented in t"is c"apter to inspect and use t"e 541 serices& T"is c"apter e3amined t"e fundamenta*s for creatin$ 541 *isteners, %"ic" are based on e3istin$ 11o *ibraries& 541 *isteners proide basic system functiona*ity, and ne% 541 *isteners e3tend t"is functiona*ity to $ie t"e pro$rammer a $reat dea* of contro* oer system app*ications and be"aior& Any 541 *istener *istens to one or more broadcasters, proidin$ t"e capabi*ity to respond to system eents t"at are communicated across app*ications& 254 11. The (ispatcher T"is c"apter bui*ds on preious coera$e of t"e 1pen1ffice&or$ paradi$m and t"en introduces t"e dispatc"er& T"e dispatc"er proides a simp*e mec"anism for ino(in$ interna* functiona*ity %it" *imited (no%*ed$e of "o% t"e interna*s %or(, but it is considered t"e *east9faored %ay of contro**in$ 1pen1ffice&or$& 11.1. 0he environment 1pen1ffice&or$ separates a componentGs ,documentVs. functiona*ity into t"e mode*, t"e contro**er, and t"e frame& 0RAM2 #ombines t"e pieces7 it contains a mode*Gs contro**er and (no%s a** about t"e disp*ay %indo%& T"e frame does not, "o%eer, "ae any disp*ay %indo% functiona*ity7 t"e frame /ust (no%s t"at disp*ay %indo%s e3ist& Send a dispatc" to t"e frame, because it contro*s t"in$s and (no%s "o% to route a dispatc"& Mode* #onsists of t"e document data and t"e met"ods to c"an$e t"e data& You can update data directly using the model. #ontro**er A%are of t"e current ie% and t"e data7 it manipu*ates t"e document %"i*e receiin$ input from t"e user interface& T"e contro**er (no%s t"in$s *i(e %"at is se*ected and is ab*e to se*ect t"in$s& TIP #omponent a*most a*%ays means an open document, but ot"er %indo%s are a*so components7 for e3amp*e, t"e +asic )D2 and t"e "e*p %indo%& 11.1.1. T1o different methods to control OOo T"e most ersati*e met"od to manipu*ate an 11o document is to $et t"e interna* 541 ob/ects and manipu*ate t"em& 5sin$ t"e mode* proides si$nificant contro*, but you must understand muc" about t"e different serices and interfaces& Anot"er met"od, %"ic" re8uires ery *itt*e understandin$ of t"e 11o interna*s, is to use a 541 dispatc"er& T"e dispatc"er accepts a command suc" as D&uno:5ndoF and ta(es care of t"e rest of t"e detai*s& T"e frame proides t"e re8uired dispatc"ers to perform t"e %or(& 0or simp*icity, t"in( of issuin$ a dispatc" as ery simi*ar to se*ectin$ an action from t"e menu& A*t"ou$" direct contro* usin$ 541 serices proides t"e most contro* and ersati*ity, some operations are muc" easier to perform usin$ t"e dispatc"er7 sometimes a dispatc"er is t"e on*y %ay to accomp*is" a tas(& 0or e3amp*e, t"e dispatc"er is t"e best so*ution for "and*in$ t"e c*ipboard& 2en t"e macro recorder performs a*most a** tas(s usin$ a dispatc"er& 255 T"ree t"in$s are re8uired to accomp*is" tas(s usin$ a dispatc"er: ,1. t"e command to dispatc", ,2. ar$uments t"at contro* t"e dispatc", and ,3. an ob/ect capab*e of performin$ t"e dispatc" ,a dispatc" proider, %"ic" is usua**y a frame.& 2ac" document "as a contro**er t"at, *oose*y spea(in$, acts as t"e interface bet%een t"e outside %or*d and t"e document& 0or e3amp*e, use t"e current contro**er to se*ect te3t, find t"e current cursor *ocation, or determine %"ic" s"eet is actie in a spreads"eet& T"e current contro**er can a*so return t"e frame of t"e document, %"ic" supports t"e dispatc" command& Listing 236. he #ispatch&elper service greatly simplifies e.ecuting dispatches. o-i#pHelper 6 create0noSer:iceB"co!&#un&#tar&$ra!e&-i#patc(Helper"C T"e dispatc" "e*per imp*ements t"e function e3ecuteDispatc", %"ic" imp*ements most of t"e functiona*ity re8uired to perform a dispatc"& Tab*e B! contains a *ist of t"e ar$uments supported by t"e e3ecuteDispatc" met"od& ;"i*e e3ecutin$ a dispatc", as discussed "ere, you cannot dispatc" a command to a frame based on its name L eit"er *eae t"e tar$et frame empty or enter D=se*fF& )t is a*so, t"erefore, not important to use anyt"in$ ot"er t"an Cero, or omit t"e ar$ument comp*ete*y, for t"e searc" f*a$& Attemptin$ to specify anot"er frame resu*ts in a run9time error ,it seems si**y to me t"at t"e ar$uments e3ist if t"ey are not usab*e 1 .& Table 94. -rguments to e.ecute#ispatch. $r+ment Description IDispatc"'roider Dispatc" proider t"at performs t"e dispatc"& 5RL Strin$ T"e command to dispatc", as a strin$& Tar$et 0rame Strin$ )dentifies t"e frame t"at %i** receie t"e dispatc"& 5se an empty strin$ or D=se*fF to specify t"e current frame ,any ot"er a*ue is ina*id.& *on$ 1ptiona* searc" f*a$s t"at indicate "o% to find t"e tar$et frame& 5se Cero or b*an( ,see Listin$ 23M., because it is not supported& 'ropertyOa*ue,. 1ptiona* ar$uments t"at are dependent on t"e imp*ementation& Listing 237. $.ecute the >undoA dispatch. Sub He*0ndo -i! o-i#pHelper a# obNect -i! oPro:ider A# ObNect oPro:ider 6 3(i#Co!ponent&CurrentController&"ra!e o-i#pHelper 6 create0noSer:iceB"co!&#un&#tar&$ra!e&-i#patc(Helper"C o-i#pHelper&execute-i#patc(BoPro:ider="&uno:0ndo"= ""= = Arra.BCC End Sub T"e dispatc" commands "ae bot" a name and a number, ca**ed a Ds*ot&F A*t"ou$" a dispatc" can be made based on eit"er, t"e dee*opers to*d me t"at t"e s*ot number may c"an$e in t"e future so it is safer to use t"e name& )f you must use a s*ot, t"e Too*s *ibrary contains a subroutine ca**ed Dispatc"S*ot, %"ic" performs a dispatc" based on a s*ot number a*one& Listing 238. #ispatch to a numeric slot. )Include t(i# librar. to u#e t(e -i#patc(Slot co!!and& JlobalScope&Ba#ic,ibrarie#&,oad,ibrar.B"3ool#"C -i#patc(SlotB<%7>C ),oad t(e About dialo= #a!e a# "&uno:About" 1 I have not verified that a named frame does not work in OOo 3.3, but it did fail when I tested around version 2.0. 256 TIP 6ou cannot ca** a routine in a *ibrary un*ess t"e *ibrary is *oaded& 6ou can *oad a *ibrary manua**y from t"e Macro dia*o$ and you can *oad it usin$ t"e LoadLibrary command as s"o%n in Listin$ 23@& T"e Too*s *ibrary inc*uded %it" 11o contains t"e Dispatc"S*ot subroutine& Some dispatc" commands re8uire ar$uments& T"e e3amp*es in Listin$ 23B perform a dispatc" %it" ar$uments& T"e JoTo#e** command needs to (no% %"ic" ce** to $o to& T"is macro moes t"e current cursor to t"e ce** +3 in a spreads"eet document& Listing 239. #ispatch commands can use arguments. -i! ar#'B7C a# ne* co!&#un&#tar&bean#&Propert.Oalue ar#'B7C&Ha!e 6 "3oPoint" ar#'B7C&Oalue 6 "FBF%" ) po#ition to B% -i! o-i#pHelper a# obNect -i! oPro:ider A# ObNect oPro:ider 6 3(i#Co!ponent&CurrentController&"ra!e o-i#pHelper 6 create0noSer:iceB"co!&#un&#tar&$ra!e&-i#patc(Helper"C o-i#pHelper&execute-i#patc(BoPro:ider= "&uno:Jo3oCell"= ""= 7= ar#'BCC 11.1.2. +inding dispatch commands A comp*ete *ist of dispatc" commands is tric(y to find& 'reious*y, ) assemb*ed a comp*ete *ist of a** supported dispatc" commands, but, t"e *ist c"an$es and it is not c*ear to me t"at it is of muc" user& As suc", ) decided to te** you "o% to find t"e *ist on your o%n& )f t"ere is a demand for it, ) may be coninced to compi*e a ne% *ist& T"an(s to Arie* #onsten*a Eai*e for t"is information& )se the 1!H! "ttp:--%i(i&serices&openoffice&or$-%i(i-0rame%or(-Artic*e-1pen1ffice&or$=3&3=#ommands contains a *ist of commands and s*ots& #*ear*y some commands are missin$, suc" as D&uno:1b/ectTit*eDescriptionF, but t"e *ist is fair*y comp*ete& 3robe the interface T"e fo**o%in$ macro uses t"e 5)#ommandDescription serice to enumerate t"e supported modu*es& A ne% #a*c document is created and a s"eet is created for eac" modu*e& T"e commands supported by t"e modu*e are p*aced on t"e s"eet& 4ote t"at t"e macro ta(es a %"i*e to run because t"ere is a *ot of data to process& Listing 240. <et commands from the ModuleManager. Sub Print5All5Co!!and# ) Create a ne* Calc docu!ent to (old t(e di#patc( co!!and# -i! o-oc A# ObNect o-oc 6 Star-e#1top&loadCo!ponent"ro!0R,B"pri:ate:$actor.+#calc"= "5de$ault"= 7= Arra.BCC -i! oS(eet# A# ObNect : oS(eet# 6 o-oc&etS(eet#BC )3(e 0ICo!!and-e#cription #er:ice pro:ide# acce## to t(e u#er inter$ace co!!and# t(at are )part o$ OpenO$$ice&or !odule#= li1e Writer or Calc& -i! o0ICo!!and-e#cription A# ObNect o0ICo!!and-e#cription 6 Create0noSer:iceB"co!&#un&#tar&$ra!e&0ICo!!and-e#cription"C )Identi$. o$$ice !odule# and pro:ide read acce## to t(e con$iuration o$ o$$ice !odule#& 257 -i! oModuleIdenti$ier A# ObNect oModuleIdenti$ier 6 Create0noSer:iceB"co!&#un&#tar&$ra!e&ModuleManaer"C -i! oModule0ICo!!and-e#cription A# ObNect= aModule#FBC=aCo!!and -i! aCo!!and#FBC -i! n4= i4 ) Jet a li#t o$ !odule na!e# #uc( a# "co!&#un&#tar&pre#entation&Pre#entation-ocu!ent" ) Create a #(eet $or eac( !odule& aModule# 6 oModuleIdenti$ier&etEle!entHa!e#BC "or n 6 7 3o 0BoundBaModule#C oModule0ICo!!and-e#cription 6 o0ICo!!and-e#cription&etB.Ha!eBaModule#BnCC ) Jet t(e co!!and# #upported b. t(i# !odule& Re-i! aCo!!and#FBC aCo!!and# 6 oModule0ICo!!and-e#cription&etEle!entHa!e#BC I$ n E6 0BoundBoS(eet#&etEle!entHa!e#BCC 3(en oS(eet#&etB.IndexBnC&#etHa!eBaModule#BnCC El#e oS(eet#&in#ertHe*B.Ha!eBaModule#BnC=nC End I$ oS(eet#&etCellB.Po#itionB7= 7= nC&et3extBC&#etStrinB"Co!!and"C oS(eet#&etCellB.Po#itionB>= 7= nC&et3extBC&#etStrinB",abel"C oS(eet#&etCellB.Po#itionB'= 7= nC&et3extBC&#etStrinB"Ha!e"C oS(eet#&etCellB.Po#itionB%= 7= nC&et3extBC&#etStrinB"Popup"C oS(eet#&etCellB.Po#itionB?= 7= nC&et3extBC&#etStrinB"Propert."C "or i 6 7 3o 0BoundBaCo!!and#C aCo!!and 6 oModule0ICo!!and-e#cription&etB.Ha!eBaCo!!and#BiCC -i! #,abelF= #Ha!eF= bPopup a# Boolean= nPropert.4= 1G "or 1 6 7 3o 0BoundBaCo!!andC I$ aCo!!andB1C&Ha!e 6 ",abel" 3(en #,abel 6 aCo!!andB1C&Oalue El#eI$ aCo!!andB1C&Ha!e 6 "Ha!e" 3(en #Ha!e 6 aCo!!andB1C&Oalue El#eI$ aCo!!andB1C&Ha!e 6 "Popup" 3(en bPopup 6 aCo!!andB1C&Oalue El#eI$ aCo!!andB1C&Ha!e 6 "Propert." 3(en nPropert. 6 aCo!!andB1C&Oalue End I$ Hext oS(eet#&etCellB.Po#itionB7= iW>= nC&et3extBC&#etStrinBaCo!!and#BiCC oS(eet#&etCellB.Po#itionB>= iW>= nC&et3extBC&#etStrinB#,abelC oS(eet#&etCellB.Po#itionB'= iW>= nC&et3extBC&#etStrinB#Ha!eC I$ bPopup 3(en oS(eet#&etCellB.Po#itionB%= iW>= nC&et3extBC&#etStrinB"3rue"C El#e oS(eet#&etCellB.Po#itionB%= iW>= nC&et3extBC&#etStrinB""al#e"C End I$ 258 oS(eet#&etCellB.Po#itionB?= iW>= nC&et3extBC&#etStrinBCStrBnPropert.CC Hext -i! oColu!n# a# ObNect oColu!n# 6 oS(eet#&etB.IndexBnC&etColu!n#BC -i! NG "or N 6 7 3o ? oColu!n#&etB.IndexBNC&#etPropert.OalueB"Opti!alWidt("= 3rueC Hext Hext End Sub IDispatc")nformation'roider constructs a *ist of dispatc" commands as returned by t"e current contro**er and disp*ays t"e *ist in a #a*c document& Listing 241. <et commands from the current controller. Sub /-i#patc(In$or!ationPro:ider -i! o-oc A# ObNect o-oc 6 Star-e#1top&loadCo!ponent"ro!0R,B"pri:ate:$actor.+#calc"= "5de$ault"= 7= Arra.BCC -i! oS(eet A# ObNect : oS(eet 6 o-oc&etS(eet#BC&etB.IndexB7C oS(eet&etCellB.Po#itionB7= 7C&et3extBC&#etStrinB"Jroup"C oS(eet&etCellB.Po#itionB>= 7C&et3extBC&#etStrinB"Co!!and"C
-i! oController : oController 6 3(i#Co!ponent&etCurrentControllerBC I$ I#HullBoControllerC Or 5 HO3 Ha#0noInter$ace#B oController= "co!&#un&#tar&$ra!e&/-i#patc(In$or!ationPro:ider"C 3(en )3O-O: #o!e *arnin Exit Sub End I$ -i! iSupportedC!dJroup#GBC iSupportedC!dJroup# 6 oController&etSupportedCo!!andJroup#BC -i! iG= NG -i! 1G "or i 6 7 3o 0BoundBiSupportedC!dJroup#C -i! a-i#patc(In$oBC a-i#patc(In$o 6 oController&etCon$iurable-i#patc(In$or!ationBiSupportedC!dJroup#BiCC
"or N 6 7 3o 0BoundBa-i#patc(In$oC -i! a-i#patc(In$or!ation a-i#patc(In$or!ation 6 a-i#patc(In$oBNC 1 6 1 W > oS(eet&etCellB.Po#itionB7= 1C&et3extBC&#etStrinBiSupportedC!dJroup#BiCC oS(eet&etCellB.Po#itionB>= 1C&et3extBC&#etStrinBa-i#patc(In$or!ation&Co!!andC Hext Hext End Sub ) e3c"an$ed emai* %it" Arie* and s"e e3pressed doubts as to t"e comp*eteness and accuracty of t"e returned *ist7 because t"e +ib*io$rap"ic commands proided by t"e 5)#ommandDescription inc*uded commands suc" as D&uno:Arro%S"apesF, %"ic" is nonsensica* in t"is conte3t& 259 %ead source code S0I2 based components s"are a common base c*ass for t"eir #ontro**er ob/ect imp*ementation, Sf3+ase#ontro**er& 0or modu*es based on S0I2, it is possib*e to obtain t"e dispatc"es as %e** as t"e parameters by parsin$ t"e SD) fi*es inside eery sf32 based modu*e ,*oo( at t"e fo*der [modu*eR-sdi-.7 or een parse t"e "eader fi*es $enerated in t"e bui*d enironment& #onsider fi*es %it" names suc" as sf3s*ots&"33, s3s*ots&"33, scs*ots&"33, sds*ots&"33, s%s*ots&"33, bass*ots&"33, and sms*ots&"33& 0or ne% modu*es it may be easier to /ust bro%se t"e source code7 for e3amp*e, in c"art2: c"art2-source-contro**er-main-#"art#ontro**er&c33 c"art2-source-contro**er-main-Dra%#ommandDispatc"&c33 c"art2-source-contro**er-main-S"ape#ontro**er&c33 TIP Dispatc" command names are case sensitie& 11.2. 1riting a macro using the dispatcher ;"en you canGt find a met"od to accomp*is" a tas( usin$ t"e 541 A'), t"e ne3t c"oice is usua**y to use t"e dispatc"er& Macros created by t"e macro recorder usin$ dispatc"es7 use Tools Macros %ecor& Macro to start t"e macro recorder& TIP Some component types do not support t"e macro recorder7 for e3amp*e, Dra%& T"e macro recorder "as many *imitations7 for e3amp*e, t"e macro recorder usua**y does not trac( %"at "appens %"en a dia*o$ is opened& ) discoered t"is *imitation %"en ) used t"e macro recorder to create a macro to import te3t fi*es& T"e DTe3t ,encoded.F import fi*ter opens a dia*o$ and as(s 8uestions about t"e imported fi*e& T"e a*ues entered in t"e dia*o$ are not captured by t"e macro recorder& )f you desire to %rite a macro usin$ t"e A'), start by readin$ t"rou$" t"e supported commands as $enerated by one of t"e macros s"o%n aboe& T"e DSend1utLineToStar)mpressF command creates an )mpress presentation %it" an out*ine created from t"e "eadin$s in t"e current document& 4o ar$uments are re8uired& Listing 242. /reate an "mpress document with an outline from this document. Sub CreateOutlineInI!pre## -i! o-i#pHelper a# obNect -i! oPro:ider A# ObNect oPro:ider 6 3(i#Co!ponent&CurrentController&"ra!e o-i#pHelper 6 create0noSer:iceB"co!&#un&#tar&$ra!e&-i#patc(Helper"C o-i#pHelper&execute-i#patc(BoPro:ider="&uno:SendOutline3oStarI!pre##"=5 ""= = Arra.BCC End Sub 11.3. Conclusion T"e dispatc" commands are po%erfu* and re8uire *itt*e (no%*ed$e of t"e interna* %or(in$s of 11o& A*t"ou$" some functiona*ity, suc" as t"e 5ndo command, can on*y be used in t"e dispatc"er, macros t"at %i** be used for a *on$ time are better off usin$ t"e interna* ob/ects direct*y& 260 12. tar(esktop T"e des(top acts as t"e main app*ication t"at contro*s 1pen1ffice&or$& T"is c"apter introduces $enera* tec"ni8ues L suc" as accessin$ inde3ed ob/ects, enumeratin$ open documents, and *oadin$ ne% documents L %"i*e discussin$ and demonstratin$ t"e base functiona*ity of t"e Des(top ob/ect& T"is c"apter a*so coers t"e Des(top ob/ect and T"is#omponent& T"e Des(top ob/ect is a com&sun&star&frame&Des(top serice, %"ic" supp*ies four primary functions: 1& StarDes(top acts as a frame& T"e des(top is t"e parent frame and contro*s t"e frames for a** of t"e documents& 2& StarDes(top acts as a des(top& T"e des(top is t"e main app*ication %it" t"e abi*ity to c*ose t"e documents L %"en t"e app*ication is s"ut do%n, for e3amp*e& 3& StarDes(top acts as a document *oader& T"e ro*e of t"e main app*ication a*so a**o%s t"e des(top to *oad e3istin$ documents and create ne% documents& !& StarDes(top acts as an eent broadcaster& T"e des(top notifies e3istin$ documents ,or any ot"er *istener. of t"in$s t"at are "appenin$ L %"en t"e app*ication is about to s"ut do%n, for e3amp*e& T"e Des(top, actin$ as t"e primary app*ication ob/ect, is created %"en 11o is started& 5se t"e $*oba**y aai*ab*e ariab*e StarDes(top to access t"e 11o Des(top ob/ect& 12.1. 0he Crame service T"e des(top is a com&sun&star&frame&0rame serice ,remember t"at an ob/ect can, and usua**y does, imp*ement more t"an one serice at a time.& 0or a document, t"e primary purpose of a frame is to act as a *iaison bet%een t"e document and t"e isib*e %indo%& 0or t"e des(top, "o%eer, t"e primary purpose is to act as t"e root frame, %"ic" contains a** ot"er frames& A frame can "o*d a component and Cero or more subframes L for simp*icity, consider a component to be a document& )n t"e case of t"e des(top, a** t"e ot"er frames are subframes of t"e root frame, and t"e component ,document. is a set of data& Simp*y stated, eac" document contains a frame t"at it uses to interact %it" t"e isib*e %indo%, but t"e des(top is a frame so t"at it can contain, contro*, and access a** of t"e documentGs frames& T"e serice com&sun&star&frame&0rame L 0rame for s"ort L proides numerous interestin$ capabi*ities t"at are not $enera**y usefu* as part of t"e Des(top ob/ect& 0or e3amp*e, t"e Tit*e and t"e Status)ndicator defined as part of t"e 0rame serice are of no use for t"e Des(top ob/ect because t"e Des(top ob/ect does not "ae a disp*ayed %indo%& T"ese properties are meanin$fu* on*y in a frame t"at contains a disp*ay %indo%& T"e des(top is a frame so t"at it can act as t"e root frame for a** t"e ot"er frames& TIP A*t"ou$" it is possib*e to use t"e des(top as a 0rame serice to enumerate t"e contained frames, t"e IDes(top interface is $enera**y more usefu* to enumerate t"e documents rat"er t"an t"e frames& ) usua**y access frames to obtain %indo% tit*es& 5se t"e $etActie0rame,. met"od of t"e des(top to obtain t"e actie frame ,see Listin$ 2!3.& T"e actie frame is t"e frame t"at contains t"e current focus& )f t"e current*y focused %indo% is not an 11o %indo%, $etActie0rame returns t"e *ast 11o frame t"at "ad t"e focus& Listing 243. 9rint the title of the current frame. Print Star-e#1top&etActi:e"ra!eBC&3itle 261 5se t"e $et0rames,. met"od to enumerate or searc" a** of t"e frames contained in t"e des(top& T"e $et0rames,. met"od returns an ob/ect t"at imp*ements t"e com&sun&star&frame&I0rames interface& A frame can contain ot"er frames7 t"e I0rames interface proides access to t"e contained frames& TIP 5se t"e fu** interface name to find t"e ;eb address for t"e A') information on t"e I0rames interface& )t is important t"at you *earn to find t"e ;eb pa$es on t"e A') site from t"e fu** serice or interface name& 12.1.1. The BIndex)ccess interface T"e I0rames interface is deried from t"e com&sun&star&container&I)nde3Access interface& As its name imp*ies, t"is interface a**o%s access to t"e contained frames usin$ a numeric inde3& 4umerous ot"er interfaces a*so derie from t"e I)nde3Access interface, a**o%in$ a simp*e numeric inde3 to access t"e contained e*ements& See Listin$ 2!! and 0i$ure MB& T"e s"eets ob/ect in a #a*c document a**o%s you to access eac" s"eet based on t"e inde3, or t"e name& TIP Learn "o% to use t"e I)nde3Access interface because 11o uses t"is serice in numerous ot"er p*aces& Listing 244. #isplay frame titles of open components. Sub -i#pla."ra!e3itle# -i! :"ra!e# A# Oariant )All o$ t(e $ra!e# -i! :"ra!e A# Oariant )A #inle $ra!e -i! i A# Inteer )Index to enu!erate t(e $ra!e# -i! # A# Strin )Contain# t(e #trin to print
:"ra!e# 6 Star-e#1top&et"ra!e#BC )Jet all o$ t(e $ra!e#
REM etCountBC return# t(e nu!ber o$ contained $ra!e# REM I$ t(ere are $our $ra!e#= t(en i (a# t(e :alue# >= '= %= and ? REM t(e etB.IndexBiC !et(od= (o*e:er= i# 8ero ba#ed& 3(i# !ean# REM t(at it re;uire# t(e :alue# 7= >= '= and % "or i 6 > 3o :"ra!e#&etCountBC :"ra!e 6 :"ra!e#&etB.IndexBi9>C # 6 # 4 CStrBi9>C 4 " : " 4 :"ra!e&3itle 4 CHRFB>7C Hext M#Box #= 7= ""ra!e 3itle#" End Sub Figure 79. itles of top4level frames. 12.1.2. +ind frames 1ith +rameearch+lag constants 5se t"e com&sun&star&frame&0rameSearc"0*a$ constants to searc" t"e 11o frames ,see Tab*e BA.& 0rameSearc"0*a$ constants are used to create an enumerated *ist of frames from t"e 8uery0rames,. met"od 262 defined in t"e I0rames interface& T"e 0rameSearc"0*a$ constants are a*so used to find a frame %"en *oadin$ a document and specifyin$ %"ic" frames %i** receie a dispatc"& )n ot"er %ords, you %i** see t"e 0rameSearc"0*a$ constants a$ain& Table 95. com.sun.star.frame.+rame*earch+lag constants. 4 %ame Description 0 A5T1 Deprecated& 5se 6 ? S2L0N#E)LDR24& 1 'AR24T )nc*ude t"e parent frame& 2 S2L0 )nc*ude t"is frame& ! #E)LDR24 )nc*ude t"e c"i*d frames of t"is frame& @ #R2AT2 #reate a frame if t"e re8uested frame is not found& 16 S)+L)4JS )nc*ude t"e c"i*d frames of t"e parent of t"is frame& 32 TAS<S )nc*ude a** frames in a** tas(s in t"e current frames "ierarc"y& 23 ALL )nc*ude a** frames e3cept TAS<S frames& 23 ? 1N2N!N16 ? 'AR24T N S2L0 N #E)LDR24 N S)+L)4JS& AA JL1+AL )nc*ude eery frame& AA ? 1N2N!N16N32 ? 'AR24T N S2L0 N #E)LDR24 N S)+L)4JS N TAS<S& T"e a*ues in Tab*e BA are enumerated constants& 11o "as enumerated a*ues for many different purposes& 6ou can access a** enumerated a*ues in 11o +asic in a simi*ar fas"ion& 2ac" constant "as an assi$ned name, as seen in t"e 4ame co*umn in Tab*e BA& 6ou can use t"is name by precedin$ it %it" com&sun&star&frame&0rameSearc"0*a$& 0or e3amp*e, use com&sun&star&frame&0rameSearc"0*a$&TAS<S to use t"e TAS<S constant ,see Listin$ 2!A.& T"e name of a constant proides meanin$fu* information %"i*e readin$ t"e +asic code& 5sin$ t"e constant a*ues direct*y, a*t"ou$" a**o%ed, obfuscates your code L in ot"er %ords, causes it to be *ess readab*e& TIP #onstant names are case sensitie t"e first time t"at t"ey are used& )f t"e t%o *ines in Listin$ 2!A are s%itc"ed, t"en a run9time error occurs because t"e ersion %it" t"e %ron$ case is found first& Listing 245. /onstant names are not case sensitive the second time they are used. Print co!&#un&#tar&$ra!e&"ra!eSearc("la&3AS^S )%' Print COM&S0H&S3AR&$ra!e&"ra!eSearc(",AJ&ta#^S )%' a Wor1# becau#e it i# alread. 1no*n& T"e a*ues in Tab*e BA are f*a$s t"at may be combined& 0or e3amp*e, t"e a*ues for ALL and JL1+AL e3ist on*y as a conenience7 t"ey are a combination of t"e ot"er f*a$s as s"o%n in Tab*e BA& 6ou can create your o%n a*ues if a suitab*e combination is not proided& 0or e3amp*e, to searc" ALL and to create a frame if it is not found, use t"e a*ue 31 ? 23 N @ ? ALL N #R2AT2& TIP 0rame searc" f*a$s are bit9f*a$s t"at can be combined by usin$ t"e 1R operator& )f you do not (no% %"at a bit9f*a$ is, /ust smi*e and nod& T"e code in Listin$ 2!6 uses t"e 0rameSearc"0*a$ constants to searc" t"e frames t"at are c"i*dren of t"e Des(top ob/ect& T"e output from Listin$ 2!6 dup*icates t"e output from Listin$ 2!! by obtainin$ a *ist of a** c"i*d frames from t"e Des(top ob/ect& 4ote t"at t"e return type from t"e 8uery0rames,. met"od is an array& ) (no% t"is because ) *oo(ed at t"e A') ;eb site& A*t"ou$" you can inspect t"e returned ob/ect to see %"at it 263 is, it isnGt possib*e to determine t"e a*ues of t"e ar$uments to t"e 8uery0rames,. met"od by inspection a*one& Listing 246. ;uery frames to get frame titles. Sub [uer."ra!e# -i! :"ra!e# A# Oariant )All o$ t(e $ra!e# -i! :"ra!e A# Oariant )A #inle $ra!e -i! i A# Inteer )Index to enu!erate t(e $ra!e# -i! # A# Strin )Contain# t(e #trin to print REM Call t(e ;uer."ra!e#BC !et(od on t(e /"ra!e# inter$ace& REM 3(i# ta1e# one aru!ent= a "ra!eSearc("la& REM 3(i# #earc(e# t(e c(ildren o$ t(e de#1top& :"ra!e# 6 Star-e#1top&et"ra!e#BC&;uer."ra!e#B5 co!&#un&#tar&$ra!e&"ra!eSearc("la&CHI,-REHC
"or i 6 ,BoundB:"ra!e#C 3o 0BoundB:"ra!e#C ) 3(e return :alue i# an arra.& # 6 # 4 :"ra!e#BiC&3itle 4 CHRFB>7C ) Append t(e title and a ne* line& Hext M#Box #= 7= ""ra!e 3itle#" ) -i#pla. t(e title#& End Sub TIP )n 11o 3&3&0, ) noticed t"at t"e frame tit*e differs for t"e "e*p %indo% %"en enumerated usin$ a 8uery& ) "ae not pursued e3act*y %"y& 12.2. 0he AEventBroadcaster interface ;"en certain important eents occur in 11o, t"e eent is broadcast to a** t"e ob/ects t"at re$ister as *isteners for a specific eent L for e3amp*e, to be notified before a document is c*osed& T"e com&sun&star&document&I2ent+roadcaster interface a**o%s t"e des(top to act as a broadcaster& T"e I2ent+roadcaster interface defines t"e met"ods add2entListener,. and remoe2entListener,. to add and remoe eent *isteners& T"ese t%o met"ods are not usua**y used direct*y because met"ods t"at are specific to t"e *istener are typica**y used& 0or e3amp*e, t"e #ontro**er ob/ect contains t"e met"ods add<eyEand*er,. and remoe<eyEand*er,. to add and remoe *isteners for (ey9press eents& 12.3. 0he A"es*top interface T"e com&sun&star&frame&IDes(top interface defines t"e primary functiona*ity of t"e Des(top serice& T"e des(top contains t"e top9*ee* components t"at can be ie%ed in a frame& )n ot"er %ords, it contains and contro*s t"e *ife cyc*e of t"e 1pen1ffice&or$ documents, "e*p %indo%, +asic )D2, and t"e ot"er component types& T"e des(top is a 0rame serice so t"at it can act as t"e root frame containin$ a** t"e ot"er frames& T"e des(top, t"erefore, "as access to and contro*s a** t"e ot"er frames& T"is contro* inc*udes t"e abi*ity to *oad documents and t"e abi*ity to c*ose a** frames and e3it 11o& 264 12.#.1. Closing the desktop and contained components To c*ose t"e des(top and a** t"e contained frames, ca** t"e terminate,. met"od& T"is met"od is not $uaranteed to c*ose t"e des(top7 it is mere*y a su$$estion ,or re8uest. t"at you %ou*d *i(e 11o to c*ose& +efore c*osin$, t"e des(top as(s eery ob/ect t"at as(ed to be notified before c*osin$ if it is 1< to c*ose& )f any *istener says no, t"en 11o %i** not terminate& 2ery open document re$isters as a terminate *istener and as(s you if you %ant to sae a document if it "as not yet been saed7 in case you %ondered "o% t"at %or(s& A** t"e 11o document types support t"e com&sun&star&uti*&I#*oseab*e interface& T"e I#*oseab*e interface defines t"e met"od Dc*ose,b0orce As +oo*ean.F& )f b0orce is 0a*se, t"e ob/ect may refuse to c*ose& )f b0orce is True, t"e ob/ect is not ab*e to refuse& Accordin$ to Mat"ias +auer, one of t"e *ead dee*opers, t"e Des(top ob/ect does not support t"e I#*oseab*e interface for *e$acy reasons& T"e terminate,. met"od %as used before it %as determined to be inade8uate for c*osin$ documents or %indo%s& )f t"e terminate,. met"od %as not a*ready imp*emented, t"en t"e des(top %ou*d a*so support t"e I#*oseab*e interface& T"e code in Listin$ 2!M demonstrates t"e safe %ay to c*ose a document usin$ any ersion of 11o& )f you (no% t"at your code %i** run on 11o 1&1 or *ater, you can simp*y use t"e c*ose,. met"od& Listing 247. he safe way to close a document using any version of OOo. I$ Ha#0noInter$ace#Bo-oc= "co!&#un&#tar&util&/Clo#eable"C 3(en o-oc&clo#eBtrueC El#e o-oc&di#po#eBC End I$ T"e code in Listin$ 2!M assumes t"at t"e ariab*e oDoc references an 11o document& Some component types do not support t"e I#*oseab*e interface& 1ne e3amp*e is t"e +asic )D2& T"e des(top contains met"ods to enumerate t"e current*y open components and to access t"e current component& T"ese met"ods are discussed s"ort*y& T"e dispose,. met"od automatica**y discards a document een if it is modified, %"i*e t"e c*ose,. met"od does not& 5se setModified,0a*se. to mar( a modified document as not modified, t"ereby preentin$ t"e c*ose,. met"od from comp*ainin$ t"at you are c*osin$ a modified document& 12.#.2. Enumerating components using BEnumeration)ccess 5sua**y, a component refers to an 11o document, but it may refer to ot"er t"in$s, suc" as t"e +asic )D2 or t"e inc*uded "e*p pa$es& 5se t"e $et#omponents,. met"od defined in t"e IDes(top interface to return an enumeration of t"e components contro**ed by t"e des(top& T"e returned ob/ect supports t"e interface com&sun&star&container&I2numerationAccess& TIP 11o "as many interfaces for returnin$ a *ist of ob/ects L some met"ods return an array of ob/ects& )n t"e des(top, I)nde3Access is used to enumerate frames and t"e I2numerationAccess interface is used to enumerate components& A component t"at is a*so an 11o document supports t"e IMode* interface& T"e mode* represents t"e under*yin$ document data, so if a component doesnGt support t"e IMode* interface, it isnGt an 11o document& )n ot"er %ords, supportin$ t"e IMode* interface imp*ies t"at a component "as data7 if it doesnGt "ae data, t"en it isnGt a document& 5se t"e Eas5no)nterfaces function to c"ec( eac" component to see if it is an 11o document& To find a specific document, searc" a** of t"e components and c"ec( t"e 5RL or some ot"er distin$uis"in$ c"aracteristic& 265 )t is possib*e t"at a document does not "ae a 5RL, in t"is case, t"e returned 5RL is an empty strin$& T"e subroutine 0i*e4ame1ut1f'at" fai*s %it" an empty strin$7 so 2numerate#omponent4ames c"ec(s for t"is case& Listing 248. #emonstrate how to enumerate components. Sub Enu!erateCo!ponentHa!e# -i! :Co!p# )Enu!eration acce## obNect -i! :Enu!erate )Enu!eration obNect -i! :Co!p )Sinle co!ponent -i! # A# Strin )-i#pla. #trin -i! #0R, A# Strin )-ocu!ent 0R,
REM ,oad t(e 3ool# librar. becau#e Strin# !odule contain# REM t(e $unction "ileHa!eOutO$Pat(BC JlobalScope&Ba#ic,ibrarie#&,oad,ibrar.B"3ool#"C
:Co!p#6Star-e#1top&etCo!ponent#BC)co!&#un&#tar&container&/Enu!erationAcce## I$ HO3 :Co!p#&(a#Ele!ent#BC 3(en )I do not (a:e to do t(i#= but Print "3(ere are no co!ponent#" )t(i# de!on#trate# t(at I can Exit Sub End I$
:Enu!erate 6 :Co!p#&createEnu!erationBC )co!&#un&#tar&container&/Enu!eration -o W(ile :Enu!erate&(a#MoreEle!ent#BC )Are t(ere an. ele!ent# to retrie:eU :Co!p 6 :Enu!erate&nextEle!entBC )Jet next ele!ent REM Onl. tr. to et t(e 0R, $ro! docu!ent co!ponent# REM 3(i# *ill #1ip t(e I-E= $or exa!ple I$ Ha#0noInter$ace#B:Co!p= "co!&#un&#tar&$ra!e&/Model"C 3(en #0R, 6 :Co!p&et0R,BC I$ #0R, 6 "" 3(en # 6 # 4 "ECo!ponent Wit( Ho 0R,D" 4 CHRFB>7C El#e # 6 # 4 "ileHa!eOutO$Pat(B#0R,C 4 CHRFB>7C End I$ End I$ ,oop M#Box #= 7= "-ocu!ent Ha!e#" End Sub 0i$ure @0, produced by Listin$ 6, *ists t"e fi*e names of a** current*y open documents& Figure 80. +ile names of currently open documents. 266 12.#.#. Current component 5se $et#urrent#omponent,. to return t"e current*y focused component, %"ic" is not necessari*y an 11o document& To obtain t"e most current document, use t"e $*oba**y defined ariab*e T"is#omponent& Listing 249. his/omponent references the current OOo document. Print 3(i#Co!ponent&et0R,BC )Wor1# $ro! Ba#ic I-E Print Star-e#1top&etCurrentCo!ponentBC&et0R,BC )"ail# $ro! Ba#ic I-E TIP StarDes(top&$et#urrent#omponent,. returns t"e current*y focused component& )f t"e +asic )D2 is open, t"e +asic )D2 component is returned& 5se t"e $*oba**y defined ariab*e T"is#omponent to return t"e most current document& Most of t"e macros t"at ) %rite are intended to modify t"e current document& +ecause of t"is, ) fre8uent*y use T"is#omponent& 12.#.$. Current component >again? A*t"ou$" StarDes(top&$et#urrent#omponent,. can be used in many situations, it is not a re*iab*e met"od to obtain t"e document t"at most recent*y "ad focus& T"e met"od $et#urrent#omponent,. returns eit"er t"e component t"at current*y "as focus, or t"e component t"at "ad t"e focus before contro* %as s%itc"ed to a different app*ication& T"is be"aior causes prob*ems %"en attemptin$ to debu$ +asic pro$rams, because t"e +asic )D2 is t"e current component& )t is t"erefore preferab*e to use T"is#omponent rat"er t"an StarDes(top&#urrent#omponent& 0orcin$ a ne% documentGs %indo% to become focused does not c"an$e t"e a*ue of T"is#omponent& T"e a*ue of T"is#omponent is set %"en t"e macro be$ins runnin$ and t"en it is not c"an$ed& Listing 250. Use one of these two methods to cause o#oc= to become the focused document. o-oc'&CurrentController&"ra!e&ContainerWindo*&to"rontBC o-oc'&CurrentController&"ra!e&Acti:ateBC TIP ;"en a macro is ca**ed because an eent occurred, T"is#omponent refers to t"e document t"at produced t"e eent un*ess t"e macro is contained in anot"er document& T"erefore, itGs better to p*ace $*oba* macros t"at %i** be ca**ed from ot"er documents inside a $*oba* *ibrary rat"er t"an inside a document& Macros may be ca**ed %"en certain eents occur ,per"aps as a re$istered eent "and*er.& ;"en a macro is ca**ed because an eent occurred, T"is#omponent refers to t"e document t"at produced t"e eent een if it isnGt t"e current*y focused document& T"e ariab*e T"is#omponent is aai*ab*e on*y from +AS)#& TIP )t is possib*e to run a macro %"en no document is open7 for obious reasons, t"e macro must reside in t"e app*ication *ibrary rat"er t"an in a document& 12.#.,. Current frame A*t"ou$" t"e 0rame serice a**o%s t"e des(top to enumerate t"e contained frames, it is t"e IDes(top interface t"at defines t"e met"od $et#urrent0rame,.& T"e $et#urrent0rame,. met"od returns t"e frame of t"e current*y focused component& TIP T"e component contained in t"e current frame may, or may not, be an 11o document& 267 T"e code in Listin$ 2A1 s"o%s one of many t"in$s you can do %it" t"e current frame& T"e macro obtains t"e current frame, t"e frame returns t"e current %indo%, and t"en t"e macro reduces t"e siCe of t"e current %indo%& Listing 251. *hrink the size of the current windows by =IR REM S(rin1 t(e current *indo* to 2<G o$ it# current #i8e& Sub S(rin1Windo*B.2< -i! :"ra!e )Current $ra!e -i! :Windo* )container *indo*
REM And t(i# i# a #truct t(at (old# a rectanle obNect REM I could (a:e al#o u#ed a Oariant or an ObNect to REM (old t(e return t.pe= but I 1no* *(at it i#= #o I REM de$ined t(e correct t.pe to (old it& -i! :Rect A# He* co!&#un&#tar&a*t&Rectanle
REM A# a #truct= t(e obNect i# copied b. :alue= not b. re$erence& REM 3(i# !ean# t(at I can !odi$. :Rect and it *ill not a$$ect REM t(e po#ition and #i8e o$ t(e *indo*& REM In !. te#t#= :Rect&/ and :Rect&P are 8ero= *(ic( i# *ron& REM :Rect&Widt( and :Rect&Hei(t are indeed correct& :Rect 6 :Windo*&etPo#Si8eBC
REM W(en #ettin t(e po#ition and #i8e= t(e la#t aru!ent #peci$ie# REM *(ic( o$ t(e aru!ent# to u#e& )co!&#un&#tar&a*t&Po#Si8e&/ Set onl. t(e /9po#ition )co!&#un&#tar&a*t&Po#Si8e&P Set onl. t(e P9po#ition )co!&#un&#tar&a*t&Po#Si8e&WI-3H Set onl. t(e Widt( )co!&#un&#tar&a*t&Po#Si8e&HEIJH3 Set onl. t(e Hei(t )co!&#un&#tar&a*t&Po#Si8e&POS Set onl. t(e Po#ition )co!&#un&#tar&a*t&Po#Si8e&SIVE Set onl. t(e Si8e )co!&#un&#tar&a*t&Po#Si8e&POSSIVE Set bot( t(e Po#ition and Si8e :Windo*&#etPo#Si8eB :Rect&/= :Rect&P= %*:Rect&Widt(+?= %*:Rect&Hei(t+?=5 co!&#un&#tar&a*t&Po#Si8e&SIVE C End Sub 12.4. .oad a document T"e des(top imp*ements t"e com&sun&star&frame&I#omponentLoader interface& T"is is a simp*e interface to *oad components from a 5RL& 5se t"e met"od Load#omponent0rom5r*,. defined in t"e I#omponentLoader interface to *oad an e3istin$ document or create a ne% one& co!&#un&#tar&lan&/Co!ponent loadCo!ponent"ro!0rlB Strin a0R,= Strin a3aret"ra!eHa!e= ,on nSearc("la#= #e;uenceE co!::#un::#tar::bean#::Propert.Oalue D aAr#C 268 T"e first ar$ument to t"e met"od Load#omponent0rom5r*,. specifies t"e 5RL of t"e document to *oad& To *oad an e3istin$ document, proide t"e 5RL of t"e document& 5se t"e function #onertTo5RL to conert a fi*e name e3pressed in an operatin$9system9specific format to a 5RL& Print Con:ert3o0R,B"c:\te!p\$ile&txt"C )$ile:+++c:+te!p+$ile&txt T"e 5RL may indicate a *oca* fi*e, or een a fi*e on t"e )nternet ,see Listin$ 2A2.& ) recommend obtainin$ a "i$"9speed )nternet connection before runnin$ t"is macro because it *oads a A009pa$e document& A*so, do not run t"is macro un*ess you "ae 11o 3&! or *ater, because %"en you c*ose Andre%Macro, it %i** cause 11o to cras"& Listing 252. Load document over &9. Sub ,oadMacro-oc"ro!Http -i! noAr#BC )An e!pt. arra. $or t(e aru!ent#& -i! :Co!p )3(e loaded co!ponent -i! #0R, A# Strin )0R, o$ t(e docu!ent to load #0R, 6 "(ttp:++***&piton.a1&or+Andre*Macro&odt" :Co!p 6 Star-e#1top&,oadCo!ponent"ro!0rlB#0R,= "5blan1"= 7= noAr#BCC End Sub 11o uses specia* 5RLs to indicate t"at a ne% document, rat"er t"an an e3istin$ document, s"ou*d be created& Table 96. URL* for creating new documents. *&L Docment Type Zpriate:factory-sca*cZ #a*c document Zpriate:factory-s%riterZ ;riter document Zpriate:factory-s%riter-%ebZ ;riter ETML ;eb document Zpriate:factory-s%riter-J*oba*DocumentZ Master document Zpriate:factory-sdra%Z Dra% document Zpriate:factory-smat"Z Mat" formu*a document Zpriate:factory-simpressZ )mpress presentation document Zpriate:factory-sc"artZ #"art Z&component:+ib*io$rap"y-Oie%1Z +ib*io$rap"y L 2dit t"e bib*io$rap"y entries Z&component:D+-_ueryDesi$nZ Z&component:D+-Tab*eDesi$nZ Z&component:D+-Re*ationDesi$nZ Z&component:D+-DataSource+ro%serZ Z&component:D+-0ormJridOie%Z Database components T"e macro in Listin$ 2A3 opens fie ne% documents L eac" in a ne% %indo%& ;"en ) *ast ran t"is in 11o 3&3, 11o seemed a bit confused as to %"ic" document s"ou*d "ae focus& Listing 253. /reate new documents. Sub ,oadE!pt.-ocu!ent# -i! noAr#BC )An e!pt. arra. $or t(e aru!ent# -i! :Co!p )3(e loaded co!ponent -i! #0R,#BC )0R,# o$ t(e ne* docu!ent t.pe# to load 269 -i! #0R, A# Strin )0R, o$ t(e docu!ent to load -i! i A# Inteer #0R,# 6 Arra.B"#calc"= "#*riter"= "#dra*"= "#!at("= "#i!pre##"C "or i 6 ,BoundB#0R,#C 3o 0BoundB#0R,#C #0R, 6 "pri:ate:$actor.+" 4 #0R,#BiC :Co!p 6 Star-e#1top&,oadCo!ponent"ro!0rlB#0R,= "5blan1"= 7= noAr#BCC Hext End Sub TIP 6ou can a*so *oad a document from a frame& ;"en a component ,document. is *oaded, it is p*aced into a frame7 t"e second ar$ument to Load#omponent0rom5r*,. specifies t"e name of t"e frame& )f a frame %it" t"e specified name a*ready e3ists, t"e ne%*y *oaded document uses t"e e3istin$ frame& T"e code in Listin$ 2A3 demonstrates t"e specia* frame name D=b*an(F L t"e specia* frame names are discussed s"ort*y& 0rame names t"at are not Dspecia*,F specify t"e name of an e3istin$ frame or a ne% frame& )f you specify a frame name, you must te** 11o "o% to find t"e frame& T"e a*ues in Tab*e BA enumerate a*id a*ues for t"e frame searc" f*a$s& )t used to be possib*e to specify t"e name of t"e frame t"at %i** contain a document ,but t"is "as not %or(ed since 11o 1&1&0.& Eere are a fe% items to note: 1& ;"en a document is *oaded, t"e frame name becomes somet"in$ *i(e D5ntit*ed 1 H 1pen1ffice&or$ ;riterF rat"er t"an t"e specified name& 2& )f you specify t"e frame name, t"e document %i** fai* to *oad if a frame %it" t"at name does not e3ist& )f t"e frame does e3ist, it %i** *oad it into a ne% frame& )f you e3periment %it" t"is, be certain to sae your documents before runnin$ t"e macro, at *east one e3periment caused t"e ne% document to *oad into t"e current frame& Listing 254. Open a document into an e.isting frame. Sub 0#eAnExi#tin"ra!e -i! noAr#BC )An e!pt. arra. $or t(e aru!ent# -i! :-oc )3(e loaded co!ponent -i! #0R, A# Strin )0R, o$ t(e docu!ent to load -i! nSearc( A# ,on )Searc( $la# -i! #"Ha!e A# Strin )"ra!e Ha!e -i! :"ra!e )-ocu!ent "ra!e -i! # A# Strin )-i#pla. #trin
REM Searc( loball. $or t(i# nSearc( 6 co!&#un&#tar&$ra!e&"ra!eSearc("la&J,OBA, W 5 co!&#un&#tar&$ra!e&"ra!eSearc("la&CREA3E
REM I can e:en open a real $ile $or t(i#= but I don)t 1no* *(at $ile# REM .ou (a:e on .our co!puter #o I create a ne* Writer docu!ent in#tead #0R, 6 "$ile:+++andre*7+(o!e+and.+doc>&odt" #0R, 6 "pri:ate:$actor.+#*riter"
REM Create a $ra!e *it( t(e na!e M."ra!e rat(er t(an 5de$ault #"Ha!e 6 "M."ra!e" :"ra!e 6 3(i#Co!ponent&CurrentController&"ra!e :-oc 6 :"ra!e&,oadCo!ponent"ro!0rlB#0R,= #"Ha!e= nSearc(= noAr#BCC 270 I$ I#HullB:-ocC 3(en Print ""ailed to create a docu!ent" Exit Sub End I$
REM 3(e na!e o$ t(e $ra!e i# M."ra!e& Hote t(at t(e na!e (a# not(in REM to do *it( t(e titleK #"Ha!e 6 :-oc&CurrentController&"ra!e&Ha!e # 6 "Created docu!ent to $ra!e " 4 #"Ha!e 4 CHRFB>7C M#Box #
REM 3(i# ti!e= do not allo* creation\ onl. allo* an exi#tin $ra!e nSearc( 6 co!&#un&#tar&$ra!e&"ra!eSearc("la&Jlobal #0R, 6 "$ile:+++andre*7+(o!e+and.+doc'&odt" #0R, 6 "pri:ate:$actor.+#calc" )#"Ha!e 6 "doc> a OpenO$$ice&or Writer" :-oc 6 :"ra!e&,oadCo!ponent"ro!0rlB#0R,= #"Ha!e= nSearc(= noAr#BCC I$ I#HullB:-ocC 3(en Print ""ailed to create a docu!ent" Exit Sub End I$ # 6 # 4 "Created docu!ent to $ra!e " 4 #"Ha!e M#Box # End Sub 11o uses specia* frame names to specify specia* be"aior ,seeTab*e BM.& 5se t"ese specia* frame names to cause t"e specified be"aior& Table 97. *pecial frame names. !rame %ame Description Z=b*an(Z #reates a ne% frame& Z=defau*tZ Detects an a*ready *oaded document or creates a ne% frame if it is not found& Z=se*fZ 5se or return t"is frame& ZZ 5se or return t"is frame& Z=parentZ 5se or return t"e direct parent of t"is frame& Z=topZ 5se or return t"e "i$"est *ee* parent frame& Z=beamerZ 5se or return a specia* subframe& A*t"ou$" you cannot current*y cause 11o to find a frame and use it, you can searc" for t"e frame %it" t"e desired name and t"en use t"at frame to *oad a document into t"at frame7 by usin$ t"e frame name D=se*fF& Listing 255. Reuse-+rame Sub 0#e"ra!eSel$ -i! noAr#BC )An e!pt. arra. $or t(e aru!ent# -i! :-oc )3(e loaded co!ponent -i! #0R, A# Strin )0R, o$ t(e docu!ent to load -i! nSearc( A# ,on )Searc( $la# -i! #"Ha!e A# Strin )"ra!e Ha!e -i! :"ra!e )-ocu!ent "ra!e 271 -i! # A# Strin )-i#pla. #trin
REM Searc( loball. $or t(i# nSearc( 6 co!&#un&#tar&$ra!e&"ra!eSearc("la&J,OBA, W 5 co!&#un&#tar&$ra!e&"ra!eSearc("la&CREA3E
REM I can e:en open a real $ile $or t(i#= but I don)t 1no* *(at $ile# REM .ou (a:e on .our co!puter #o I create a ne* Writer docu!ent in#tead #0R, 6 "$ile:+++andre*7+(o!e+and.+doc>&odt" #0R, 6 "pri:ate:$actor.+#*riter"
REM Create a $ra!e *it( t(e na!e M."ra!e rat(er t(an 5de$ault #"Ha!e 6 "M."ra!e" :"ra!e 6 3(i#Co!ponent&CurrentController&"ra!e :-oc 6 :"ra!e&,oadCo!ponent"ro!0rlB#0R,= #"Ha!e= nSearc(= noAr#BCC I$ I#HullB:-ocC 3(en Print ""ailed to create a docu!ent" Exit Sub End I$
REM 3(e na!e o$ t(e $ra!e i# M."ra!e& Hote t(at t(e na!e (a# not(in REM to do *it( t(e titleK #"Ha!e 6 :-oc&CurrentController&"ra!e&Ha!e # 6 "Created docu!ent to $ra!e " 4 #"Ha!e 4 CHRFB>7C M#Box #
REM 3(i# ti!e= do not allo* creation\ onl. allo* an exi#tin $ra!e #0R, 6 "$ile:+++andre*7+(o!e+and.+doc'&odt" #0R, 6 "pri:ate:$actor.+#calc" #"Ha!e 6 "5#el$" ) Jet a docu!ent)# $ra!e $ro! t(e docu!ent)# current controller& :-oc 6 :-oc&CurrentController&"ra!e&,oadCo!ponent"ro!0rlB#0R,= #"Ha!e= nSearc(= noAr#BCC I$ I#HullB:-ocC 3(en Print ""ailed to create a docu!ent" Exit Sub End I$ # 6 # 4 "Created docu!ent to $ra!e " 4 #"Ha!e M#Box # End Sub 12.$.1. -amed parameters T"e fina* ar$ument to t"e Load#omponent0rom5r*,. met"od is an array of structures of type com&sun&star&beans&'ropertyOa*ue& 2ac" property a*ue consists of a name and a a*ue& T"e properties are used to pass named parameters t"at direct 11o %"en it *oads t"e document& Tab*e B@ contains a brief description of t"e supported named parameters& TIP Tab*e B@ contains on*y named parameters t"at are not deprecated& T"e A') ;eb site on t"e com&sun&star&document&MediaDescriptor serice contains a comp*ete *ist of named parameters, deprecated and ot"er%ise& Some properties are not s"o%n, suc" as Aborted, because t"ey are set %"i*e *oadin$7 for e3amp*e, Aborted, %"ic" is set if an incorrect pass%ord is used& 272 Table 98. 3alid named parameters for loading and storing documents. Parameter Description AsTemp*ate A a*ue of True creates a ne% untit*ed document, een if t"e document is not a temp*ate& T"e defau*t *oads t"e temp*ate document for editin$& Aut"or Sets t"e current aut"or if t"e component can trac( t"e aut"or of t"e current ersion %"en t"e document is saed& #"aracterSet )dentifies t"e c"aracter set for sin$*e9byte c"aracters& #omment Simi*ar to Aut"or parameter, but sets t"e document description for ersion contro*& #omponentData A**o%s component9specific properties& DocumentTit*e Sets t"e Document tit*e& 0i*terData Additiona* properties for a fi*ter if it is re8uired& 0i*ter4ame 4ame of t"e fi*ter for *oadin$ or storin$ t"e component %"en not usin$ 11o types& 0i*ter1ptions Additiona* properties for a fi*ter if it is re8uired& T"ese a*ues must be strin$s and must be supported by t"e fi*ter& 5se 0i*terData for non9strin$ options& 0rame Specify t"e frame containin$ t"e document& Eidden A a*ue of 0a*se *oads t"e document so t"at it is "idden& Do not do t"is if you intend to ma(e t"e document isib*e after it is *oaded& Eierarc"ica*Document 4ame T"e "ierarc"ica* pat" to t"e embedded document from topmost container7 for e3amp*e, +ase forms are stored in t"e +ase document& )nputStream 6ou can specify an e3istin$ input stream for *oadin$ a document L for e3amp*e, if you "ae t"e document in memory and donGt %ant to %rite it to dis( first& )nteractionEand*er 'asses an interaction "and*er to "and*e errors and obtains a pass%ord if re8uired& KumpMar( Kumps to a mar(ed position after *oadin$ t"e component& A simi*ar t"in$ can be accomp*is"ed by appendin$ a VWV and t"e /ump mar( name in t"e 5RL used to open t"e document7 t"e synta3 %it" a VWV is not specified in most 5RL sc"emas& Macro23ecutionMode T"e numeric a*ue specifies if macros are e3ecuted %"en t"e document is *oaded ,Ta'le ((.& MediaType Specifies t"e M)M2 type of t"e data t"at %i** be *oaded& 1pen4e%Oie% A a*ue of True forces t"e component to create a ne% %indo% een if t"e document is a*ready *oaded& Some components support mu*tip*e ie%s for t"e same data& )f t"e opened component does not support mu*tip*e ie%s, a ne% %indo% is opened& )t is not a ie%, but mere*y t"e document *oaded one more time& 1utputStream )f used %"en storin$ a document ,not for readin$., t"e stream must be used to %rite t"e data& )f a stream is not proided, t"e *oader %i** create a stream by itse*f usin$ t"e ot"er properties& 1er%rite A a*ue of True oer%rites any e3istin$ fi*e %it" t"e same name %"i*e sain$& 'ass%ord 'ass%ord for *oadin$ or storin$ a document& )f a document t"at re8uires a pass%ord is *oaded and no pass%ord is specified, t"e document is not *oaded& 'ostData 'osts data to an ETT' address and t"en *oads t"e response as a document& 'ostData is usua**y used to obtain a resu*t from a ;eb form on a ;eb site& 'reie% A a*ue of True specifies t"at t"e document is *oaded for preie%& 11o may 273 Parameter Description ma(e some optimiCations %"en it opens a document in preie% mode& Read1n*y 1pens t"e document as read9on*y& Read9on*y documents are not modifiab*e from t"e user interface, but you can modify t"em by usin$ t"e 11o A') ,in ot"er %ords, from a macro.& Referer A 5RL indicatin$ t"e referrer %"o opened t"is document& ;it"out a referrer, a document t"at re8uires security c"ec(s is denied& ,6es, t"e parameter name is DReferer,F not DReferrer&F. Repair'ac(a$e 11o documents are stored in a compressed Cipped format& A a*ue of True attempts to recoer information from a dama$ed P)' fi*e& Start'resentation )f true, te**s t"e component *oadin$ t"e document t"at a presentation t"at is in t"e document is to be started ri$"t a%ay& Start'resentation )f t"e document contains a presentation, it is started immediate*y& Status)ndicator Oa*ue is an ob/ect to use as a pro$ress indicator as t"e document is *oaded or saed& Su$$estedSaeAsDir Specify t"e 5RL t"at is used ne3t time SaeAs dia*o$ is opened& Su$$estedSaeAs4ame Specify t"e su$$ested fi*e name t"at is used ne3t time SaeAs dia*o$ is opened& Temp*ate4ame 4ame of t"e temp*ate instead of t"e 5RL& Must a*so use t"e Temp*ateRe$ion4ame& Temp*ateRe$ion4ame 'at" to t"e temp*ate instead of t"e 5RL& Must a*so use t"e Temp*ate4ame& 5npac(ed Settin$ t"is to true means, donVt use a Cip fi*e to sae t"e document, use a fo*der instead ,on*y usab*e for 5#+ contents, t"at support fo*ders.& 5npac(ed 11o stores documents in a Cipped format& A a*ue of True stores t"e fi*e in a fo*der if it is supported for t"e component type& 5pdateDocMode T"e numeric a*ue specifies "o% t"e document is updated& See t"e A') site for t"e constant com&sun&star&document&5pdateDocMode& 5RL 0u**y 8ua*ified 5RL of t"e document to *oad, inc*udin$ t"e KumpDescriptor if re8uired& Oersion )f ersionin$ is supported for t"e component, t"is parameter indicates t"e ersion to *oad or sae& T"e main document is *oaded or saed if no ersion is specified& Oie%#ontro**er4ame ;"i*e *oadin$ a document into a frame, t"is specifies t"e name of t"e ie% contro**er to create& T"at is, t"e property is passed to t"e documentVs createOie%#ontro**er met"od& )f t"e *oaded document does not support t"e IMode*2 interface, t"e property is i$nored& Oie%Data T"e a*ue for t"is parameter is component specific and usua**y supp*ied by t"e frame contro**er& Oie%)d Some components support different ie%s of t"e same data& T"e a*ue specifies t"e ie% to use after *oadin$& T"e defau*t is Cero and is treated as t"e defau*t ie%& 274 12.$.2. !oading a template ;"i*e *oadin$ a document usin$ Load#omponent0rom5r*,., t"e 11o A') treats a** documents t"e same& 6ou can open an 11o temp*ate for editin$ ,c"an$in$ a temp*ate and t"en sain$ it as a ne% temp*ate. or you can use a temp*ate as t"e startin$ point for a ne% document& T"e named parameter AsTemp*ate directs 11o to open t"e specified document as a temp*ate rat"er t"an openin$ a document for editin$& T"e macro in Listin$ 2A6 opens a document as a temp*ate& Listing 256. Load a document as a template. Sub 0#e3e!plate REM 3(i# i# an arra. $ro! 7 3o 7 o$ t.pe Propert.Oalue -i! ar#B7C A# He* co!&#un&#tar&bean#&Propert.Oalue -i! #0R, A# Strin )0R, o$ t(e docu!ent to load #0R, 6 "$ile:+++(o!e+and.+doc>&ott" ar#B7C&Ha!e 6 "A#3e!plate" ar#B7C&Oalue 6 3rue Star-e#1top&,oadCo!ponent"ro!0rlB#0R,= "5blan1"= 7= ar#BCC End Sub T"e met"od Load#omponent0rom5r*,. assumes t"at a 5RL is used to specify t"e document *ocation7 t"is is not operatin$9system specific& A*t"ou$" ) ran t"e macro in Listin$ 2A6 on my Linu3 computer, it %i** %or( on a ;indo%s computer as %e**& 1n a ;indo%s computer, t"e 5RL usua**y inc*udes t"e drie *etter& #0R, 6 "$ile:++c:+(o!e+and.+doc>&ott" TIP 5se t"e functions #onert0rom5RL and #onertTo5RL to conert bet%een t"e operatin$9system9specific notation and 5RL notation& 12.$.#. Enabling macros 1hile loading a document ;"en a document t"at contains a macro is opened from t"e user interface ,5)., a security dia*o$ opens, as(in$ if macros s"ou*d be run& ;"en a document is *oaded from a macro usin$ t"e 11o A'), macros are disab*ed in t"e document& Some macros run based on eents t"at occur in a document& )f macros are disab*ed in t"e document, you can sti** manua**y run t"e contained macros, but t"e macros t"at are usua**y started from an eent in t"e document %i** neer run& T"e named parameter Macro23ecutionMode directs 11o "o% to treat macros %"en a document is *oaded& Tab*e BB enumerates t"e a*id a*ues for t"e Macro23ecutionMode parameter& Table 99. com.sun.star.document.Macro$.ecutionMode constants. 4 %ame Description 0 42O2R=2I2#5T2 A macro s"ou*d not be e3ecuted at a**& 1 0R1M=L)ST 23ecute macros from secure *ist 8uiet*y& 2 AL;A6S=2I2#5T2 23ecute any macro, macros si$ned %it" trusted sertificates and macros from secure *ist are e3ecuted 8uiet*y& 3 5S2=#140)J 5se confi$uration to retriee macro settin$s& )n case a user confirmation is re8uired a dia*o$ is output& ! AL;A6S=2I2#5T2=41=;AR4 A macro s"ou*d be e3ecuted a*%ays no conformation s"ou*d be proided& A 5S2=#140)J=R2K2#T=#140)RMAT)14 5se confi$uration to retriee macro settin$s& Treat cases %"en user 275 4 %ame Description confirmation re8uired as re/ected& 6 5S2=#140)J=A''R1O2=#140)RMAT)14 5se confi$uration to retriee macro settin$s& Treat cases %"en user confirmation re8uired as approed& M 0R1M=L)ST=41=;AR4 23ecute on*y macros from secure *ist& Macros t"at are not from t"e *ist are not e3ecuted& @ 0R1M=L)ST=A4D=S)J42D=;AR4 23ecute on*y macros from secure *ist or macros t"at are si$ned by trusted certificates& B 0R1M=L)ST=A4D=S)J42D=41=;AR4 23ecute on*y macros from secure *ist or macros t"at are si$ned by trusted certificates& 4o %arnin$-conformation s"ou*d be s"o%n& T"e macro in Listin$ 2AM *oads a document as a temp*ate and a**o%s macros to run %"en t"e document is *oaded& T"is macro a*so demonstrates t"at mu*tip*e named parameters can be used simu*taneous*y& Listing 257. Load a document as a template and enable contained macros. Sub 0#e3e!plateRunMacro REM 3(i# i# an arra. $ro! 7 3o > o$ t.pe Propert.Oalue -i! ar#B7C A# He* co!&#un&#tar&bean#&Propert.Oalue -i! #0R, A# Strin )0R, o$ t(e docu!ent to load Print co!&#un&#tar&docu!ent&MacroExecMode&0SE5COH"IJ #0R, 6 "$ile:+++(o!e+and.+doc>&#x*" ar#B7C&Ha!e 6 "A#3e!plate" ar#B7C&Oalue 6 3rue ar#B>C&Ha!e 6 "MacroExecutionMode" ar#B>C&Oalue 6 co!&#un&#tar&docu!ent&MacroExecMode&A,WAPS5E/EC03E5HO5WARH Star-e#1top&,oadCo!ponent"ro!0rlB#0R,= "5blan1"= 7= ar#BCC End Sub 12.$.$. Importing and exporting 1pen1ffice&or$ "as a type9detection mec"anism to determine a documentGs type %"en it is *oaded& T"is mec"anism "as been re*iab*e for t"e *imited number of document types t"at ) dea* %it" dai*y& Sometimes, "o%eer, you must specify t"e fi*ter name %"en importin$ a document& To e3port a document, you must a*%ays specify t"e e3port fi*ter type& T"e code in Listin$ 2A@ opens a Microsoft ;ord document& )n my testin$ t"e documents opened correct*y een %"en ) did not specify t"e fi*ter name& Listing 258. *pecify the filter name while loading a document. Sub ,oad-oc"ile -i! noAr#B7C A# He* co!&#un&#tar&bean#&Propert.Oalue -i! #0R, A# Strin noAr#B7C&Ha!e 6 ""ilterHa!e" noAr#B7C&Oalue 6 "Micro#o$t Word @2+'777+/P" #0R, 6 "$ile:+++(o!e+and.+one&doc" Star-e#1top&,oadCo!ponent"ro!0rlB#0R,= "5blan1"= 7= noAr#BCC End Sub 276 12.$.,. +ilter names 4e% fi*ters are fre8uent*y added to 11o, so it seems si**y to *ist t"e supported fi*ters, %"en a macro can retriee t"e *atest *ist& T"e fo**o%in$ macro creates a ne% #a*c document and t"en disp*ays t"e *ist of supported fi*ters& A recorded macro is used to format t"e data& T"e 5)4ame is t"e $enera* name7 or *oca*iCed name& T"e 4ame co*umn contains t"e interna* name to use %"en specifyin$ a fi*ter name for import or e3port& T"e )mport and 23port co*umns identify if t"e fi*ter can be used for import or e3port& T"e 1ptions co*umn, indicates if options can be passed to t"e fi*ter& T"ese options direct t"e fi*ter& ) too( t"e f*a$s=int2str function from an officia* 11o %eb site, but ) "ae not found t"e meanin$ of t"e f*a$s from anot"er *ocation, so ) modified it s*i$"t*y and dropped t"e code in p*ace "ere& T"e fi*ter names are a*so stored in t"e fi*e TypeDetection&3cu stored in t"e 11o confi$uration fo*ders& Listing 259. List supported filters in a /alc *heet. #ub "ilter#3oCalc -i! o"" ) "ilter"actor. #er:ice -i! o"ilterHa!e# ) Arra. o$ $ilter na!e#& -i! o-oc ) -ocu!ent created to (old t(e $ilter na!e#& -i! oS(eet ) S(eet t(at *ill (old t(e $ilter in$or!ation& -i! oCell ) Cell to update -i! iG ) Index Oariable& -i! $Prop#BC ) Propertie# $or eac( $ilter& -i! $pG ) "ilter propert. index -i! $pColG ) Colu!n $or t(e #peci$ied $ilter data& -i! #F ) Wor1 #trin t(at (old# #o!e propert. :alue#& -i! i0#er-ataG ) "or enu!eratin arra. propert. :alue#& -i! oProp ) A #inle propert.& -i! oArra.-ata ) Arra. o$ u#er propertie#& -i! #PropHa!e#B2C A# Strin -i! $la# A# ,on #PropHa!e#B7C 6 "Ha!e" #PropHa!e#B>C 6 "I!port" #PropHa!e#B'C 6 "Export" #PropHa!e#B%C 6 "Option#" #PropHa!e#B?C 6 "Oi#ible" #PropHa!e#B<C 6 ""la#" #PropHa!e#BAC 6 "-ocu!entSer:ice" #PropHa!e#B2C 6 "0IHa!e" o"" 6 create0noSer:iceB "co!&#un&#tar&docu!ent&"ilter"actor." C o"ilterHa!e# 6 o""&etEle!entHa!e#BC
) Create a Writer doc and #a:e t(e $ilter na!e# to it& o-oc 6 Star-e#1top&loadCo!ponent"ro!0R,B "pri:ate:$actor.+#calc"= "5blan1"= 7= Arra.BC C oS(eet 6 o-oc&etS(eet#BC&etB.IndexB7C )In#pect oS(eet
) Print t(e $ilter na!e# into a Writer docu!ent& "or i 6 ,BoundB o"ilterHa!e# C 3o 0BoundB o"ilterHa!e# C )oCell 6 oS(eet&etCellB.Po#itionB7= iW>C 277 )oCell&#etStrinBo"ilterHa!e#BiCC $Prop#BC 6 o""&etB.Ha!eBo"ilterHa!e#BiCC "or $p 6 ,BoundB$Prop#C 3o 0BoundB$Prop#C oCell 6 oS(eet&etCellB.Po#itionB$p= iW>C oProp 6 $Prop#B$pC $pCol 6 "indInArra.AddBoProp&Ha!e= #PropHa!e#C I$ $pCol D 0BoundB#PropHa!e#C 3(en Re-i! Pre#er:e #PropHa!e#B$pColC A# Strin #PropHa!e#B$pColC 6 oProp&Ha!e End I$
oCell 6 oS(eet&etCellB.Po#itionB$pCol= iW>C I$ Hot I#Arra.BoProp&OalueC 3(en oCell&#etStrinBoProp&OalueC I$ oProp&Ha!e 6 ""la#" 3(en $la# 6 oProp&Oalue oCell&#etStrinBCStrB$la#C 4 " 6 " 4 $la#5int'#trB$la#C I$ $la# and > 3(en oCell 6 oS(eet&etCellB.Po#itionB"indInArra.AddB"I!port"= #PropHa!e#C= iW>C oCell&#etStrinB"/"C Endi$ I$ $la# and ' 3(en oCell 6 oS(eet&etCellB.Po#itionB"indInArra.AddB"Export"= #PropHa!e#C= iW>C oCell&#etStrinB"/"C Endi$ I$ $la# and >'Q 3(en oCell 6 oS(eet&etCellB.Po#itionB"indInArra.AddB"Option#"= #PropHa!e#C= iW>C oCell&#etStrinB"/"C Endi$ I$ BB$la# and ?7@AC or B$la# and Q>@'CC 3(en oCell 6 oS(eet&etCellB.Po#itionB"indInArra.AddB"Oi#ible"= #PropHa!e#C= iW>C oCell&#etStrinB"/"C Endi$ End I$ El#eI$ ,BoundBoProp&OalueC E6 0BoundBoProp&OalueC 3(en # 6 "" oArra.-ata 6 oProp&Oalue "or i0#er-ata 6 ,BoundBoArra.-ataC 3o 0BoundBoArra.-ataC I$ Oar3.peBoArra.-ataBi0#er-ataCC 6 Q 3(en # 6 # 4 "BStrin:" 4 oArra.-ataBi0#er-ataC 4 "C" El#e # 6 # 4 "B" 4 oArra.-ataBi0#er-ataC&Ha!e 4 ":" 4 oArra.-ataBi0#er-ataC&Oalue 4 "C" End I$ Hext oCell&#etStrinB#C End I$ Hext Hext "or $p 6 ,BoundB#PropHa!e#C 3o 0boundB#PropHa!e#C oCell 6 oS(eet&etCellB.Po#itionB$p= 7C oCell&#etStrinB#Propna!e#B$pCC Hext "inal"or!atBo-ocC 278 End Sub $unction $la#5int'#trB$la# a# lonC a# #trin -i! c$la# a# lon -i! #tr:al a# #trin -i! cur"la A# ,on c$la# 6 $la# #tr:al 6 "" i$ c$la# and 4H7777777> t(en #tr:al 6 #tr:al W " I!port" c$la# 6 c$la#9> endi$ i$ c$la# and 4H7777777' t(en #tr:al 6 #tr:al W " Export" c$la# 6 c$la#9' endi$ i$ c$la# and 4H7777777? t(en #tr:al 6 #tr:al W " 3e!plate" c$la# 6 c$la#9? endi$ i$ c$la# and 4H7777777Q t(en #tr:al 6 #tr:al W " Internal" c$la# 6 c$la#9Q endi$ i$ c$la# and 4H777777>7 t(en #tr:al 6 #tr:al W " 3e!platePat(" c$la# 6 c$la#9>A endi$ i$ c$la# and 4H777777'7 t(en #tr:al 6 #tr:al W " O*n" c$la# 6 c$la#9%' endi$ i$ c$la# and 4H777777?7 t(en #tr:al 6 #tr:al W " Alien" c$la# 6 c$la#9A? endi$ i$ c$la# and 4H777777Q7 t(en #tr:al 6 #tr:al W " 0#eOption#" c$la# 6 c$la#9>'Q endi$ i$ c$la# and 4H77777>77 t(en #tr:al 6 #tr:al W " -e$ault" c$la# 6 c$la#9'<A endi$ i$ c$la# and 4H77777'77 t(en #tr:al 6 #tr:al W " Executable" c$la# 6 c$la#9<>' endi$ i$ c$la# and 4H77777?77 t(en #tr:al 6 #tr:al W " SupportSelection" c$la# 6 c$la#9>7'? 279 endi$ i$ c$la# and 4H77777Q77 t(en #tr:al 6 #tr:al W " Map3oAppPlu" c$la# 6 c$la#9'7?Q endi$ i$ c$la# and 4H7777>777 t(en #tr:al 6 #tr:al W " HotIn"ile-ialo" c$la# 6 c$la#9?7@A endi$ i$ c$la# and 4H7777'777 t(en #tr:al 6 #tr:al W " HotInC(oo#er" c$la# 6 c$la#9Q>@' endi$ i$ c$la# and 4H7777?777 t(en #tr:al 6 #tr:al W " Ac.nc(rona#" c$la# 6 c$la#9>A%Q? endi$ i$ c$la# and 4H7777Q777 t(en #tr:al 6 #tr:al W " Creator" c$la# 6 c$la#9%'2AQ endi$ i$ c$la# and 4H777>7777 t(en #tr:al 6 #tr:al W " Readonl." c$la# 6 c$la#9A<<%A endi$ i$ c$la# and 4H777'7777 t(en #tr:al 6 #tr:al W " HotIn#talled" c$la# 6 c$la#9>%>72' endi$ i$ c$la# and 4H777?7777 t(en #tr:al 6 #tr:al W " Con#ultSer:ice" c$la# 6 c$la#9'A'>?? endi$ i$ c$la# and 4H777Q7777 t(en #tr:al 6 #tr:al W " %rdPart."ilter" c$la# 6 c$la#9<'?'QQ endi$ i$ c$la# and 4H77>77777 t(en #tr:al 6 #tr:al W " Pac1ed" c$la# 6 c$la#9>7?Q<2A endi$ i$ c$la# and 4H77'77777 t(en #tr:al 6 #tr:al W " SilentExport" c$la# 6 c$la#9'7@2><' endi$ i$ c$la# and 4H77?77777 t(en #tr:al 6 #tr:al W " Bro*#erPre$erred" c$la# 6 c$la#9?>@?%7? endi$ i$ c$la# and 4H77Q77777 t(en #tr:al 6 #tr:al W " XH77Q77777Y" c$la# 6 c$la#9Q%QQA7Q endi$ 280
i$ c$la# and 4H7>777777 t(en #tr:al 6 #tr:al W " XH7>777777Y" c$la# 6 c$la#9>A222'>A endi$
i$ c$la# and 4H7'777777 t(en #tr:al 6 #tr:al W " XH7'777777Y" c$la# 6 c$la#9%%<<??%' endi$
i$ c$la# and 4H>7777777 t(en #tr:al 6 #tr:al W " Pre$erred" c$la# 6 c$la#9'AQ?%<?<A endi$ i$ c$la# ED 7 t(en #tr:al 6 #tr:al W " KKK A33EH3IOH: un#upported $la X"Wc$la#W"Y detected KKK" endi$ $la#5int'#tr 6 #tr:al end $unction "unction "indInArra.AddB#Ha!eF= na!eArra.C A# Inteer -i! i A# Inteer "or i 6 ,BoundBna!eArra.BCC 3o 0BoundBna!eArra.BCC )Print na!eArra.BiC 4 " and " 4 #Ha!e I$ na!eArra.BiC 6 #Ha!e 3(en "indInArra.Add 6 i Exit "unction End I$ Hext i 6 0BoundBna!eArra.BCC W > "indInArra.Add 6 i End "unction #ub "inal"or!atBo-ocC re! 9999999999999999999999999999999999999999999999999999999999999999999999 re! de$ine :ariable# -i! docu!ent a# obNect -i! di#patc(er a# obNect re! 9999999999999999999999999999999999999999999999999999999999999999999999 re! et acce## to t(e docu!ent docu!ent 6 o-oc&CurrentController&"ra!e di#patc(er 6 create0noSer:iceB"co!&#un&#tar&$ra!e&-i#patc(Helper"C re! 9999999999999999999999999999999999999999999999999999999999999999999999 -i! ar#>B7C a# ne* co!&#un&#tar&bean#&Propert.Oalue ar#>B7C&Ha!e 6 "3oPoint" ar#>B7C&Oalue 6 "FAF>" di#patc(er&execute-i#patc(Bdocu!ent= "&uno:Jo3oCell"= ""= 7= ar#>BCC 281 re! 9999999999999999999999999999999999999999999999999999999999999999999999 -i! ar#'B>C a# ne* co!&#un&#tar&bean#&Propert.Oalue ar#'B7C&Ha!e 6 "B." ar#'B7C&Oalue 6 > ar#'B>C&Ha!e 6 "Sel" ar#'B>C&Oalue 6 true di#patc(er&execute-i#patc(Bdocu!ent= "&uno:JoRi(t3oEndO$-ata"= ""= 7= ar#'BCC re! 9999999999999999999999999999999999999999999999999999999999999999999999 -i! ar#%B'C a# ne* co!&#un&#tar&bean#&Propert.Oalue ar#%B7C&Ha!e 6 ""ontHei(t&Hei(t" ar#%B7C&Oalue 6 >' ar#%B>C&Ha!e 6 ""ontHei(t&Prop" ar#%B>C&Oalue 6 >77 ar#%B'C&Ha!e 6 ""ontHei(t&-i$$" ar#%B'C&Oalue 6 7 di#patc(er&execute-i#patc(Bdocu!ent= "&uno:"ontHei(t"= ""= 7= ar#%BCC re! 9999999999999999999999999999999999999999999999999999999999999999999999 -i! ar#?B7C a# ne* co!&#un&#tar&bean#&Propert.Oalue ar#?B7C&Ha!e 6 "Bold" ar#?B7C&Oalue 6 true di#patc(er&execute-i#patc(Bdocu!ent= "&uno:Bold"= ""= 7= ar#?BCC re! 9999999999999999999999999999999999999999999999999999999999999999999999 -i! ar#<B7C a# ne* co!&#un&#tar&bean#&Propert.Oalue ar#<B7C&Ha!e 6 "Hori8ontalAlin!ent" ar#<B7C&Oalue 6 co!&#un&#tar&table&CellHoriMu#ti$.&CEH3ER di#patc(er&execute-i#patc(Bdocu!ent= "&uno:Hori8ontalAlin!ent"= ""= 7= ar#<BCC re! 9999999999999999999999999999999999999999999999999999999999999999999999 -i! ar#AB>C a# ne* co!&#un&#tar&bean#&Propert.Oalue ar#AB7C&Ha!e 6 "B." ar#AB7C&Oalue 6 > ar#AB>C&Ha!e 6 "Sel" ar#AB>C&Oalue 6 true di#patc(er&execute-i#patc(Bdocu!ent= "&uno:Jo-o*n3oEndO$-ata"= ""= 7= ar#ABCC re! 9999999999999999999999999999999999999999999999999999999999999999999999 -i! ar#2B7C a# ne* co!&#un&#tar&bean#&Propert.Oalue ar#2B7C&Ha!e 6 "aExtraWidt(" ar#2B7C&Oalue 6 '<? di#patc(er&execute-i#patc(Bdocu!ent= "&uno:SetOpti!alColu!nWidt("= ""= 7= ar#2BCC re! 9999999999999999999999999999999999999999999999999999999999999999999999 -i! ar#QBQC a# ne* co!&#un&#tar&bean#&Propert.Oalue ar#QB7C&Ha!e 6 "B.Ro*#" 282 ar#QB7C&Oalue 6 true ar#QB>C&Ha!e 6 "Ha#Header" ar#QB>C&Oalue 6 true ar#QB'C&Ha!e 6 "Ca#eSen#iti:e" ar#QB'C&Oalue 6 $al#e ar#QB%C&Ha!e 6 "IncludeAttrib#" ar#QB%C&Oalue 6 true ar#QB?C&Ha!e 6 "0#er-e$Index" ar#QB?C&Oalue 6 7 ar#QB<C&Ha!e 6 "Col>" ar#QB<C&Oalue 6 2 ar#QBAC&Ha!e 6 "A#cendin>" ar#QBAC&Oalue 6 true ar#QB2C&Ha!e 6 "Col'" ar#QB2C&Oalue 6 > ar#QBQC&Ha!e 6 "A#cendin'" ar#QBQC&Oalue 6 true di#patc(er&execute-i#patc(Bdocu!ent= "&uno:-ataSort"= ""= 7= ar#QBCC di#patc(er&execute-i#patc(Bdocu!ent= "&uno:Jo3oCell"= ""= 7= ar#>BCC end #ub 12.$... !oading and sa'ing documents T"e des(top or a frame is used to *oad a document& To store a document, use t"e met"od storeTo5RL,., %"ic" is imp*emented by t"e Document ob/ect& T"e first ar$ument to t"is met"od is t"e 5RL to %"ic" t"e document %i** be stored& T"e second ar$ument is an array of named parameters ,see Tab*e B@.& To e3port a document to a different type, t"e 0i*ter4ame must specify t"e document e3port type& T"e code in Listin$ 260 e3ports a ;riter document to a 'D0 fi*e& Listing 260. $.port the current document) assuming it is a 'riter document) as 9#+. -i! ar#B7C a# ne* co!&#un&#tar&bean#&Propert.Oalue ar#B7C&Ha!e 6 ""ilterHa!e" ar#B7C&Oalue 6 "*riter5pd$5Export" 3(i#Co!ponent&#tore3o0R,B"$ile:+++te#t&pd$"=ar#BCC TIP 0i*ter names are case sensitie& Some #a*c import and e3port fi*ters support options7 for e3amp*e, D)0, d+ase, and Lotus fi*ters a** use t"e same fi*ter option, a numeric inde3 t"at identifies %"ic" c"aracter set to use for sin$*e9byte c"aracters& Listing 261. he #"+) d!ase) and Lotus filters all use the same filter option. -i! ar#B>C a# ne* co!&#un&#tar&bean#&Propert.Oalue ar#B7C&Ha!e 6 ""ilterHa!e" ar#B7C&Oalue 6 "dBa#e" ar#B>C&Ha!e 6 ""ilterOption#" )Identi$. c(aracter #et $or #inle9b.te c(ar# ar#B>C&Oalue 6 7 )S.#te! c(aracter #et >> Eand*e #SO fi*es in t"e database section& 283 T"e discussion of t"e #SO fi*ter assumes fami*iarity %it" t"e #SO fi*e format& )f you arenGt fami*iar %it" t"is format, fee* free to s(ip t"is section& T"e Te3t #SO fi*ter, un*i(e t"e d+ase fi*ter, uses a comp*icated strin$ containin$ fie to(ens& 2ac" to(en can contain mu*tip*e a*ues separated by a s*as" mar( ,-.& T"e to(ens are t"en separated by a comma ,,.& Listing 262. he /*3 filter options are complicated. -i! ar#B>C a# ne* co!&#un&#tar&bean#&Propert.Oalue ar#B7C&Ha!e 6 ""ilterHa!e" ar#B7C&Oalue 6 "#calc: 3ext 9 txt 9 c#: BStarCalcC" ar#B>C&Ha!e 6 ""ilterOption#" ar#B>C&Oalue 6 "??=%?=7=>=>+<+'+>+%+>+?+>" T"e first to(en contains t"e fie*d separators as AS#)) a*ues& 0or e3amp*e, to specify a comma as t"e de*imiter, use t"e AS#)) a*ue !! ,see Listin$ 262.& To specify t"at some fie*ds are separated by a a space ,AS#)) 32. and some are separated by a tab ,AS#)) B., Listin$ 262 %ou*d use D32-B,3!,0,1,1-A-2-1-3-1-!-1F for t"e fi*ter options& )n a #SO fi*e, t"e te3t portions are usua**y surrounded by eit"er doub*e 8uotation mar(s ,Z. or sin$*e 8uotation mar(s ,V.& Listin$ 262 specifies t"at te3t portions s"ou*d be surrounded by doub*e 8uotation mar(s, usin$ an AS#)) a*ue of 3!& )f you %ant to use mu*tip*e te3t de*imiters, separate t"em %it" a s*as"& T"e t"ird to(en identifies t"e c"aracter set to use7 t"is is t"e same a*ue used to identify t"e c"aracter set in t"e D)0, d+ase, and Lotus fi*ters& T"e code in Listin$ 262 specifies a Cero for t"e c"aracter set& T"e fourt" to(en identifies t"e first *ine to import L typica**y *ine one& Listin$ 20 specifies t"at t"e first *ine of te3t s"ou*d be input& T"e *ast to(en identifies t"e format of eac" co*umn in t"e #SO fi*e& T"e co*umns can be formatted as eit"er de*imited te3t ,see Listin$ 263. or as fi3ed9%idt" te3t ,see Listin$ 26!.& Listing 263. #elimited4te.t4format string for the /*3 filter. E$ield5nu!D+E$or!atD+E$ield5nu!D+E$or!atD+E$ield5nu!D+E$or!atD+&&& T"e [fie*d=numR is an inte$er t"at identifies a fie*d, %"ere 1 is t"e *eftmost fie*d& 0or e3amp*e, $ien t"e fie*ds DoneF, Dt%oF, and Dt"reeF, a fie*d=num of 2 refers to Dt%oF& T"e [formatR is an inte$er t"at identifies t"e format of t"e fie*d ,see Ta'le )**.& T"e code in Listin$ 262 specifies t"at fie*ds one t"rou$" four use a format of 1, %"ic" is t"e standard format& Table 100. /*3 field format values. !ormat Description 1 Standard 2 Te3t 3 MM-DD-66 ! DD-MM-66 A 66-MM-DD B Do not import7 i$nore t"is fie*d& 10 )mport a number formatted in t"e 5S92n$*is" *oca*e re$ard*ess of t"e current *oca*e& 284 Listing 264. +i.ed4width4columns format string for the /*3 filter. "I/+E#tartD+E$or!atD+E#tartD+E$or!atD+E#tartD+E$or!atD+&&& Te** t"e fi*ter t"at t"e fi*e uses a fi3ed9%idt" format by usin$ t"e te3t D0)IF as t"e first portion of t"e *ast to(en& 0i3ed9%idt" #SO fi*es identify fie*ds by specifyin$ %"ere eac" fie*d starts ,see Listin$ 26!.& T"e [startR a*ue specifies t"e first c"aracter in a fie*d& A start of 0 refers to t"e *eftmost c"aracter of t"e te3t& T"e [formatR is an inte$er t"at identifies t"e format of t"e te3t ,see Tab*e 100.& 12.$./. Error handling 1hile loading a document 23ceptions are not t"ro%n %"i*e *oadin$ a document7 instead, errors are t"ro%n usin$ an interaction "and*er t"at is passed as a named parameter& 5nfortunate*y, you cannot imp*ement an 11o +asic interaction "and*er& T"e 11o Dee*operGs Juide, "o%eer, "as e3amp*es of error "and*ers usin$ ot"er *an$ua$es& )n ot"er %ords, in +AS)#, you cannot trap errors %"i*e *oadin$ a document7 t"e document simp*y fai*s to *oad and returns nu**& T"e Jrap"ica* 5ser )nterface ,J5). proides an interaction "and*er t"at interacts %it" t"e user& T"e J5)Gs interaction "and*er disp*ays error messa$es %"en errors occur and prompts t"e user for a pass%ord if it is re8uired& )f no "and*er is inc*uded as a named parameter, a defau*t "and*er is used& T"e defau*t "and*er simp*y i$nores most errors, proidin$ *itt*e feedbac( to t"e user& 12.. Conclusion T"e des(top acts as t"e main app*ication t"at contro*s 1pen1ffice&or$, so %"en you need to obtain somet"in$ t"at is $*oba**y re*ated to t"e documents or frames, *oo( at t"e des(top& T"e $*oba**y aai*ab*e ariab*es StarDes(top and T"is#omponent proide easy access to t"e 11o Des(top ob/ect and t"e current document& T"is c"apter introduced tec"ni8ues for accessin$ containers %it" mu*tip*e ob/ects& 0ami*iariCe yourse*f %it" t"e basic capabi*ities for openin$ documents, for importin$ and e3portin$ fi*e types, and t"e capabi*ities and *imitations of 11o, in order to e3pand your abi*ity to use and create a %ide ariety of fi*e types %it"in t"e 11o enironment& 285 1#. Generic (ocument Methods 1pen1ffice&or$ supports si3 primary document types: te3t, spreads"eet, dra%in$, mat", database, and presentation& T"e different document types s"are si$nificant functiona*ity and interfaces, suc" as accessin$ t"e document mode*, printin$, and sain$& T"is c"apter introduces common tas(s across a** of t"e document types& 2ery document contains data t"at can be manipu*ated and printed& 0or e3amp*e, t"e primary data in a ;riter document is te3t, but it can a*so contain tab*es and $rap"ics& T"e data mode* consists of t"is under*yin$ data t"at can be manipu*ated independent*y of "o% it is disp*ayed& To manipu*ate t"e data by means of a macro, you manipu*ate t"e data mode* direct*y& A*t"ou$" you can use t"e dispatc"er to indirect*y manipu*ate t"e data, t"e c"an$es are sti** made direct*y to t"e mode*& A typica* usa$e of t"e dispatc"er is to paste t"e c*ipboard contents into t"e document ,see #"apter 11& T"e Dispatc"er.& T"e data mode* contains a #ontro**er ob/ect, %"ic" manipu*ates t"e isua* presentation of t"e data& T"e contro**er doesnGt c"an$e t"e data7 it on*y contro*s "o% t"e document is presented& T"e contro**er interacts direct*y %it" t"e user interface to contro* t"e *ocation of t"e disp*ayed cursor, to contro* %"ic" pa$e is disp*ayed, and to se*ect portions of t"e document& 5se t"e contro**er to determine disp*ay9re*ated information suc" as t"e current pa$e or t"e current*y se*ected te3t& TIP 11o supports a mode ca**ed D"ead*ess,F %"ic" "as no startup screen, no defau*t document, no user interface, and supports no user interaction& ,5se Dsoffice 9>F to see a *ist of supported modes&. )f 11o is started in "ead*ess mode, t"ere is no disp*ay component& T"erefore, a contro**er is not re8uired and may not e3ist& )f itGs possib*e for your macro to run on 11o in "ead*ess mode, you must c"ec( t"e contro**er to see if it is nu** before usin$ it& 13.1. /ervice Manager 1pen1ffice&or$ "as a $enera* $*oba* serice mana$er, %"ic" is used to create and obtain instances of $enera* 541 serices& A serice mana$er accepts a strin$ t"at identifies a type of ob/ect, and it returns an instance of t"at ob/ect& T"e $*oba* serice mana$er is made aai*ab*e in 11o +asic t"rou$" t"e function create5noSerice,Strin$.& T"e $*oba* serice mana$er returns $enera* ob/ects suc" as a dispatc" "e*per or an ob/ect for simp*e fi*e access& Listing 265. Use the global service manager. o-i#patc(er 6 create0noSer:iceB"co!&#un&#tar&$ra!e&-i#patc(Helper"C oSi!ple"ileAcce## 6 create0noSer:iceB"co!&#un&#tar&ucb&Si!ple"ileAcce##"C Documents are a serice mana$er to create ob/ects t"at t"ey contain ,or t"at are direct*y re*ated to t"e document.7 for e3amp*e, a ;riter document is ab*e to create a te3t tab*e or te3t fie*d t"at can be inserted into t"e document& )n $enera*, ob/ects t"at %ere not created by a document cannot be inserted into t"e document& A ;riter document is unab*e to return $*oba* ob/ects, and t"e $*oba* serice mana$er is unab*e to return ob/ects t"at are t"en inserted into a document& Listing 266. Use a document as a service manager. REM ,et t(e docu!ent create t(e text table& o3able 6 o-oc&createIn#tanceB "co!&#un&#tar&text&3ext3able" C o3able&initiali8eB%= 'C )3(ree ro*#= t*o colu!n# REM Ho* in#ert t(e text table at t(e end o$ t(e docu!ent& o-oc&3ext&in#ert3extContentBo-oc&3ext&etEndBC= o3able= "al#eC 286 13.2. /ervices and interfaces T"in( of an 11o component as a %indo% o%ned by t"e des(top& 5se t"e Des(top ob/ect to enumerate t"e components, inc*udin$ documents, t"e +asic )D2 and t"e "e*p %indo% a*on$ %it" t"e actua* documents& )f a component supports t"e com&sun&star&frame&IMode* interface, t"e component is a document ,rat"er t"an t"e +asic )D2 or t"e "e*p %indo%.& 2ery document supports t"e IMode* interface and eac" document type "as a uni8ue serice t"at it supports ,see Tab*e 101.& 5se Eas5no)nterfaces to determine if an ob/ect supports t"e IMode* interface7 t"en use t"e ob/ect met"od supportsSerice to determine t"e document type& TIP T"e met"od supportsSerice,. is defined by t"e com&sun&star&*an$&ISerice)nfo interface& T"is interface a*so defines t"e met"od $et)mp*ementation4ame,., %"ic" returns a uni8ue strin$ identifyin$ t"e ob/ect type& able (C(. Uni8ue services that identify the documentSs type. Service Docment Type com&sun&star&te3t&Te3tDocument ;riter te3t document& com&sun&star&s"eet&Spreads"eetDocument #a*c spreads"eet document& com&sun&star&dra%in$&Dra%in$Document Dra% dra%in$ document& com&sun&star&presentation&'resentationDocument )mpress presentation document& com&sun&star&formu*a&0ormu*a'roperties Mat" formu*a document& com&sun&star&comp&dba&1DatabaseDocument +ase Document 11o contains numerous interfaces t"at are used by many ,if not a**. of t"e document types& #onsider t"is partia* *ist of common interfaces& Interface Description com&sun&star&beans&I'ropertySet Jet and set ob/ect properties& com&sun&star&container&I#"i*d 0or ob/ects %it" a sin$*e parent, $et and set t"at parent& com&sun&star&datatransfer&ITransferab*e Jet data for data transfer7 *i(e copyin$ to t"e c*ipboard& com&sun&star&document&IDocument'ropertiesSupp*ier Access a documents properties7 for e3amp*e, aut"or and creation date& com&sun&star&document&IDocument2ent+roadcaster Re$ister to be notified %"en eents occur& com&sun&star&document&I2entsSupp*ier Jet a *ist of eents supported by t"is ob/ect& com&sun&star&document&ILin(Tar$etSupp*ier Jet t"e *ist of *in( tar$ets in a document& com&sun&star&document&IOie%DataSupp*ier Jet properties describin$ a documentVs open ie%s& com&sun&star&dra%in$&IDra%'a$esSupp*ier Jet dra% pa$es for documents t"at support mu*tip*e dra% pa$es7 for e3amp*e, a dra%in$ or a presentation& com&sun&star&frame&ILoadab*e 0unctiona*ity to *oad documents& com&sun&star&frame&IMode* Representation of a resource ,document. in t"e sense t"at it %as created-*oaded from a resource7 off "and, ) am not a%are of any document t"at does not imp*ement IMode*& T"is interface a*so proides access to t"e mode*Vs components& com&sun&star&frame&IStorab*e Met"ods to store a document& com&sun&star&*an$&I#omponent A**o%s an ob/ect to o%n and dispose ,free. an ob/ect7 for 287 e3amp*e, a te3t tab*e& com&sun&star&*an$&I2entListener +ase interface for a** *isteners7 proides a disposin$ met"od& com&sun&star&*an$&IMu*tiSerice0actory )mp*emented by factories to create ob/ects and determine %"at ob/ects t"e factor can create& com&sun&star&*an$&ISerice)nfo Determine %"ic" serices an ob/ect supports& com&sun&star&*an$&IType'roider Determine t"e types ,interfaces. an ob/ect supports& com&sun&star&script&IStar+asicAccess Deprecated, but proides access to *ibraries& com&sun&star&sty*e&ISty*e0ami*iesSupp*ier Jet sty*e fami*ies supported by a document7 for e3amp*e, para$rap" sty*es& com&sun&star&uti*&I#*ose+roadcaster A**o%s an ob/ect to eto a c*ose re8uest& com&sun&star&uti*&I#*oseab*e As( a document to c*ose7 t"is is preferred to dispose& com&sun&star&uti*&IModifiab*e Determine if a document "as been modified& com&sun&star&uti*&IModify+roadcaster Re$ister and be notified %"en a document is modified& com&sun&star&uti*&I4umber0ormatsSupp*ier Jet t"e documentVs number formats& com&sun&star&ie%&I'rintKob+roadcaster Re$ister and be notified about print pro$ress& com&sun&star&ie%&I'rintab*e Document print functiona*ity& com&sun&star&ie%&IRenderab*e 0unctiona*ity to render a document& )ronica**y, searc"in$ is not supported by a** document types& T"is is because searc"in$ functiona*ity is ery specific to t"e document& 0or e3amp*e, searc"in$ a te3t document is ery different t"an searc"in$ a spreads"eet ,in terms of desired options.& )n #a*c, searc"in$ is proided by t"e eac" s"eet rat"er t"an by t"e document& A #a*c document is composed of mu*tip*e spreads"eets& A si$nificant portion of t"e functiona*ity, t"erefore, e3ists in t"e spreads"eet ob/ects rat"er t"an in t"e parent #a*c document& 0or e3amp*e, searc"in$ te3t or obtainin$ dra% pa$es bot" e3ist in spreads"eet ob/ects L dra% pa$es are discussed in dept" in >>#"apter 1A, DDra% And )mpress Documents&F T"e 1pen1ffice&or$ A') ;eb site contains e3tensie, detai*ed "e*p on most of t"e serices and interfaces& T"e pa$e is bui*t by startin$ %it" t"e ;eb address D"ttp:--api&openoffice&or$-docs-common-ref-F and t"en usin$ t"e interface name to bui*d t"e rest of t"e address& 0or e3amp*e, t"e com&sun&star&beans&I'ropertySet interface "as an )nternet address as fo**o%s: (ttp:++api&openo$$ice&or+doc#+co!!on+re$+co!+#un+#tar+bean#+/Propert.Set&(t!l 13.3. 5etting and setting properties T"e db$=properties property is a strin$ containin$ a *ist of properties supported t"e ob/ect containin$ t"e property7 you s"ou*d read t"at *ast sentence a$ain& 11o +asic automatica**y ma(es t"ese properties aai*ab*e for direct access7 ot"er *an$ua$es may not& T"e com&sun&star&beans&I'ropertySet interface proides met"ods to $et, set, and enumerate t"e ob/ectGs properties, as s"o%n in Tab*e 102& 288 able (C=. Ob%ect methods defined by the interface :9roperty*et. O27ect )et6od Description $et'ropertySet)nfo,. Return an ob/ect supportin$ t"e com&sun&star&beans&I'ropertySet)nfo interface& T"is ob/ect describes t"e ob/ectGs properties but may be nu**& set'ropertyOa*ue,name, a*ue. Set t"e a*ue of t"e named property& A *istener may eto t"is c"an$e& $et'ropertyOa*ue,name. Return t"e a*ue of t"e named property& add'roperty#"an$eListener,name, *istener. Add an I'roperty#"an$eListener for t"e named property& An empty name *istens for a** properties& remoe'roperty#"an$eListener,name, *istener. Remoe an I'roperty#"an$eListener& addOetoab*e#"an$eListener,name, *istener. Add an IOetoab*e#"an$eListener for t"e named property& An empty name *istens for a** properties& remoeOetoab*e#"an$eListener,name, *istener. Remoes an IOetoab*e#"an$eListener& )n 11o +asic, properties are usua**y accessed direct*y& Listin$ 26M demonstrates t%o %ays to obtain t"e #"ar0ont4ame property from a ;riter document L t"ese met"ods return t"e name of t"e font sty*e& Listing 267. wo methods to obtain the name of the font style. Print 3(i#Co!ponent&C(ar"ontHa!e Print CStrB3(i#Co!ponent&etPropert.OalueB"C(ar"ontHa!e"CC Accessin$ t"e property direct*y is t"e most e3pedient met"od %"i*e usin$ 11o +asic, but t"ere are adanta$es to usin$ t"e met"ods defined by t"e I'ropertySet)nfo interface& Some properties are defined as optiona*, so not eery document contains eery property& T"e I'ropertySet)nfo interface defines t"e ob/ect met"od "as'roperty+y4ame,., %"ic" can be used to test for t"e e3istence of a property before use7 errors can sti** be aoided by usin$ error9"and*in$ routines& Anot"er use is to $enerica**y enumerate a** of t"e contained properties and possib*y t"eir a*ues as s"o%n in Listin$ 26@& 0i$ure @1 s"o%s some properties of a ;riter document usin$ t"e macro in Listin$ 26@& Listing 268. #isplay general document properties. Sub etPropert.Oalue# -i! :PropIn$o )Propert.SetIn$o obNect -i! :Prop# )Arra. o$ propertie# -i! :Prop )co!&#un&#tar&bean#&Propert. -i! : )Oalue o$ a #inle propert. -i! iG )Index :ariable -i! #F )Jeneral !e##ae #trin -i! nCountG
REM ObNect i!ple!ent# inter$ace co!&#un&#tar&bean#&/Propert.SetIn$o :PropIn$o 6 3(i#Co!ponent&etPropert.SetIn$oBC REM #e;uenceE Propert. D :PropIn$o&etPropertie#BC REM Propert. :PropIn$o&etPropert.B.Ha!eBna!eC REM boolean :PropIn$o&(a#Propert.B.Ha!eBna!eC :Prop# 6 :PropIn$o&etPropertie#BC "or i 6 7 3o 0BoundB:Prop#C I$ nCount 6 %7 3(en nCount 6 7 289 M#Box #= 7= "Propertie#" # 6 "" End I$ nCount 6 nCount W > :Prop 6 :Prop#BiC )co!&#un&#tar&bean#&Propert. # 6 S 4 :Prop&Ha!e 4 " 6 " : 6 3(i#Co!ponent&etPropert.OalueB:Prop&Ha!eC I$ I#HullB:C 3(en # 6 S 4 "Hull" El#eI$ I#E!pt.B:C 3(en # 6 S 4 "E!pt." El#eI$ Oar3.peB:C E @ 3(en # 6 S 4 CStrB:C El#e # 6 S 4 "ObNect or Arra." End I$ # 6 S 4 CHRFB>7C Hext M#Box #= 7= "Propertie#" End Sub Figure 81. he first (C properties of his/omponent. TIP )n case you missed t"e imp*ications of t"e macro in Listin$ 26@, it a**o%s you to $enerica**y inspect any ob/ect t"at supports t"e I'ropertySet interface& T"e abi*ity to inspect an ob/ect is ina*uab*e %"en you arenGt certain %"at you can do %it" an ob/ect& After $ettin$ a property set information ob/ect, 5se $et'roperties,. to $et an array of 'roperty ob/ects& 5se "as'roperty,name. to determine if a property e3ists& 5se $et'roperty+y4ame,name. to $et a specific property& 13.4. "ocument properties Document properties contain information re*ated to t"e document suc" as t"e aut"or and creation time7 as opposed to t"e properties discussed in t"e preious section t"at are re*ated to t"e document contents suc" as t"e current font& 290 'reious met"ods for obtainin$ document properties "ae been deprecated7 for e3amp*e, usin$ $etDocument)nfo to obtain and modify user fie*ds& 5se +ile Properties to open t"e document properties dia*o$& 5se $etDocument'roperties to obtain t"e Document'roperties ob/ect& Listing 269. Use the #ocument9roperties ob%ect. ) co!&#un&#tar&docu!ent&-ocu!entPropertie# print-ocPropertie#B3(i#Co!ponent&et-ocu!entPropertie#BCC End Sub Sub print-ocPropertie#Bo-ocProp#C -i! #F -i! o-ata
# 6 "Aut(or : " 4 o-ocProp#&Aut(or 4 CHRFB>7C 4 5 "AutoloadSec# : " 4 o-ocProp#&AutoloadSec# 4 CHRFB>7C 4 5 "Autoload0R, : " 4 o-ocProp#&Autoload0R, 4 CHRFB>7C 4 5 "-e$ault3aret : " 4 o-ocProp#&-e$ault3aret 4 CHRFB>7C 4 5 "-e#cription : " 4 o-ocProp#&-e#cription 4 CHRFB>7C 4 5 "EditinC.cle# : " 4 o-ocProp#&EditinC.cle# 4 CHRFB>7C 4 5 "Editin-uration : " 4 5 #econd#A#Prett.3i!eBo-ocProp#&Editin-urationC 4 CHRFB>7C 4 5 "Jenerator : " 4 o-ocProp#&Jenerator 4 CHRFB>7C 4 5 "Modi$iedB. : " 4 o-ocProp#&Modi$iedB. 4 CHRFB>7C 4 5 "3itle : " 4 o-ocProp#&3itle 4 CHRFB>7C 4 5 ",anuae : " 4 o-ocProp#&,anuae&Countr. 4 ":" 4 5 o-ocProp#&,anuae&,anuae 4 CHRFB>7C 4 5 "Modi$ication-ate : " 4 o-ocProp#&Modi$ication-ate&-a. 4 "+" 4 5 o-ocProp#&Modi$ication-ate&Mont( 4 "+" 4 5 o-ocProp#&Modi$ication-ate&Pear 4 " " 4 5 o-ocProp#&Modi$ication-ate&Hour# 4 ":" 4 5 o-ocProp#&Modi$ication-ate&Minute# 4 ":" 4 5 o-ocProp#&Modi$ication-ate&Second# 4 "&" 4 5 o-ocProp#&Modi$ication-ate&Hundredt(Second# 4 CHRFB>7C 4 5 "Print-ate : " 4 o-ocProp#&Print-ate&Mont( 4 "+" 4 5 o-ocProp#&Print-ate&-a. 4 "+" 4 5 o-ocProp#&Print-ate&Pear 4 " " 4 5 o-ocProp#&Print-ate&Hour# 4 ":" 4 5 o-ocProp#&Print-ate&Minute# 4 ":" 4 5 o-ocProp#&Print-ate&Second# 4 "&" 4 5 o-ocProp#&Print-ate&Hundredt(Second# 4 CHRFB>7C 4 5 "PrintedB. : " 4 o-ocProp#&PrintedB. 4 CHRFB>7C 4 5 "SubNect : " 4 o-ocProp#&SubNect 4 CHRFB>7C 4 5 "3e!plate-ate : " 4 o-ocProp#&3e!plate-ate&Mont( 4 "+" 4 5 o-ocProp#&3e!plate-ate&-a. 4 "+" 4 5 o-ocProp#&3e!plate-ate&Pear 4 " " 4 5 o-ocProp#&3e!plate-ate&Hour# 4 ":" 4 5 o-ocProp#&3e!plate-ate&Minute# 4 ":" 4 5 o-ocProp#&3e!plate-ate&Second# 4 "&" 4 5 o-ocProp#&3e!plate-ate&Hundredt(Second# 4 CHRFB>7C 4 5 "3e!plateHa!e : " 4 o-ocProp#&3e!plateHa!e 4 CHRFB>7C 4 5 "3e!plate0R, : " 4 o-ocProp#&3e!plate0R, 4 CHRFB>7C 4 5 "3itle : " 4 o-ocProp#&3itle 4 CHRFB>7C 291 M#Box #= 7= "-ocu!ent Propertie#" -i! iG o-ata 6 o-ocProp#&-ocu!entStati#tic# # 6 "" "or i 6 ,BoundBo-ataC 3o 0BoundBo-ataC # 6 # 4 o-ataBiC&Ha!e 4 " : " 4 o-ataBiC&Oalue 4 CHRFB>7C Hext M#Box #= 7= "-ocu!ent Stati#tic#" o-ata 6 o-ocProp#&^e.*ord# # 6 "" "or i 6 ,BoundBo-ataC 3o 0BoundBo-ataC # 6 # 4 o-ataBiC 4 CHRFB>7C Hext M#Box #= 7= "^e.*ord#" )I (a:e little experience *it( t(i# obNect& )See!# t(at t(e u#er de$ined propertie# are a:ailable (ere& )co!&#un&#tar&co!p&co!p(elper&OPropert.Ba o-ata 6 o-ocProp#&0#er-e$inedPropertie# End Sub 1#.$.1. (ocument properties from a closed document )t is easy to access t"e document properties from a document t"at is not open& Listing 270. Read the document properties from a document that is not open. Sub loadExternalPropertie# -i! #Pat(F -i! #Pat(0rl -i! o-ocProp# #Pat( 6 Con:ert3o0rlB"+andre*7+(o!e+and.+Mo:e"i#"ro!"ra!e#&odt"C o-ocProp# 6 Create0noSer:iceB"co!&#un&#tar&docu!ent&-ocu!entPropertie#"C o-ocProp#&load"ro!Mediu!B#Pat(= Arra.BCC print-ocPropertie#Bo-ocProp#C End Sub 1#.$.2. Custom properties 6ou can create and remoe your o%n custom document properties& 5se t"e 'ropertyAttribute constants s"o%n in Tab*e 103 %"i*e creatin$ an attribute to contro* t"e be"aior of created properties& 292 able (CF. com.sun.star.beans.9roperty-ttribute constants. Constant Vale Description MA6+2O1)D 1 T"e property a*ue can be oid& +154D 2 A 'roperty#"an$e2ent %i** be fired to a** re$istered property c"an$e *isteners %"en t"e a*ue of t"is property c"an$es& #14STRA)42D ! A 'roperty#"an$e2ent %i** be fired to a** re$istered etoab*e c"an$e *isteners %"en t"e a*ue of t"is property c"an$es& TRA4S)24T @ T"e property a*ue is not saed %it" t"e document& R2AD14L6 16 T"e property a*ue is read9on*y& MA6+2AM+)J515S 32 T"e property a*ue may be ambi$uous& MA6+2D20A5LT 6! T"e property can be set to defau*t& R2M1O2A+L2 12@ T"e property can be remoed& T"is used to be ca**ed R2M1OA+L2& 1'T)14AL 2A6 T"e property is optiona*& 5se add'roperty,name, attributes, defau*t=a*ue. to create a ne% property and remoe'roperty,name. to remoe a property from t"e document properties& ;"en a property is created, t"at property is added to t"e documentVs properties, so you can use t"e property set information ob/ect Listing 271. -dd a new document property. Sub AddHe*-ocu!entPropert. -i! o0-P o0-P 6 3(i#Co!ponent&et-ocu!entPropertie#BC&0#er-e$inedPropertie# I$ HO3 o0-P&etPropert.SetIn$oBC&(a#Propert.B.Ha!eB"Aut(or,a#tHa!e"C 3(en o0-P&addPropert.B"Aut(or,a#tHa!e"= 5 co!&#un&#tar&bean#&Propert.Attribute&MAPBEOOI- W 5 co!&#un&#tar&bean#&Propert.Attribute&REMOOEAB,E W 5 co!&#un&#tar&bean#&Propert.Attribute&MAPBE-E"A0,3= 5 "-e$ault ,a#t Ha!e"C End I$ End Sub 1#.$.#. (eprecated document information ob4ect T"e deprecated met"od $etDocument)nfo %as t"e preious met"od for obtainin$ and modifyin$ user data& T"e macro in Listin$ 2M2 sets t"e a*ue of a user fie*d and t"en disp*ays its a*ue& TIP Document)nfo and Standa*oneDocument)nfo are deprecated and rep*aced by Document'roperties& Listing 272. #eprecated method for getting and setting user information data. Sub Jet0#erIn$o"ield# -i! :-ocIn$o )-ocu!ent In$or!ation ObNect -i! #F )Jeneral #trin to print -i! iG )Index :ariable :-ocIn$o 6 3(i#Co!ponent&et-ocu!entIn$oBC :-ocIn$o&#et0#er"ieldOalueB>= "M. #pecial u#er :alue"C "or iG 6 7 3o :-ocIn$oBC&et0#er"ieldCountBC9> #F 6 #F 4 :-ocIn$o&et0#er"ieldHa!eBiC 4 " 6 " 45 293 CStrB:-ocIn$o&et0#er"ieldOalueBiCC 4 CHRFB>7C Hext M#Box #F= 7= "In$o "ield#" End Sub 13.. .ist events As 11o operates, it $enerates eents to inform *isteners t"at somet"in$ "as occurred& T"e eent *istener-supp*ier frame%or( a**o%s a macro to be ca**ed or a *istener to be notified %"en a specific eent occurs L for e3amp*e, %"en a document is *oaded or modified, or %"en te3t se*ection c"an$es& 2ac" document type supports t"e t%o interfaces com&sun&star&document&I2ent+roadcaster and com&sun&star&document&I2entsSupp*ier, a**o%in$ t"em to support eent9re*ated actiities L for e3amp*e, broadcastin$ eents to *isteners and proidin$ a *ist of supported eents& T"e macro in Listin$ 2M3 *ists t"e eent *isteners re$istered %it" t"e current document and for 11o& Anot"er use for t"is macro is to *ist t"e eents supported by t"e document& A*t"ou$" t"ere are no re$istered *isteners, t"is macro proides a nice *ist of t"e supported eent types& Listing 273. List the documentPs events. Sub -i#pla.A:ailableE:ent# -i! oJEB ) JlobalE:entBroadca#ter -i! o-oc -i! #F -i! o3ext
o-oc 6 Star-e#1top&,oadCo!ponent"ro!0rlB"pri:ate:$actor.+#*riter"= "5blan1"= 7= Arra.BCC oJEB 6 create0no#er:iceB"co!&#un&#tar&$ra!e&JlobalE:entBroadca#ter"C # 6 MoinBoJEB&E:ent#&etEle!entHa!e#BC= CHRFB>7CC o3ext 6 o-oc&3ext o3ext&In#ertStrinBo3ext&End= "666Jlobal E:ent#" 4 CHRFB>7C= "al#eC o3ext&In#ertStrinBo3ext&End= #= "al#eC # 6 MoinBo-oc&E:ent#&etEle!entHa!e#BC= CHRFB>7CC o3ext&In#ertStrinBo3ext&End= CHRFB>7C 4 CHRFB>7C 4 "666Writer E:ent#" 4 CHRFB>7C= "al#eC o3ext&In#ertStrinBo3ext&End= #= "al#eC End Sub Eere is a *ist of eents: 1& 1nStartApp 2& 1n#*oseApp 3& 1n#reate !& 1n4e% A& 1nLoad0inis"ed 6& 1nLoad M& 1n'repare5n*oad @& 1n5n*oad B& 1nSae 294 10& 1nSaeDone 11& 1nSae0ai*ed 12& 1nSaeAs 13& 1nSaeAsDone 1!& 1nSaeAs0ai*ed 1A& 1n#opyTo 16& 1n#opyToDone 1M& 1n#opyTo0ai*ed 1@& 1n0ocus 1B& 1n5nfocus 20& 1n'rint 21& 1nOie%#reated 22& 1n'repareOie%#*osin$ 23& 1nOie%#*osed 2!& 1nModify#"an$ed 2A& 1nTit*e#"an$ed 26& 1nOisArea#"an$ed 2M& 1nMode#"an$ed 2@& 1nStora$e#"an$ed 2B& 1n'a$e#ount#"an$e 30& 1nMai*Mer$e 31& 1nMai*Mer$e0inis"ed 32& 1n0ie*dMer$e 33& 1n0ie*dMer$e0inis"ed 3!& 1nLayout0inis"ed TIP Many ob/ects besides documents support eent *isteners& 0or e3amp*e, you can *isten to an indiidua* ce** in a #a*c document& 1#.,.1. 6egistering "our o1n listener T"e macro in Listin$ 2M3 uses t"e J*oba*2ent+roadcaster to access eent *isteners at t"e 11o *ee*& T"e macro in Listin$ 2M! rep*aces t"e documents 1nSae *istener %it" a macro named MySae, in Modu*e1, in t"e Standard *ibrary for My Macros& ;"en t"e document is saed, MySae is automatica**y ca**ed& T"e association is maintained een after c*osin$ and openin$ t"e document& 295 Listing 274. Register your own listener. Sub StealAnE:ent -i! !E:entProp#B>C a# ne* co!&#un&#tar&bean#&Propert.Oalue !E:entProp#B7C&Ha!e 6 "E:ent3.pe" !E:entProp#B7C&Oalue 6 "StarBa#ic" !E:entProp#B>C&Ha!e 6 "Script" !E:entProp#B>C&Oalue 6 "!acro:+++Standard&Module>&M.Sa:eBC"
)oJlobalE:entBroadca#ter 6 create0no#er:iceB"co!&#un&#tar&$ra!e&JlobalE:entBroadca#ter"C )oJlobalE:entBroadca#ter&E:ent#&ReplaceB.Ha!eB"OnStartApp"= !E:entProp#BCC 3(i#Co!ponent&E:ent#&ReplaceB.Ha!eB"OnSa:e"= !E:entProp#BCC End Sub TIP 5se t"e *ocation Dmacro:--"e**o-Standard&Modu*e1&MySae,.F to specify a macro in t"e document named D"e**o&odtF& A*t"ou$" t"is %or(s fine, t"e association is not *ost %"en t"e document is c*osed& An eent can /ust as easi*y be stored at t"e 11o *ee* by usin$ t"e J*oba*2ent+roadcaster& Do not mista(e t"e a*ue *ocation for t"e same 5RL type synta3 used to associate a form contro* to a macro: ":nd&#un&#tar&#cript:Standard&Module>&,ocalM.Sa:eUlanuae6Ba#ic4location6docu!ent" 1#.,.2. Intercepting dispatch commands Rep*acin$ a *istener eent is not t"e same as interceptin$ t"e +ile > Sa,e dispatc", t"is is mere*y a *istener used after t"e command "as been e3ecuted& )nterceptin$ a dispatc" %i** *oo( more *i(e t"is code proided by 'ao*o Montaoni& 1ne of t"e prob*ems %it" t"is is t"at a status *istener is not used, so, if a command is disab*ed, t"e menu %i** not s"o% t"e command as disab*ed& TIP +e ery carefu* %"i*e %ritin$ *isteners and interceptin$ dispatc"es& Assume t"at somet"in$ %i** c"an$e, or t"at you did somet"in$ %ron$ and t"at 11o %i** cras"7 you "ae been %arned& Listing 275. Replace a few menu commands. Jlobal o-i#patc(Interceptor Jlobal oSla:e-i#patc(Pro:ider Jlobal oMa#ter-i#patc(Pro:ider Jlobal o"ra!e Jlobal b-ebu A# Boolean -i! oCop.-i#patc( Sub Rei#terInterceptor o"ra!e 6 3(i#Co!ponent¤tController&"ra!e o-i#patc(Interceptor 6 Create0no,i#tenerB"3(i#"ra!e5"= 5 "co!&#un&#tar&$ra!e&/-i#patc(Pro:iderInterceptor"C o"ra!e&rei#ter-i#patc(Pro:iderInterceptorBo-i#patc(InterceptorC End Sub Sub Relea#eInterceptorBC On Error Re#u!e Hext o"ra!e&relea#e-i#patc(Pro:iderInterceptorBo-i#patc(InterceptorC 296 End Sub "unction 3(i#"ra!e5;uer.-i#patc( B o0rl= 5 #3aret"ra!eHa!e A# Strin= lSearc("la# A# ,on C A# Oariant
3(i#"ra!e5;uer.-i#patc( 6 o-i#p End "unction "unction 3(i#"ra!e5;uer.-i#patc(e# B !-i#patc(e# C A# Oariant )3(i#"ra!e5;uer.-i#patc(e# 6 !-i#patc(e#BC End "unction "unction 3(i#"ra!e5etSla:e-i#patc(Pro:ider B C A# Oariant 3(i#"ra!e5etSla:e-i#patc(Pro:ider 6 oSla:e-i#patc(Pro:ider End "unction Sub 3(i#"ra!e5#etSla:e-i#patc(Pro:ider B oS-P C oSla:e-i#patc(Pro:ider 6 oS-P End Sub "unction 3(i#"ra!e5etMa#ter-i#patc(Pro:ider B C A# Oariant 297 3(i#"ra!e5etMa#ter-i#patc(Pro:ider 6 oMa#ter-i#patc(Pro:ider End "unction Sub 3(i#"ra!e5#etMa#ter-i#patc(Pro:ider B oM-P C oMa#ter-i#patc(Pro:ider 6 oM-P End Sub Sub tole-ebu b-ebu 6 Hot b-ebu End Sub "unction JetCop.-i#patc(BC I$ Hot I#HullBoCop.-i#patc(C 3(en oCop.-i#patc( 6 5 Create0no,i#tenerB"M.Cu#to!5"= "co!&#un&#tar&$ra!e&/-i#patc("C End I$
JetCop.-i#patc( 6 oCop.-i#patc( End "unction Sub M.Cu#to!5di#patc(B0R,= Aru!ent#C Select Ca#e 0R,&co!plete Ca#e "&uno:Cop." M#Box "Sorr.= t(e oriinal " 4 0R,&co!plete 4 5 " di#patc( *a# #tolen $ro! Paolo M&"= ?Q
Ca#e "&uno:0ndo" M#Box "0ndo W(atUUUUKKKUUU"= >A Ca#e El#e End Select End Sub Sub M.Cu#to!5addStatu#,i#tenerBControl= 0R,C End Sub Sub M.Cu#to!5re!o:eStatu#,i#tener BControl= 0R,C End Sub A simi*ar met"od "as been used to intercept conte3t menus usin$ a I#onte3tMenu)nterceptor& 298 13.#. .in* targets Lin( tar$ets, a*so ca**ed D/ump mar(s,F can be used to /ump direct*y to a specific *ocation& T"e document nai$ator contains a *ist of *in( tar$ets& T"e ob/ect met"od $etLin(s,., defined by t"e com&sun&star&document&ILin(Tar$etSupp*ier interface, proides access to t"e *in( tar$ets& T"e $etLin(s,. met"od returns an ob/ect t"at supports t"e I4ameAccess interface& )n ot"er %ords, you can access t"e *in(s usin$ t"e met"ods $et+y4ame,., $et2*ement4ames,., "as+y4ame,., and "as2*ements,.& T"e ob/ect returned by t"e $etLin(s,. met"od does not access t"e *in(s direct*y, but rat"er it proides access to ot"er ob/ects t"at can& To access a** of t"e indiidua* *in(s, first use t"e $etLin(s,. met"od to access t"e master *ist of *in(s& 5se t"is returned ob/ect to access eac" Dfami*yF of *in(s based on t"e fami*y name& 0or e3amp*e, to obtain an ob/ect t"at can access a** of t"e tab*e *in(s, use: o-oc&et,in1#BC&etB.Ha!eB"3able#"C After obtainin$ a fami*y of *in(s, you can a*so obtain t"e indiidua* *in(s by name& At t"is fina* step, you "ae access to bot" t"e name of t"e *in( and t"e ob/ect t"at is *in(ed& T"e macro in Listin$ 2M6 obtains a** of t"e *in( fami*ies and t"e *in(s t"at t"ey contain, and t"en disp*ays t"e *in(Gs name in a ne%*y created ;rite document& Listing 276. <et %ump targets for the current document. Sub JetMu!p3aret# -i! #,in1Ha!e# )3able#= 3ext "ra!e#= Headin#= Boo1!ar1#= etc&&& -i! :One,in1 )One lin1 t.pe -i! iG )Index :ariable -i! #F )Jeneral #trin -i! :te!p -i! oHe*-oc -i! noAr#BC )An e!pt. arra. $or t(e aru!ent# -i! :Co!p )3(e loaded co!ponent -i! #0R,#BC )0R,# o$ t(e ne* docu!ent t.pe# to load -i! #0R, A# Strin )0R, o$ t(e docu!ent to load -i! o3ext
#0R, 6 "pri:ate:$actor.+#*riter" :Co!p 6 Star-e#1top&,oadCo!ponent"ro!0rlB#0R,= "5blan1"= 7= noAr#BCC o3ext 6 :Co!p&3ext o3ext&in#ertStrinBo3ext&End= ",IH^ 3PPES" 4 CHRFB>7C= "al#eC #,in1Ha!e# 6 3(i#Co!ponent&et,in1#BC&etEle!entHa!e#BC o3ext&in#ertStrinBo3ext&End= MoinB#,in1Ha!e#= C(rFB>7CC= "al#eC o3ext&in#ertStrinBo3ext&End= 5 CHRFB>7C 4 CHRFB>7C 4 "M0MP 3ARJE3S" 4 CHRFB>7C= 5 "al#eC "or i 6 7 3o 0BoundB#,in1Ha!e#C :One,in1 6 3(i#Co!ponent&et,in1#BC&etB.Ha!eB#,in1Ha!e#BiCC # 6 # 4 #,in1Ha!e#BiC 4 " 6 " I$ I#E!pt.B:One,in1C 3(en # 6 # 4 "E!pt." El#e # 6 # 4 #,in1Ha!e#BiC 4 " : " 4 5 MoinB:One,in1&etEle!entHa!e#BC= CHRFB>7C 4 #,in1Ha!e#BiC 4 " : " C REM 3o obtain t(e actual lin1 obNect= #uc( a# a REM text table or a rap(ic# obNect= u#e t(e $ollo*in 299 REM :te!p 6 :One,in1&etEle!entHa!e#BC REM :ObN 6 :One,in1&etB.Ha!eB:te!pB7CC End I$ # 6 # 4 CHRFB>7C Hext )M#Box #= 7= "Mu!p 3aret#" o3ext&in#ertStrinBo3ext&End= #= "al#eC End Sub 6ou can use /ump mar(s ,*in( tar$ets. to /ump direct*y to a specific *ocation %"en a document is *oaded& 5se /ump mar(s to focus t"e cursor at a specific *ocation %"en a document is opened, as s"o%n in Listin$ 2MM& T"e KumpMar( attribute sets t"e name from t"e a*ues s"o%n in t"e created document ,if you run t"e macro aboe.7 for e3amp*e, DTab*e1atab*eF /umps to t"e specified tab*e& Listing 277. Use the HumpMark property to %ump to a link target. -i! Prop#B7C Prop#B7C&Ha!e 6 "Mu!pMar1" Prop#B7C&Oalue 6 "3able>Stable" #0rl 6 "$ile:++c:+doc#+Special5doc&odt" :-oc 6 Star-e#1top&,oadCo!ponent"ro!0rlB#0rl= "5blan1"= 7= Prop#BCC 6ou can a*so use t"e /ump mar( as part of t"e 5RL ,see Listin$ 2M@. by p*acin$ it at t"e end of t"e 5RL separated by an octot"orpe c"aracter ,W.& )f t"e /ump mar( contains any specia* c"aracters, suc" as spaces, t"ey must be encoded usin$ standard 5RL notation& 0or e3amp*e, a space is encoded as X20& Listing 278. Use the HumpMark property to %ump to a link target. #0rl 6 "$ile:++c:+doc#+Special5doc&odtL3able>Stable" :-oc 6 Star-e#1top&,oadCo!ponent"ro!0rlB#0rl= "5blan1"= 7= Prop#BCC TIP T"e c"aracter DWF "as many names, inc*udin$: number si$n, pound si$n, "as", s"arp, crunc", "e3, $rid, pi$pen, tic9tac9toe, sp*at, cross"atc", and octot"orpe, to name a fe%& 13.$. 2ccessing view dataI A-iew"ata/upplier 5sin$ 11o, open a document, edit it or c"an$e somet"in$ ,for e3amp*e, moe to anot"er pa$e or c"an$e t"e Coom factor., c*ose t"e document, and open t"e document a$ain& ;"en you do t"is, t"e document opens at t"e same screen *ocation, at t"e same siCe, %it" t"e same Coom factor as %as actie %"en it %as *ast saed& T"is information is stored %it" t"e document and is aai*ab*e t"rou$" t"e interface com&sun&star&document&IOie%DataSupp*ier& T"is interface proides one ob/ect met"od, $etOie%Data,.& Listin$ 2MB disp*ays t"e ie% data for T"is#omponent ,see 0i$ure @2.& Listing 279. <et3iew#ata is found in the Sub JetOie*-ata -i! :Oie*-ata )Oie* data obNect -i! iG )Index :ariable -i! NG )Index :ariable -i! #F )Jeneral #trin -i! :te!p )Oie* data $or one obNect :Oie*-ata 6 3(i#Co!ponent&etOie*-ataBC REM "or eac( :ie* o$ t(e data "or i 6 7 3o :Oie*-ata&etCountBC 9 > 300 :te!p 6 :Oie*-ata&etB.IndexBiC "or N 6 7 3o 0BoundB:te!pC # 6 # 4 :te!pBNC&Ha!e 4 " 6 " 4 CStrB:te!pBNC&OalueC 4 CHRFB>7C Hext M#Box #= 7= "Oie* -ata" Hext End Sub Figure 82. 3iew data for a document. 13.&. Close a documentI ACloseable As of 11o 1&1&0, eac" document type supports t"e com&sun&star&uti*&I#*oseab*e interface& To c*ose t"ese ob/ects, ca** t"e ob/ect met"od c*ose,b0orce.& )f b0orce is True, t"e ob/ect must c*ose& )n ot"er %ords, it may not refuse to c*ose& )f, "o%eer, b0orce is 0a*se, t"e ob/ect may refuse to c*ose& +efore a document is c*osed, a messa$e is sent to a** re$istered *isteners, $iin$ t"em an opportunity to preent t"e c*osure& )f t"e c*ose re8uest is not etoed by any *istener, a messa$e is sent to eac" re$istered *istener, adisin$ t"em t"at t"e document %i** c*ose& T"e I#*ose+roadcaster interface proides met"ods to add and remoe a c*ose *istener ,see Tab*e 10!.& able (C2. Ob%ect methods defined by the interface :/lose!roadcaster. O27ect )et6od Description add#*oseListener,I#*oseListener. Add *istener to receie or "ae a eto for Dc*oseF eents& remoe#*oseListener,I#*oseListener. Remoe an ob/ect re$istered as a c*ose *istener usin$ add#*oseListener,.& T"e macro in Listin$ 2@0 demonstrates t"e safe %ay to c*ose a document usin$ t"e ob/ectGs c*ose,. met"od& 0or ersions of 11o prior to 1&1&0, t"e c*ose,. met"od is not aai*ab*e, so you must use t"e dispose,. met"od instead& T"e dispose,. met"od is unconditiona* and is not t"e preferred met"od to c*ose a document ,by document ) rea**y mean any ob/ect t"at supports bot" c*ose and dispose. because it doesnGt a**o% a re$istered user %"o mi$"t be usin$ t"e document to eto t"e c*ose and finis" %"at "e or s"e is doin$& Listing 280. he safe way to close a document. I$ Ha#0noInter$ace#Bo-oc= "co!&#un&#tar&util&/Clo#eable"C 3(en o-oc&clo#eBtrueC El#e o-oc&di#po#eBC End I$ 301 TIP Do not use dispose to c*ose a document, it is t"ere for *e$acy purposes& Assume, for e3amp*e, t"at you start printin$ a document and t"en immediate*y dispose,. t"e document& T"e document t"at is bein$ used for printin$ is sudden*y $one and 11o cras"es& 13.(. "raw 3agesI A"raw3ages/upplier 1#.2.1. (ra1 and Impress Dra% and )mpress are a*most identica* in t"e interfaces t"at t"ey support& Dra% is specifica**y desi$ned to "and*e independent $rap"ic ob/ects, %"ereas )mpress is desi$ned for business effects and presentations& T"e dra%in$ functiona*ity of Dra% and )mpress is identica*, "o%eer& T"e $rap"ic ob/ects are dra%n and disp*ayed on Ddra% pa$es&F +y t"eir desi$n, bot" Dra% and )mpress support mu*tip*e dra% pa$es& T"e functiona*ity to retriee a Dra%'a$e ob/ect is defined by t"e com&sun&star&dra%in$&IDra%'a$esSupp*ier interface& T"e interface com&sun&star&dra%in$&IDra%'a$es defines met"ods to retriee, insert, and remoe indiidua* pa$es ,see Tab*e 10A.& able (CI. Ob%ect methods defined by the interface :#raw9ages. O27ect )et6od Description )nsert4e%+y)nde3,inde3. #reate and insert a ne% dra% pa$e or master pa$e& remoe,IDra%'a$e. Remoe a dra% pa$e or master pa$e& $et#ount,. Return t"e number of dra% pa$es& $et+y)nde3,inde3. Return a specific dra% pa$e& "as2*ements,. Return True if t"ere are documents& T"e macro in Listin$ 2@1 demonstrates "o% to iterate t"rou$" eac" of t"e dra% pa$es& 2ac" dra% pa$e is e3ported to a K'J fi*e& T"e e3port type is specified by t"e MediaType property& Listing 281. $.port each graphics page to a H9<. o"ilter6Create0noSer:iceB"co!&#un&#tar&dra*in&Jrap(icExport"ilter"C -i! ar#B>C a# ne* co!&#un&#tar&bean#&Propert.Oalue "or i67 to o-oc&et-ra*Pae#BC&etcountBC9> oPae 6 o-oc&et-ra*Pae#BC&etB.IndexBiC na!e 6 oPae&na!e o"ilter&#etSource-ocu!entBopaeC ar#B7C&Ha!e 6 "0R," ar#B7C&Oalue 6 "$ile:+++cS+"4oPae&na!e4"&MPJ" ar#B>C&Ha!e 6 "Media3.pe" ar#B>C&Oalue 6 "i!ae+Npe" o"ilter&$ilterBar#BCC Hext TIP T"e inde3 used to access dra% pa$es is Cero based& T"is means t"at t"e first dra% pa$e is at *ocation 0& )f a document contains four dra% pa$es, t"ey are numbered 0 t"rou$" 3& T"is is %"y t"e 0or *oop in Listin$ 2@1 is from 0 To oDoc&$etDra%'a$es,.&$etcount,.91& 302 T"e macro in Listin$ 2@2 creates a ne% )mpress document and t"en adds a $rap"ic ima$e to t"e first dra% pa$e& T"e dra% ima$e is siCed to retain t"e aspect ratio& Listing 282. -dd a proportionally sized graphic to a draw page. Sub AddProportionalJrap(ic -i! o-oc )He*l. created I!pre## docu!ent -i! o-ra*Pae )3(e dra* pae t(at *ill contain t(e rap(ic i!ae -i! oJrap( )3(e created rap(ic i!ae
REM Create an I!pre## pre#entation docu!entK o-oc 6 Star-e#1top&loadCo!ponent"ro!0R,B"pri:ate:$actor.+#i!pre##"=5 "5de$ault"= 7= Arra.BCC
REM In#ert a #econd dra* pae i$ de#ired= REM lea:in t(e $ir#t dra* pae untouc(edK REM Could u#e t(e propert. -ra*Pae# REM o-ra*Pae 6 o-oc&-ra*Pae#&in#ertHe*B.IndexB>C REM o-ra*Pae 6 o-oc&et-ra*Pae#BC&in#ertHe*B.IndexB>C REM In t(i# ca#e= #i!pl. u#e t(e $ir#t dra* paeK o-ra*Pae 6 o-oc&et-ra*Pae#BC&etB.IndexB7C
REM Create a rap(ic# obNect t(at can be in#erted into t(e docu!ent oJrap( 6 o-oc&createIn#tanceB"co!&#un&#tar&dra*in&Jrap(icObNectS(ape"C
REM Set t(e 0R, o$ t(e i!ae #o t(at it can be added to t(e docu!ent oJrap(&Jrap(ic0R, 6 "(ttp:++api&openo$$ice&or+brandin+i!ae#+loone*&i$" o-ra*Pae&addBoJrap(C
REM I$ I #top (ere= t(ere *ill be a :er. #!all rap(ic i!ae in t(e REM upper9le$t corner o$ t(e docu!ent& 3(i# i# prett. !uc( u#ele##& REM Alt(ou( I could #i!pl. #i8e t(e rap(ic to t(e #a!e #i8e a# t(e bit!ap REM #i8e= I c(oo#e in#tead to #i8e t(i# #o t(at it i# a# lare a# po##ible REM *it(out c(anin t(e a#pect ratio& REM -eter!ine t(e ratio o$ t(e (ei(t to t(e *idt( $or t(e i!ae and REM al#o $or t(e dra* pae&
REM Co!pare t(e ratio# to #ee *(ic( i# *ider= relati:el. #pea1in I$ dPaeRatio D dI!aeRatio 3(en oHe*Si8e&Widt( 6 o-ra*Pae&Widt( oHe*Si8e&Hei(t 6 C,nBC-blBo-ra*Pae&Widt(C * dI!aeRatioC El#e oHe*Si8e&Widt( 6 C,nBC-blBo-ra*Pae&Hei(tC + dI!aeRatioC 303 oHe*Si8e&Hei(t 6 o-ra*Pae&Hei(t End I$ REM Center t(e i!ae on t(e I!pre## paeK -i! oPo#ition a# ne* co!&#un&#tar&a*t&Point oPo#ition&/ 6 Bo-ra*Pae&Widt( 9 oHe*Si8e&Widt(C+' oPo#ition&P 6 Bo-ra*Pae&Hei(t 9 oHe*Si8e&Hei(tC+'
oJrap(&SetSi8eBoHe*Si8eC oJrap(&SetPo#itionBoPo#itionC End Sub As a*ready stated, )mpress and Dra% documents are ery simi*ar in t"e A') t"at t"ey support& T"e macro in Listin$ 2@3 dra%s *ines in a Dra% document ,see 0i$ure @3.& Listing 283. #raw lines in a new graphic document. Sub -ra*,ine#In-ra*-ocu!ent -i! o-oc )He*l. created -ra* docu!ent -i! o-ra*Pae )3(e dra* pae t(at *ill contain t(e rap(ic# i!ae -i! oS(ape )S(ape to in#ert REM Create a ne* -ra* docu!entK o-oc 6 Star-e#1top&loadCo!ponent"ro!0R,B"pri:ate:$actor.+#dra*"=5 "5de$ault"= 7= Arra.BCC
REM 0#e t(e $ir#t dra* pae o-ra*Pae 6 o-oc&et-ra*Pae#BC&etB.IndexB7C
oSi8e&*idt( 6 o-ra*Pae&Widt( oSi8e&(ei(t6 o-ra*Pae&Hei(t 9 ' * oPo#&P oS(ape&#etSi8eBoSi8eC o-ra*Pae&addBoS(apeC Hext End Sub 304 Figure 83. hese lines drawn in a #raw document overlap. 1#.2.2. (ra1 lines 1ith arro1s in Calc 2ac" #a*c document contains a sin$*e dra% pa$e for eac" s"eet )n #a*c, eac" s"eet is *i(e a transparent *ayer containin$ dra%in$ data on top of t"e standard document data& T"e fo**o%in$ macro demonstrates a coup*e of usefu* t"in$s: 2ac" ce** "as a position on t"e dra% pa$e& T"is macro dra%s a *ine bet%een specific ce**s by usin$ t"e 'osition attribute on a ce**& T"e *ine is dra% from t"e upper *eft corner of ce** +2 to t"e upper *eft corner of ce** D!& A LineS"ape is created by t"e document& After creation, attributes are set on t"e LineS"ape7 for e3amp*e, position, siCe, and co*or& T"e LineS"ape is added to t"e dra% pa$e& Arro%s, and ot"er *ine endin$s, are added after t"e LineS"ape "as been added to t"e dra% pa$e H at *east t"is is re8uired in 11o ersion 3&3&0& Arro% *ine endin$s are set by settin$ t"e Line2nd4ame and LineStart4ame& ) %as not ab*e to find a *ist of supported arro% names, so, ) used t"e J5) to find t"e names mentioned in t"e J5), and t"e fe% t"at ) tried %or(ed& 4e3t, ) searc"ed t"e source code and ) found fi*ter-source-msfi*ter-esc"ere3&c3 and s3-source-dia*o$-sdstrin$&src, %"ic" contains t"e fo**o%in$ names: Arro% Arro% concae #irc*e Dimension Lines Doub*e Arro% Line Arro% Rounded *ar$e Arro% Rounded s"ort Arro% Sma** Arro% S8uare S8uare !A 305 Symmetric Arro% )n testin$, t"e en95S names %or(ed in ot"er *oca*es& Loca*e specific names %or(, but t"e a*ue t"at is stored is based on t"e en95S *oca*e name& )n ot"er %ords, usin$ ZDoub*e f*ec"eZ %it" a 0renc" *oca*e sets t"e property to DDoub*e Arro%F& Listing 284. #raw lines in a /alc document. Sub In#ert,ineInCalc-ocu!ent -i! o,ine -i! oCell> -i! oCell' -i! oS(eet -i! oPo# a# ne* co!&#un&#tar&a*t&Point -i! oSi8e a# ne* co!&#un&#tar&a*t&Si8e -i! oPae oS(eet 6 3(i#Co!ponent&S(eet#B7C oCell> 6 oS(eet&etCellB.Po#itionB>= >C oCell' 6 oS(eet&etCellB.Po#itionB%= %C o,ine 6 3(i#Co!ponent&createIn#tanceB"co!&#un&#tar&dra*in&,ineS(ape"C
REM Pou !u#t do t(i# A"3ER in#ertin t(e line into t(e pae& o,ine&,ineEndHa!e 6 "Arro*" o,ine&,ineStartHa!e 6 "-ouble Arro*" End Sub Figure 84. #raw a line in a /alc document. 306 1#.2.#. 8riter 2ac" ;riter document contains a sin$*e dra% pa$e for t"e entire document& )n ;riter, t"e pa$e is *i(e a transparent *ayer containin$ dra%in$ data on top of t"e standard document data& ;riter documents do not support t"e IDra%'a$esSupp*ier interface, because t"ey on*y contain a sin$*e dra% pa$e& T"ey do, "o%eer, support t"e IDra%'a$eSupp*ier interface, %"ic" defines t"e sin$*e ob/ect met"od $etDra%'a$e,.& T"e macro in Listin$ 2@3 uses optiona* dra% pa$e properties L name*y "ei$"t and %idt"& T"e dra% pa$e from a ;riter document does not contain t"ese properties& T"e dra% pa$e in a ;riter document "as ot"er pecu*iarities, "o%eer& 0or e3amp*e, addin$ *ines to t"e dra% pa$e L as done in Listin$ 2@3 L adds t"em as c"aracters at t"e cursor position rat"er t"an interpretin$ t"e positions as specific *ocations in t"e document& T"e macro in Listin$ 2@A dra%s *ines to demonstrate t"is be"aior ,a*so see 0i$ure @A.& Listing 285. #raw lines in a 'rite document. Sub -ra*,ine#InWrite-ocu!ent -i! o-oc )He*l. created Writer docu!ent -i! o-ra*Pae )3(e dra* pae t(at *ill contain t(e rap(ic# i!ae -i! oS(ape )S(ape to in#ert REM Create a ne* Writer docu!entK o-oc 6 Star-e#1top&loadCo!ponent"ro!0R,B"pri:ate:$actor.+#*riter"=5 "5de$ault"= 7= Arra.BCC
oSi8e&*idt( 6 dStepSi8e 9 C,nBC-blBiC * dStepSi8e + >7C+' oSi8e&*idt( 6 C,nBdStepSi8e+< * i 9 dStepSi8eC oSi8e&(ei(t6 dStepSi8e oS(ape&#etSi8eBoSi8eC o-ra*Pae&addBoS(apeC Hext End Sub 307 Figure 85. hese lines drawn in a 'riter document are treated as characters. 13.1+. 0he model IMode* is t"e primary interface t"at distin$uis"es a component as a document, as opposed to t"e 11o +asic )D2 or t"e inc*uded "e*p pa$es& 1b/ects t"at imp*ement t"e interface com&sun&star&frame&IMode* represent a component created from a 5RL& 11o document ob/ects may be contro**ed by a contro**er, %"ic" is a*so considered a ie% of t"e document& T"e IMode* interface defines t"e ob/ect met"ods in Tab*e 106& able (CG. Ob%ect methods defined by the interface com.sun.star.frame.:Model. O27ect )et6od Description $et5RL,. 5RL of t"e document returned as a Strin$& $etAr$s,. Return a copy of t"e com&sun&star&document&MediaDescriptor for t"is mode* ,document.& *oc(#ontro**ers,. 'reent some disp*ay updates L macros may run faster& +e sure to un*oc( t"e contro**ers %"en you are finis"ed& un*oc(#ontro**ers,. #a** t"is once for eac" ca** to *oc(#ontro**ers,.& "as#ontro**ersLoc(ed,. )s t"ere at *east one *oc( remainin$> $et#urrent#ontro**er,. T"e contro**er t"at current*y contro*s t"is mode*& $et#urrentSe*ection,. #urrent se*ection on t"e current contro**er& 1#.13.1. (ocument arguments Ar$uments passed to t"e document *oader contro* "o% t"e document is *oaded7 for e3amp*e, openin$ a document as read9on*y& 5se $etAr$s,. to obtain t"e documents media descriptor, %"ic" detai*s "o% t"e document %as *oaded& T"e MediaDescriptor serice can be accessed as a series of optiona* properties or as an array of properties ,see Listin$ 2@6 and 0i$ure @6.& Listing 286. 9rint the document media descriptor. Sub print-ocu!entAr#BC REM 3(i# #a.# to inore an. line# t(at cau#e an error& REM Obtainin a :alue !a. cau#e an error= but t(at i# REM not a proble!& It Nu#t pre:ent# a :alue $ro! bein printed& On Error Re#u!e Hext 308
REM Obtain t(e !edia de#criptor& It turn# out t(at t(i# REM can be repre#ented a# an arra. o$ Propert.Oalue #er:ice#& :Ar# 6 3(i#Co!ponent&etAr#BC
"or i 6 7 3o 0BoundB:Ar#C )"or eac( propert. # 6 # 4 :Ar#BiC&Ha!e 4 " 6 " )Add t(e propert. na!e and an e;ual# #in # 6 # 4 :Ar#BiC&Oalue )Obtainin t(e :alue !a. $ailK # 6 # 4 CHRFB>7C )Add a ne*9line c(aracter Hext M#Box #= 7= "Ar#" End Sub Figure 86. 9roperties returned by the get-rgs67 ob%ect method. A te3t fi*e is not a standard 11o ;riter fi*e, but rat"er, a simp*e fi*e t"at "as typica**y been created by a simp*e editor suc" as 4otepad& Te3t fi*es contain no information t"at identify t"e c"aracter set t"at %as used, or "o% *ines are terminated& Te3t fi*es usua**y use t"e fi*e e3tension TIT& ;"en a te3t fi*e is opened, 11o disp*ays a dia*o$ and as(s 8uestions about t"e fi*e so t"at it (no%s "o% t"e te3t fi*e is encoded& ) %as as(ed "o% to *oad a te3t fi*e usin$ a macro, aoidin$ t"e dia*o$ and e3p*icit*y specifyin$ t"e import a*ues& A*t"ou$" ) %as ab*e to correct*y determine t"e import fi*ter name, ) "ad no idea "o% to specify t"e re8uired fi*ter options& ) "ad no idea, t"at is, unti* ) found t"e $etAr$s,. ob/ect met"od& TIP )f you (no% "o% to open a document usin$ t"e J5), but are uncertain "o% t"e ar$uments must be set to *oad t"e document usin$ *oad#omponent0rom5RL, t"en first *oad t"e document usin$ t"e J5), t"en inspect t"e documentVs media descriptor& Eint: *oo( at 0i*ter1ptions& 0i$ure @6 s"o%s t"e ar$uments for an imported te3t fi*e& T"e 0i*ter4ame property indicates t"e name of t"e import fi*ter, and t"e 0i*ter1ptions property indicates t"e fi*ter options t"at %ere used to open t"e fi*e& 5sin$ t"ese properties %it" t"e des(top ob/ect met"od Load#omponent0rom5r*,., t"e fi*e is correct*y imported and t"e dia*o$ is not disp*ayed& Tab*e 10M contains a *ist of t"e properties t"at may be returned from t"e 309 $etAr$s,. ob/ect met"od& T"e 11o A') ;eb site contains a fe% more properties, but t"ey are obscure or deprecated& able (CT. Ob%ect properties defined by the service Media#escriptor. Property Description Aborted May be set if document *oad is aborted %"i*e enterin$ a pass%ord& AsTemp*ate Document %as *oaded as a temp*ate& Aut"or Aut"or of t"is document ersion7 t"is is for ersionin$& #"aracterSet Document c"aracter set for sin$*e9byte c"aracters& #omment #omment on t"e current document ersion7 t"is is for ersionin$& DocumentTit*e )f t"e document tit*e is specified, it is inc*uded "ere& 0i*ter4ame 0i*ter used to import or sae t"is document& 0i*ter1ptions 0i*ter used to import t"is document& 0i*terData Additiona* import properties if t"e 0i*ter1ptions strin$ is not sufficient& Eidden )f t"e Eidden ar$ument is specified durin$ *oad, it is inc*uded "ere& Eierarc"ica*Document4ame T"e "ierarc"ica* pat" to t"e embedded document from topmost container& )nputStream )f t"e )nputStream is specified durin$ *oad, it is inc*uded "ere& )nteractionEand*er 23ception "and*er if an error occurs durin$ import& KumpMar( Kump to t"is mar(ed position after *oadin$ t"e document& MediaType M)M2 type of t"is document& 1pen4e%Oie% 1pens a ne% ie% for an a*ready *oaded document, rat"er t"an /ust openin$ t"e document t%ice& )n ot"er %ords, re8uest t%o ie%s of t"e same data& 1utputStream Stream to use %"i*e %ritin$ t"e document& 1er%rite 1er%rite any e3istin$ fi*e on sae& 'ass%ord 'ass%ord for *oadin$ or storin$ t"e document& 'reie% Document *oaded in preie% mode7 optimiCes for preie%9on*y use& Read1n*y Document opened as read9on*y7 contro**er %i** not c"an$e t"e document& Referer 5RL of document referrer L for e3amp*e, if opened by c*ic(in$ an ETT' *in(& Repair'ac(a$e 1pen t"e document in repair mode& Start'resentation )mmediate*y after *oadin$ an )mpress document, start t"e presentation& Status)ndicator )f a status indicator %as specified %"en t"e document %as *oaded, it is inc*uded "ere& 5npac(ed )f True, an 11o document is stored as a fo*der rat"er t"an a P)' fi*e& 5RL 5RL of t"e document& Oersion #urrent document ersion, if ersionin$ is supported& Oie%Data T"e ie% data to use& Oie%)d T"e )D of t"e initia* ie%& Macro23ecutionMode Specifies "o% macros are treated %"en t"e document is *oaded& 310 13.11. /aving a document T"e *ocation %"ere a document is saed is ca**ed its 5niform Resource Locator ,5RL. L in ot"er %ords, its fi*e name& A fi*e 5RL usua**y contains t"e comp*ete pat" to t"e fi*e& ;"en t"e fi*e name is referred to as t"e 5RL, it "as a form simi*ar to Dfi*e:---c:-myfi*e&s3%F rat"er t"an Dc:Smyfi*e&s3%F& A 5RL is a $enera* %ay of %ritin$ a stora$e *ocation, one t"at can be e3tended conenient*y to inc*ude a %ide ran$e of stora$e *ocation types in a manufacturer9independent and computer9independent manner& 11o +asic supports t"e functions #onertTo5RL and #onert0rom5RL to conert bet%een t"e t%o notations& T"e IStorab*e interface defines ob/ect met"ods to sae a document to a 5RL ,see Tab*e 10@.& able (C0. Ob%ect methods defined by the service com.sun.star.frame.:*torable. O27ect )et6od Description "asLocation,. True if t"e document "as a stora$e *ocation and 0a*se if t"is is a ne% b*an( document& $etLocation,. Return t"e 5RL %"ere t"e ob/ect %as stored after ca**in$ storeAs5RL,.& isReadon*y,. 6ou cannot ca** store,. if t"e fi*e %as ca**ed from a read9on*y *ocation& store,. Stores t"e data to t"e current 5RL& storeAs5RL,5RL, ar$s. Stores t"e document to t"e specified 5RL, %"ic" becomes t"e current 5RL& storeTo5RL,5RL, ar$s. Stores t"e document to t"e specified 5RL, but t"e current 5RL does not c"an$e& 5se t"e ob/ect met"od "asLocation,. to determine if a document (no%s %"ere to sae itse*f, and use t"e met"od store,. to sae it to t"e current 5RL& T"e macro in Listin$ 2@M uses met"ods defined by bot" IStorab*e and IModifiab*e to sae a document to dis(& T"e document is stored on*y if it (no%s %"ere to store itse*f, it "as c"an$ed, and it is not read9on*y& Listing 287. 9roper method to save a document. I$ B3(i#Co!ponent&i#Modi$iedBCC 3(en I$ B3(i#Co!ponent&(a#,ocationBC AH- BHot 3(i#Co!ponent&i#ReadOnl.BCCC 3(en 3(i#Co!ponent&#toreBC El#e REM Eit(er t(e docu!ent doe# not (a:e a location or .ou cannot REM #a:e t(e docu!ent becau#e t(e location i# read9onl.& #etModi$iedB"al#eC End I$ End I$ A document does not "ae a stora$e *ocation immediate*y after it is created& A document *oaded from dis(, "o%eer, "as a (no%n *ocation& 5se t"e ob/ect met"od storeAs5RL,. or storeTo5RL,. to sae a document to a specified *ocation& T"e difference bet%een t"e met"ods is t"at storeAs5RL,. sets t"e current *ocation ,5RL. and storeTo5RL,. does not& T"e se8uence of actions in Tab*e 10B "e*ps c*arify t"e difference& able (C1. #ifference between storeoURL and store-sURL. Step $ction Comment 1 #reate document #annot use t"e store,. met"od because t"e document "as no *ocation& 2 5se storeTo5RL Document saed, but cannot use t"e store,. met"odbecause it "as no *ocation& 3 5se storeAs5RL #an use t"e store,. met"od because no% t"e document "as a *ocation& ! 5se storeTo5RL Document saed, but t"e *ocation is t"e same as set in step 3& 311 TIP T"e met"od storeAs5RL,. is simi*ar to t"e menu option 0i*e a Sae As, %"ic" c"an$es t"e current *ocation& T"e met"od storeTo5RL,. is usua**y used to e3port a document so t"at t"e fi*e 5RL does not c"an$e and contain a non911o document e3tension& T"e t%o ob/ect met"ods for storin$ a document, storeAs5RL,. and storeTo5RL,., accept t"e same ar$uments7 *earn to use one and youG** (no% "o% to use t"e ot"er& 3(i#Co!ponent&#toreA#0R,Burl= ar#BCC 3(i#Co!ponent&#tore3o0R,Burl= ar#BCC T"e second ar$ument is an array of property a*ues ,see Tab*e 10M. t"at direct "o% t"e document is saed ,see Listin$ 2@@.& T"e fi*es can /ust as easi*y be stored %it" no ar$uments ,see Listin$ 2@B.& Listing 288. *ave a document to a new location. -i! ar#B7C A# He* co!&#un&#tar&bean#&Propert.Oalue -i! #0rl A# Strin #0rl 6 "$ile:+++c:+M.G'7-ocu!ent#+te#t5$ile&#x*" ar#B7C&Ha!e 6 "O:er*rite" )3(i# propert. i# de$ined in 3able >72 ar#B7C&Oalue 6 "al#e )-o not o:er*rite an exi#tin docu!ent& 3(i#Co!ponent&#toreA#0R,B#0rl= ar#BCC TIP T"e com&sun&star&frame&I#omponentLoader interface defines t"e ob/ect met"od Load#omponent0rom5r*,., %"ic" is used to *oad a fi*e& T"e different document types do not imp*ement t"is interface, but t"e document frame and t"e des(top bot" imp*ement t"e interface& T"e met"od Load#omponent0rom5r*,. a*so uses t"e a*ues in Tab*e 10M to direct "o% t"e fi*e is *oaded& Listing 289. *ave the document with an inappropriate file e.tension. 3(i#Co!ponent&#tore3o0R,B"$ile:+++c:+t*o&xl#"= Arra.BCC TIP T"e macro in Listin$ 2@B uses t"e fi*e e3tension D3*sF, %"ic" is typica**y used by Microsoft 23ce*& T"is does not cause t"e fi*e to be stored usin$ t"e Microsoft 23ce* format& T"e fi*e is saed usin$ t"e standard 11o fi*e format if an e3port fi*ter is not e3p*icit*y stated& ;"en you open a fi*e, 11o c"ec(s to see if t"e fi*e is in a standard 11o fi*e format& )f not, t"e fi*e type is determined based on t"e fi*e e3tension& ) cannot een count t"e number of times t"at ) "ae been as(ed %"y 11o is not ab*e to open a comma9de*imited te3t fi*e& T"e usua* ans%er is t"at a comma9de*imited fi*e must "ae t"e fi*e e3tension #SO or 11o cannot reco$niCe t"e fi*e& A*t"ou$" t"e fi*e e3tension is important %"i*e *oadin$ a fi*e from t"e J5), it is not important %"i*e sain$& )f you %ant to sae a fi*e in a non9 1pen1ffice&or$ natie format, you must e3p*icit*y te** 11o to sae in a different fi*e format ,see Listin$ 2B0.& Listing 290. $.port a document to the specified Microsoft $.cel file format. -i! ar#B7C a# ne* co!&#un&#tar&bean#&Propert.Oalue ar#B7C&Ha!e 6 ""ilterHa!e" )I a! #o excited= *(ic( $ilter *ill *e u#eU ar#B7C&Oalue 6 "MS Excel @2" )O(= t(e Excel @2 $or!atK 3(i#Co!ponent&#tore3o0R,B"$ile:+++c:+one&xl#"=ar#BCC 312 TIP A*t"ou$" t"e e3port fi*ter names are t"e same as t"e import fi*ter names, not eery import fi*ter can e3port and not eery e3port fi*ter can import& )mpress and Dra%, used to edit $rap"ica* content, support mu*tip*e dra% pa$es& To e3port a dra% pa$e to a specific $rap"ics format re8uires t"e use of a $rap"ics e3port fi*ter ,see Listin$ 2B1.& T"e media type must be specified or t"e e3port %i** fai*& Listing 291. $.port the first draw page to a H9< file. -i! o"ilter -i! ar#B>C a# ne* co!&#un&#tar&bean#&Propert.Oalue o"ilter6Create0noSer:iceB"co!&#un&#tar&dra*in&Jrap(icExport"ilter"C o"ilter&#etSource-ocu!entB3(i#Co!ponent&dra*Pae#B7CC ar#B7C&Ha!e 6 "0R," )W(ere t(e $ile *ill be #a:ed ar#B7C&Oalue 6 "$ile:+++c:+one&MPJ" )3(e de#tination 0R, ar#B>C&Ha!e 6 "Media3.pe" )W(at t.pe o$ $ile ar#B>C&Oalue 6 "i!ae+Npe" )3(e $ile t.pe o"ilter&$ilterBar#BCC 13.12. Manipulating st'les Sty*es proide a met"od of $roupin$ formattin$ information& 0or e3amp*e, a para$rap" sty*e defines t"e font, c"aracter siCe, mar$ins, and many ot"er formattin$ options& #"an$in$ a sty*e c"an$es eery ob/ect usin$ t"e sty*e& T"e interface com&sun&star&sty*e&ISty*e0ami*iesSupp*ier proides access to t"e sty*es used by a document& T"e macro in Listin$ 2B2 disp*ays t"e names of a** sty*es in t"e current document7 0i$ure @M s"o%s t"e resu*ts for one of my documents& Listing 292. #isplay styles used in a document. Sub -i#pla.AllSt.le# -i! o"a!ilie# )"a!ilie# i# inter$ace co!&#un&#tar&container&/Ha!eAcce## -i! o"a!il.Ha!e# )Ha!e# o$ $a!il. t.pe#& Arra. o$ #trin -i! oSt.leHa!e# )Ha!e# o$ #t.le#& Arra. o$ #trin -i! oSt.le# )St.le# i# inter$ace co!&#un&#tar&container&/Ha!eAcce## -i! oSt.le )An indi:idual #t.le -i! # A# Strin )0tilit. #trin :ariable -i! n A# Inteer )Index :ariable -i! i A# Inteer )Index :ariable
REM "ir#t= di#pla. t(e #t.le t.pe# and t(e nu!ber REM o$ eac( #t.le t.pe& "or n 6 ,BoundBo"a!il.Ha!e#C 3o 0BoundBo"a!il.Ha!e#C oSt.le# 6 o"a!ilie#&etB.Ha!eBo"a!il.Ha!e#BnCC # 6 # 4 oSt.le#&etCountBC 4 " " 4 o"a!il.Ha!e#BnC 4 CHRFB>7C Hext M#Box #= 7= "St.le "a!ilie#" REM Ho*= di#pla. all o$ t(e di$$erent #t.le na!e# "or n 6 ,BoundBo"a!il.Ha!e#C 3o 0BoundBo"a!il.Ha!e#C # 6 "" oSt.le# 6 o"a!ilie#&etB.Ha!eBo"a!il.Ha!e#BnCC 313 oSt.leHa!e# 6 oSt.le#&etEle!entHa!e#BC "or i 6 ,BoundBoSt.leHa!e#C 3o 0Bound BoSt.leHa!e#C #6# W i W " : " W oSt.leHa!e#BiC W CHRFB>7C I$ BBi W >C Mod %7 6 7C 3(en M#Box #=7=o"a!il.Ha!e#BnC # 6 "" End I$ Hext i I$ ,enB#C ED 7 3(en M#Box #=7=o"a!il.Ha!e#BnC Hext n End Sub Figure 87. he style families in one of my 'riter documents. T"e different document types contain different types of sty*es& 0i$ure @M s"o%s t"e sty*e fami*ies in a ;riter document& #a*c documents contain t"e sty*e fami*ies #e**Sty*es and 'a$eSty*es7 )mpress documents contain t"e sty*e fami*ies Jrap"ics and Defau*t7 Dra% documents contain t"e sty*e fami*y Jrap"ic& A*t"ou$" eac" sty*e type is different, t"ey do "ae simi*arities& 0or e3amp*e, eac" sty*e imp*ements bot" t"e com&sun&star&sty*e&Sty*e serice and t"e com&sun&star&sty*e&ISty*e interface& T"e common met"ods and properties proide ery rudimentary functiona*ity ,see Tab*e 110.& able ((C. Ob%ect methods defined in the com.sun.star.style.*tyle service. )et6od or Property Description is5serDefined,. )s t"is sty*e user9defined> )f not, it is inc*uded %it" 11o& is)n5se,. )s t"is sty*e used in t"e document> $et'arentSty*e,. ;"at is t"e parent sty*e> set'arentSty*e,name. Set t"e parent sty*e& )s'"ysica* )s t"e sty*e p"ysica**y created> 0o**o%Sty*e Sty*e name app*ied to t"e ne3t para$rap"& 0or e3amp*e, %"i*e usin$ a "eadin$ sty*e ) mi$"t %ant t"e ne3t para$rap" to be re$u*ar te3t& Disp*ay4ame 4ame of t"e sty*e as disp*ayed in t"e user interface& )sAuto5pdate )f t"e properties of an ob/ect usin$ t"is sty*e are c"an$ed ,for e3amp*e, if ) c"an$e t"e font., are t"ese c"an$es automatica**y updated to t"e sty*e> Tab*e 110 s"o%s met"ods and properties t"at can be used to ans%er t"e common 8uestion, DEo% do ) obtain a *ist of sty*es t"at are current*y used by a document>F See Listin$ 2B3 and 0i$ure @@& 314 TIP Listin$ 2B2 accesses sty*es by name7 Listin$ 2B3 accesses sty*es by inde3& 4otice t"at %"en $et#ount,. returns 10, t"ere are 10 items present, inde3ed 0 t"rou$" B& Listing 293. #isplay all used paragraph styles. Sub -i#pla.All0#edPararap(St.le# -i! oSt.le# )St.le# i# inter$ace co!&#un&#tar&container&/Ha!eAcce## -i! oSt.le )An indi:idual #t.le -i! # A# Strin )0tilit. #trin :ariable -i! i A# Inteer )Index :ariable
oSt.le# 6 3(i#Co!ponent&St.le"a!ilie#&etB.Ha!eB"Pararap(St.le#"C REM I$ etCountBC #a.# t(at t(ere are >7 #t.le#= t(i# !ean# $ro! 7 to @ "or i 6 > 3o oSt.le#&etCountBC oSt.le 6 oSt.le#&etB.IndexBi9>C I$ oSt.le&i#In0#eBC 3(en # 6 # 4 oSt.le&-i#pla.Ha!e 4 CHRFB>7C Hext M#Box #=7="Pararap( St.le# In 0#e" End Sub Figure 88. 9aragraph styles used in a 'riter document. )nitia**y, ) %as confused by t"e resu*ts s"o%n in 0i$ure @@ because it inc*uded para$rap" sty*es t"at ) t"ou$"t ) %asnGt usin$& ) assumed t"at ) "ad made a mista(e %"i*e %ritin$ my document, so ) started *oo(in$ for t"ese accidenta**y used sty*es& To find t"e incorrect*y sty*ed te3t, ) started %it" t"e 0ind Q Rep*ace dia*o$ ,2dit a 0ind Q Rep*ace.& )f you c"ec( t"e bo3 *abe*ed DSearc" for Sty*es,F a** of t"e sty*es used in t"e document become aai*ab*e in t"e DSearc" forF drop9do%n bo3& ) used t"is met"od to searc" for t"e sty*e DTe3t bodyF ,s"o%n in 0i$ure @@., but it %as not found in t"e document& After some moments of confusion L in t"is case, rou$"*y fie minutes L ) rea*iCed t"at ) "ad not found a bu$ in 1pen1ffice&or$, but rat"er ) "ad uncoered an interestin$ be"aior of %"ic" ) "ad not been preious*y a%are& ;"en a sty*e is used in a document, t"e parent sty*e is *isted as used een if it is not direct*y used& 0or e3amp*e, in my document, t"e sty*e DTab*e #ontentsF uses DTe3t bodyF as t"e parent sty*e& T"e different sty*e types contain met"ods and properties appropriate for t"eir type& See "ttp:--api&openoffice&or$-docs-common-ref-com-sun-star-sty*e-modu*e9i3&"tm* for t"e common serices, interfaces, structs, and constants re*ated to sty*es& T"e types s"o%n in t"e sty*e modu*e are t"e base on %"ic" t"e ot"er sty*es are bui*t& 0or e3amp*e, t"e t%o serices com&sun&star&te3t&Te3t'a$eSty*e and 315 com&sun&star&s"eet&Tab*e'a$eSty*e bot" "ae t"e serice com&sun&star&sty*e&'a$eSty*e in common& To $et a fee* for a sty*e it is fre8uent*y e3pedient to start by inspectin$ t"e ob/ect& M#Box :ObN&db5!et(od# M#Box :ObN&db5#upportedInter$ace# M#Box :ObN&db5propertie# T"e sty*e ob/ects, *i(e many ot"er ob/ects, imp*ement t"e I'ropertySet interface& T"e macro in Listin$ 2B! uses t"is interface to disp*ay a *ist of properties contained in t"e D=body te3tF para$rap" sty*e& Listin$ 2B! does not disp*ay t"e a*ue of eac" property7 it on*y disp*ays t"e name of eac" property& )t is an interestin$ e3ercise to modify Listin$ 2B! to a*so disp*ay t"e a*ue of eac" property t"at is a standard data type L a property may be a comp*e3 ob/ect& Listing 294. #isplay 9roperties for a paragraph style. Sub St.lePropertie# -i! oSt.le# )St.le# i# inter$ace co!&#un&#tar&container&/Ha!eAcce## -i! # A# Strin )0tilit. #trin :ariable -i! i A# Inteer )Index :ariable -i! Prop# )Arra. o$ propertie#
REM Eac( #t.le #upport# t(e co!&#un&#tar&bean#&/Propert.Set inter$ace REM 3(i# #upport# t(e !et(od etPropert.SetIn$oBC= *(ic( allo*# REM an enu!eration o$ t(e contained propertie#& REM Jet propertie# return# an arra. o$ co!&#un&#tar&bean#&Propert. oSt.le# 6 3(i#Co!ponent&St.le"a!ilie#&etB.Ha!eB"Pararap(St.le#"C Prop# 6 oSt.le#&etB.Ha!eB"5bod. text"C&etPropert.SetIn$oBC&etPropertie#BC "or i 6 7 3o 0BoundBProp#C )"or eac( propert. # 6 # 4 Prop#BiC&Ha!e 4 CHRFB>7C )Include t(e propert. na!e and ne* line I$ BiW>C MO- %7 6 7 3(en )I$ t(e #trin beco!e# too lare M#Box #=7="St.le Propertie#" )di#pla. t(e current #trin # 6 "" )Re#et t(e li#t End I$ Hext REM In ca#e t(e entire li#t *a# not printed& I$ ,enB#C ED 7 3(en M#Box #=7="St.le Propertie#" End Sub )n my e3perience, itGs rare to access and inspect sty*es& )tGs een *ess common to modify a sty*e from a macro& T"ere are times, "o%eer, %"en t"is is done& 0or e3amp*e, t"e pa$e siCe is defined by t"e current pa$e sty*e& 5se t"e current contro**er to determine t"e current pa$e sty*e, and t"en use t"at to determine t"e pa$e dimensions& Listin$ 2BA disp*ays t"e siCe of t"e pa$e, t"e mar$ins, and t"e current cursor position on t"e pa$e& 0i$ure @B s"o%s t"e resu*ts& TIP T"e most common reason t"at ) "ae seen for modifyin$ a pa$e sty*e is to add a "eader or footer to t"e current pa$e sty*e& 'ortions of t"is code are specu*atie and "ae c"an$ed since ) ori$ina**y created t"e code& T"e current contro**er returns t"e current cursor position based on t"e *eftmost corner of t"e first pa$e in t"e document& 1n pa$e 200, t"erefore, t"e 6 coordinate may be ery *ar$e& T"e fo**o%in$ code attempts to compensate for t"is, but, it does so poor*y ,%"ere poor*y means t"at ) be*iee t"e ans%er is incorrect %it" respect to t"e top and t"e bottom of t"e pa$e.& >> 316 Listing 295. 9rint9age"nformation Sub PrintPaeIn$or!ation -i! oOie*Cur#or )Current :ie* cur#or -i! oSt.le )Current pae #t.le -i! lHei(t A# ,on )Pae (ei(t $ro! Pae St.le in >+>77 !! -i! lWidt( A# ,on )Pae *idt( $ro! Pae St.le in >+>77 !! -i! # A# Strin )3e!porar. #trin :ariable REM 3(e current controller inter$ace# *it( t(e (u!an b t(at)# .ouK REM Well= *e (ope .ou are (u!an an.*a.& REM Obtain t(e current :ie* cur#or $ro! t(e controller& It i# REM t(e t(in t(at 1no*# *(ere t(e current cur#or i#= a$ter all& oOie*Cur#or 6 3(i#Co!ponent&CurrentController&etOie*Cur#orBC
REM 3(at :ie* cur#or 1no*# a lot o$ t(in#= includin t(e REM current pae #t.le& 0#e t(e pae #t.le na!e to et REM a re$erence to t(e current pae #t.le& # 6 oOie*Cur#or&PaeSt.leHa!e oSt.le 6 3(i#Co!ponent&St.le"a!ilie#&etB.Ha!eB"PaeSt.le#"C&etB.Ha!eB#C # 6 "Pae St.le 6 " 4 # 4 CHRFB>7C lHei(t 6 oSt.le&Hei(t )Pae (ei(t in >+>77 !! lWidt( 6 oSt.le&Widt( )Pae *idt( in >+>77 !!
-i! : REM Cur#or)# coordinate# relati:e to t(e top le$t po#ition o$ t(e pae REM Return t.pe i# co!&#un&#tar&a*t&Point REM 0nit# are in t*ip#& Con:ert t(e! to inc(e#& : 6 oOie*Cur#or&etPo#itionBC
REM Pae nu!ber $ro! t(e :ie* cur#or include# "p(anto!" pae# becau#e REM t*o pae# in a ro* !u#t bot( be on #a. a ri(t #ide& REM :&P doe# not include t(i#& -i! realPaeHu!ber A# ,on realPaeHu!ber 6 "ixB:&P + lHei(tC
-i! realP : realP 6 :&P 9 realPaeHu!ber * lHei(t
REM Place t(e cur#or a# t(e di#tance to t(e !arin and t(en add t(e !arin& REM "or t(e :ertical (ei(t add (al$ t(e c(aracter (ei(t& I #(ould REM probabl. do t(i# $or t(e c(aracter *idt( a# *ell $or (ori8ontal& dPCur#or 6 realP+'<?7&7 W d3op W dC(arHei(t + ' dPBotto! 6 BlHei(t 9 realPC+'<?7&7 9 d3op 9 dC(arHei(t + ' d/Cur#or 6 :&/+'<?7&7 W d,e$t d/Ri(t 6 BlWidt( 9 :&/C+'<?7&7 9 d,e$t
#6# 4"Cur#or i# "4"or!atBd/Cur#or= "7&LL"C 4 " inc(e# $ro! le$t "4CHRFB>7C #6# 4"Cur#or i# "4"or!atBd/Ri(t= "7&LL"C 4 " inc(e# $ro! ri(t "4CHRFB>7C #6# 4"Cur#or i# "4"or!atBdPCur#or= "7&LL"C 4 " inc(e# $ro! top "4CHRFB>7C #6# 4"Cur#or i# "4"or!atBdPBotto!= "7&LL"C 4 " inc(e# $ro! botto! "4CHRFB>7C #6# 4"C(ar (ei(t 6 " 4 "or!atBdC(arHei(t= "7&LLLL"C 4 " inc(e#"4CHRFB>7C M#Box #= 7= "Pae in$or!ation" End Sub Figure 89. "nformation from the page style. #a*c documents are composed of spreads"eets& 2ac" s"eet can use a different pa$e sty*e& T"e macro in Listin$ 2BA obtains t"e current pa$e sty*e usin$ t"e ie% cursor& To obtain t"e sty*e from a #a*c document, use t"e actie s"eet& REM 0#e t(e currentl. acti:e #(eet to obtain t(e pae #t.le& REM In a Calc docu!ent= t(e current controller 1no*# *(ic( #(eet REM i# acti:e& 318 Print "St.le 6 " 4 3(i#Co!ponent&CurrentController&etActi:eS(eetBC&PaeSt.le 13.13. "ealing with locale A *oca*e represents a specific $eo$rap"ica*, po*itica*, or cu*tura* re$ion& 4umbers and dates are considered *oca*e9sensitie, so number formats are associated %it" a *oca*e& 5se Too*s a 1ptions a Lan$ua$e Settin$s a Lan$ua$es to see %"ic" *oca*e is used for your computer& #reatin$ a *oca*e is ery easy& -i! a,ocale A# He* co!&#un&#tar&lan&,ocale a,ocale&,anuae 6 "$r" a,ocale&Countr. 6 ""R" TIP 11o may not support eery possib*e *oca*e, but it %i** attempt to use t"e best possib*e matc"& T"e *oca*e depends upon bot" t"e *an$ua$e and t"e country& Some countries use mu*tip*e *an$ua$es and some *an$ua$es are used in mu*tip*e countries& Tab*e 111 contains t"e t%o9c"aracter code t"at identifies eac" *an$ua$e, and Tab*e 112 contains t"e t%o9c"aracter code t"at identifies eac" country& TIP A*t"ou$" t"e *oca*e codes are not case sensitie, t"ey are typica**y %ritten in *o%ercase for t"e *an$ua$e and uppercase for t"e country& able (((. Locale language codes) alphabetized by code. Code Lan+a+e Code Lan+a+e Code Lan+a+e aa Afar ab Ab("aCian af Afri(aans am Am"aric ar Arabic as Assamese ay Aymara aC ACerbai/ani ba +as"(ir be +ye*orussian b$ +u*$arian b" +i"ari bi +is*ama bn +en$a*i7 +an$*a bo Tibetan br +reton ca #ata*an co #orsican cs #Cec" cy ;e*s" da Danis" de Jerman dC +"utani e* Jree( en 2n$*is" eo 2speranto es Spanis" et 2stonian eu +as8ue fa 'ersian fi 0innis" f/ 0i/i fo 0aroese fr 0renc" fy 0risian $a )ris" $d Scots Jae*ic $* Ja*ician $n Juarani $u Ju/arati "a Eausa "e Eebre% ,former*y i%. "i Eindi "r #roatian "u Eun$arian "y Armenian ia )nter*in$ua id )ndonesian ,former*y in. ie )nter*in$ue i( )nupia( is )ce*andic it )ta*ian iu )nu(titut /a Kapanese /% Kaanese (a Jeor$ian (( <aCa(" (* Jreen*andic (m #ambodian (n <annada 319 Code Lan+a+e Code Lan+a+e Code Lan+a+e (o <orean (s <as"miri (u <urdis" (y <ir$"iC *a Latin *n Lin$a*a *o Laot"ian *t Lit"uanian * Latian, Lettis" m$ Ma*a$asy mi Maori m( Macedonian m* Ma*aya*am mn Mon$o*ian mo Mo*daian mr Marat"i ms Ma*ay mt Ma*tese my +urmese na 4auru ne 4epa*i n* Dutc" no 4or%e$ian oc 1ccitan om ,Afan. 1romo or 1riya pa 'un/abi p* 'o*is" ps 'as"to, 'us"to pt 'ortu$uese 8u _uec"ua rm R"aeto9Romance rn <irundi ro Romanian ru Russian r% <inyar%anda sa Sans(rit sd Sind"i s$ San$"o s" Serbo9#roatian si Sin"a*ese s( S*oa( s* S*oenian sm Samoan sn S"ona so Soma*i s8 A*banian su Sundanese ss Sis%ati st Sesot"o s S%edis" s% S%a"i*i ta Tami* te Te*u$u t$ Ta/i( t" T"ai ti Ti$rinya t( Tur(men t* Ta$a*o$ tn Sets%ana to Ton$a tr Tur(is" ts Tson$a tt Tatar t% T%i u$ 5i$"ur u( 5(rainian ur 5rdu uC 5Cbe( i Oietnamese o Oo*apu( %o ;o*of 3" I"osa yi 6iddis" ,former*y /i. yo 6oruba Ca P"uan$ C" #"inese Cu Pu*u 320 able ((=. Locale country codes) capitalized by country. Code Contry Code Contry A0 Af$"anistan AL A*bania DP A*$eria AS American Samoa AD Andorra A1 An$o*a A) An$ui**a A_ Antarctica AJ Anti$ua and +arbuda AR Ar$entina AM Armenia A; Aruba A5 Austra*ia AT Austria AP ACerbai/an +S +a"amas +E +a"rain +D +an$*ades" ++ +arbados +6 +e*arus +2 +e*$ium +P +e*iCe +K +enin +M +ermuda +T +"utan +1 +o*iia +A +osnia and EerCe$o%ina +; +ots%ana +O +ouet )s*and +R +raCi* )1 +ritis" )ndian 1cean Territory +4 +runei Darussa*am +J +u*$aria +0 +ur(ina 0aso +) +urundi <E #ambodia #M #ameroon #A #anada #O #ape Oerde <6 #ayman )s*ands #0 #entra* African Repub*ic TD #"ad #L #"i*e #4 #"ina #I #"ristmas )s*and ## #ocos ,<ee*in$. )s*ands #1 #o*ombia <M #omoros #D #on$o, Democratic Repub*ic of ,%as Paire. #J #on$o, 'eop*eGs Repub*ic of #< #oo( )s*ands #R #osta Rica #) #ote DG)oire ER #roatia ,*oca* name: Erats(a. #5 #uba #6 #yprus #P #Cec" Repub*ic D< Denmar( DK D/ibouti DM Dominica D1 Dominican Repub*ic TL 2ast Timor 2# 2cuador 2J 2$ypt SO 2* Sa*ador J_ 28uatoria* Juinea 2R 2ritrea 22 2stonia 2T 2t"iopia 0< 0a*(*and )s*ands ,Ma*inas. 01 0aroe )s*ands 0K 0i/i 321 Code Contry Code Contry 0) 0in*and 0R 0rance 0I 0rance, Metropo*itan J0 0renc" Juiana '0 0renc" 'o*ynesia T0 0renc" Sout"ern Territories JA Jabon JM Jambia J2 Jeor$ia D2 Jermany JE J"ana J) Jibra*tar JR Jreece JL Jreen*and JD Jrenada J' Juade*oupe J5 Juam JT Juatema*a J4 Juinea J; Juinea9+issau J6 Juyana ET Eaiti EM Eeard and Mc Dona*d )s*ands E4 Eonduras E< Eon$ <on$ E5 Eun$ary )S )ce*and )4 )ndia )D )ndonesia )R )ran ,)s*amic Repub*ic 1f. )_ )ra8 )2 )re*and )L )srae* )T )ta*y KM Kamaica K' Kapan K1 Kordan <P <aCa("stan <2 <enya <) <iribati <' <orea, Democratic 'eop*eGs Repub*ic 1f <R <orea, Repub*ic 1f <; <u%ait <J <yr$yCstan LA Lao 'eop*eGs Democratic Repub*ic LO Latia L+ Lebanon LS Lesot"o LR Liberia L6 Libyan Arab Kama"iriya L) Liec"tenstein LT Lit"uania L5 Lu3embour$ M< Macedonia, T"e 0ormer 6u$os*a Repub*ic 1f MJ Mada$ascar M; Ma*a%i M6 Ma*aysia MO Ma*dies ML Ma*i MT Ma*ta ME Mars"a** )s*ands M_ Martini8ue MR Mauritania M5 Mauritius 6T Mayotte MI Me3ico 0M Micronesia, 0ederated States 1f MD Mo*doa, Repub*ic 1f M# Monaco M4 Mon$o*ia MS Montserrat MA Morocco MP MoCambi8ue MM Myanmar 4A 4amibia 4R 4auru 322 Code Contry Code Contry 4' 4epa* 4L 4et"er*ands A4 4et"er*ands Anti**es 4# 4e% #a*edonia 4P 4e% Pea*and 4) 4icara$ua 42 4i$er 4J 4i$eria 45 4iue 40 4orfo*( )s*and M' 4ort"ern Mariana )s*ands 41 4or%ay 1M 1man '< 'a(istan '; 'a*au 'S 'a*estinian Territory, 1ccupied 'A 'anama 'J 'apua 4e% Juinea '6 'ara$uay '2 'eru 'E '"i*ippines '4 'itcairn 'L 'o*and 'T 'ortu$a* 'R 'uerto Rico _A _atar R2 Reunion R1 Romania R5 Russian 0ederation R; R%anda <4 Saint <itts And 4eis L# Saint Lucia O# Saint Oincent and T"e Jrenadines ;S Samoa SM San Marino ST Sao Tome and 'rincipe SA Saudi Arabia S4 Sene$a* S# Seyc"e**es SL Sierra Leone SJ Sin$apore S< S*oa(ia ,S*oa( Repub*ic. S) S*oenia S+ So*omon )s*ands S1 Soma*ia PA Sout" Africa JS Sout" Jeor$ia and T"e Sout" Sand%ic" )s*ands 2S Spain L< Sri Lan(a SE St& Ee*ena 'M St& 'ierre And Mi8ue*on SD Sudan SR Suriname SK Sa*bard And Kan Mayen )s*ands SP S%aCi*and S2 S%eden #E S%itCer*and S6 Syrian Arab Repub*ic T; Tai%an TK Ta/i(istan TP TanCania, 5nited Repub*ic 1f TE T"ai*and TJ To$o T< To(e*au T1 Ton$a TT Trinidad and toba$o T4 Tunisia TR Tur(ey TM Tur(menistan T# Tur(s And #aicos )s*ands TO Tua*u 5J 5$anda 5A 5(raine A2 5nited Arab 2mirates 323 Code Contry Code Contry J+ 5nited <in$dom 5S 5nited States 5M 5nited States Minor 1ut*yin$ )s*ands 56 5ru$uay 5P 5Cbe(istan O5 Oanuatu OA Oatican #ity State ,Eo*y See. O2 OeneCue*a O4 Oiet 4am OJ Oir$in )s*ands ,+ritis". O) Oir$in )s*ands ,5&S&. ;0 ;a**is and 0utuna )s*ands 2E ;estern Sa"ara 62 6emen 65 6u$os*aia PM Pambia P; Pimbab%e ) ma(e e3tensie use of sty*es in t"e 11o documents t"at ) %rite& ) use a specific para$rap" sty*e to format my code samp*es& 2ac" para$rap" sty*e a**o%s you to set t"e defau*t c"aracter attributes to use in t"e para$rap"& )n 11o, c"aracters specify t"e *oca*e so ) set t"e *oca*e for t"is para$rap" sty*e to un(no%n7 t"is preents t"e spe**9c"ec(er from c"ec(in$ my code samp*es& To te** 11o t"at a %ord is 0renc", and s"ou*d be c"ec(ed as 0renc", set t"e *oca*e of t"e c"aracters to 0renc"& T"e code in Listin$ 2B6 traerses t"e para$rap"s in a document and sets t"e *oca*e on eac" one& Listing 296. *et a simple 'riter document to use a +rench locale. Sub Set-ocu!ent,ocale -i! a,ocale A# He* co!&#un&#tar&lan&,ocale a,ocale&,anuae 6 "$r" )Set t(e ,ocale to u#e t(e "renc( lanuae a,ocale&Countr. 6 ""R" )Set t(e ,ocale to u#e "rance a# t(e countr. -i! oCur#or )Cur#or u#ed to tra:er#e t(e docu!ent& -i! o3ext )3(e docu!ent text obNect o3ext 6 3(i#Co!ponent&3ext )Writer docu!ent# (a:e a 3ext obNect oCur#or 6 o3ext&create3extCur#orBC )Create a text cur#or REM Mo:e cur#or to t(e #tart o$ t(e docu!ent and do not #elect text& oCur#or&Jo3oStartB"al#eC REM Mo:e to t(e end o$ t(e pararap(= #electin t(e entire pararap(& REM otoHextPararap(BC return# "al#e i$ it $ail#& -o W(ile oCur#or&otoHextPararap(B3rueC oCur#or&C(ar,ocale 6 a,ocale )3(i# can $ail $or #o!e pararap( t.pe# oCur#or&oRi(tB7= "al#eC )-e#elect all text ,oop End Sub T"e spe**9c"ec(er, "yp"enation, and t"esaurus a** re8uire a *oca*e to function& T"ey %i** not function, "o%eer, if t"ey arenGt proper*y confi$ured& 5se Tools Options !anguage Settings -riting Ai&s to confi$ure t"ese in 11o& T"e macro in Listin$ 2BM obtains a Spe**#"ec(er, Eyp"enator, and T"esaurus, a** of %"ic" re8uire a Loca*e ob/ect& Listing 297. *pell /heck) &yphenate) and hesaurus. Sub SpellC(ec1Exa!ple 324 -i! #BC )Contain# t(e *ord# to c(ec1 -i! :Return )Oalue returned $ro! SpellC(ec1er= H.p(enator= and 3(e#auru# -i! i A# Inteer )0tilit. index :ariable -i! !#F )Me##ae #trin
REM Alt(ou( I create an e!pt. aru!ent arra.= I could al#o REM u#e Arra.BC to return an e!pt. arra.& -i! e!pt.Ar#BC a# ne* co!&#un&#tar&bean#&Propert.Oalue
) Call t(e etPrinterHa!e# !et(od on t(e PrinterSer:er obNect& aHa!e# 6 oMet(od&in:o1eBoPrintSer:er= Arra.BCC M#Box MoinBaHa!e#= CHRFB>7CC End Sub TIP )f 11o does not reco$niCe your printer by itVs name, surround t"e printer name %it" an$*e brac(ets D[printer=nameRF, in t"e past some printers re8uired t"is& Prior to OOo 3.5, the PrinterServer cannot be used from Basic, because XTypeProvider is not declared to be inherited by that class; although it is implemented in the class. Basic cannot, therefore, recognize the methods supported by the object. The code in Listing 299 demonstrates how to call the method directly. 13.1. 3rinting documents T"e primary printin$ functiona*ity is common to a** 11o document types& T"e interface com&sun&star&ie%&I'rintab*e defines t"ree met"ods ,see Tab*e 113.& able ((F. Ob%ect methods defined by com.sun.star.view.:9rintable. O27ect )et6od Description $et'rinter,. Defau*t printer as an array of properties ,com&sun&star&ie%&'rinterDescriptor.& set'rinter,properties. Assi$n a ne% printer to t"e ob/ect ,com&sun&star&ie%&'rinterDescriptor.& print,properties. 'rint t"e document ,com&sun&star&ie%&'rint1ptions.& T"e ob/ect met"od $et'rinter,. returns an array of properties t"at describe t"e printer ,see 0i$ure B0.& T"e macro in Listin$ 300 demonstrates "o% to access and interpret eac" of t"e properties ,see Tab*e 11! for supported properties.& 327 Listing 300. #isplay printer properties. Sub -i#pla.PrinterPropertie# -i! Prop# )Arra. o$ co!&#un&#tar&bean#&Propert.Oalue -i! iG )Index :ariable o$ t.pe Inteer -i! #F )-i#pla. #trin -i! : ) -i! #Ha!eF ) On Error Re#u!e Hext Prop# 6 3(i#Co!ponent&etPrinterBC "or i 6 7 3o 0BoundBProp#C #Ha!e 6 prop#BiC&Ha!e : 6 prop#BiC&Oalue # 6 # 4 #Ha!e 4 " 6 " I$ #Ha!e 6 "PaperOrientation" 3(en REM co!&#un&#tar&:ie*&PaperOrientation&,AH-SCAPE al#o #upported # 6 # 4 II$B:6co!&#un&#tar&:ie*&PaperOrientation&POR3RAI3=5 "Portrait"= ",and#cape"C 4 " 6 " 4 CStrB:C El#eI$ #Ha!e 6 "Paper"or!at" 3(en Select Ca#e : Ca#e co!&#un&#tar&:ie*&Paper"or!at&A% # 6 # 4 "A%" Ca#e co!&#un&#tar&:ie*&Paper"or!at&A? # 6 # 4 "A?" Ca#e co!&#un&#tar&:ie*&Paper"or!at&A< # 6 # 4 "A<" Ca#e co!&#un&#tar&:ie*&Paper"or!at&B? # 6 # 4 "B?" Ca#e co!&#un&#tar&:ie*&Paper"or!at&B< # 6 # 4 "B<" Ca#e co!&#un&#tar&:ie*&Paper"or!at&,E33ER # 6 # 4 ",E33ER" Ca#e co!&#un&#tar&:ie*&Paper"or!at&,EJA, # 6 # 4 ",EJA," Ca#e co!&#un&#tar&:ie*&Paper"or!at&3AB,OI- # 6 # 4 "3AB,OI-" Ca#e co!&#un&#tar&:ie*&Paper"or!at&0SER # 6 # 4 "0SER" Ca#e El#e # 6 # 4 "0n1no*n :alue" End Select # 6 # 4 " 6 " 4 CStrB:C El#eI$ #Ha!e 6 "PaperSi8e" 3(en REM t.pe i# co!&#un&#tar&a*t&Si8e REM 3(e #i8e i# in 3WIPS and t(ere are >??7 t*ip# per inc( #6# 4 C-blB:&Widt(C+>??7&7 4 "x" 4 C-blB:&Hei(tC+>??7&7 4 " Binc(e#C" El#e # 6 # 4 CStrB:C End I$ # 6 # 4 CHRFB>7C Hext M#Box #= 7= "Printer Propertie#" End Sub 328 Figure 90. 9roperties of the default printer. able ((2. 9roperties defined by the service com.sun.star.view.9rinter#escriptor. Property Description 4ame 4ame of t"e printer 8ueue& 'aper1rientation 'aper orientation ,com&sun&star&ie%&'aper1rientation.& 'aper0ormat 'redefined paper siCes ,com&sun&star&ie%&'aper0ormat.& 'aperSiCe 'aper siCe in t%ips ,com&sun&star&a%t&SiCe.& )s+usy )s t"e printer busy> #anSet'aper1rientation #an t"e paper orientation be set> #anSet'aper0ormat Are ot"er paper formats supported> #anSet'aperSiCe #an t"e paper siCe be set> TIP A*t"ou$" you can set t"e printer as of 11o 1&1&1, no met"od is proided in 11o +asic to obtain a *ist of printers& )f you rea**y need a *ist of printers, try ca**in$ an e3terna* DLL or %ritin$ code to searc" confi$uration fi*es&>>> #a** t"e print,. met"od %it" no properties to print a sin$*e copy of t"e document to t"e current printer& A** of t"e document types support t"e properties in Tab*e 11A& T"e 'a$es property supports t"e standard format used in t"e 'rint dia*o$& T"e format strin$ D1, 3, !9M, B9F prints pa$es 1, 3, ! t"rou$" M, and B t"rou$" t"e *ast pa$e& able ((I. 9roperties defined by com.sun.star.view.9rintOptions. Property Description #opy#ount 4umber of copies to print& 0i*e4ame Send t"e output to a fi*e rat"er t"an to t"e printer& #o**ate #o**ate t"e printed pa$es ,set to True or 0a*se.& 'a$es Specifies pa$es and pa$e ran$es to print& Listing 301. 9rint pages FC and F( of the current document. -i! Prop#B>C A# He* co!&#un&#tar&bean#&Propert.Oalue Prop#B7C&Ha!e 6 "Pae#" : Prop#B7C&Oalue 6 "%79%>" 329 3(i#Co!ponent&printBProp#BCC ;"en a document is printed, contro* returns to t"e ca**er before t"e printin$ is comp*ete& )f you c*ose t"e document before printin$ is done, 1pen1ffice&or$ is *i(e*y to cras" because t"e 11o interna*s are sti** usin$ t"e document& )tGs possib*e to set up an eent *istener t"at %atc"es for t"e print /ob to finis", but t"ereGs an easier %ay t"at isnGt current*y documented& T"e print,. met"od accepts an array of properties t"at direct t"e printin$& T"e D%aitF ar$ument %it" a +oo*ean a*ue of True instructs t"e print,. met"od to not return unti* after printin$ is comp*ete& >> As of May 1M, 2011 %it" 11o 3&3, t"e %ait ar$ument does not %or(7 s print *istener is demonstrated in section 13&1A&3& A #a*c e3amp*e %it" a 'rint *istener& TIP #*osin$ a document %"i*e 1pen1ffice&or$ is printin$ t"e document can cause 1pen1ffice&or$ to cras"& 5se t"e D%aitF property to aoid t"is prob*em& 1n 5ni39type computers, printers are confi$ured to %or( %it" 1pen1ffice&or$ usin$ t"e DspadminF uti*ity& After a printer "as been confi$ured for 11o, it is aai*ab*e for use by name& 6ou can sti** use printers t"at "ae not been confi$ured for 11o, but you must enc*ose t"e printer name bet%een t"e c"aracters D[F and DRF& To print %it" a printer ot"er t"an t"e defau*t, use code simi*ar to t"e fo**o%in$: Public oProp#B7C a# He* co!&#un&#tar&bean#&Propert.Oalue Public oOpt#B>C a# He* co!&#un&#tar&bean#&Propert.Oalue -i! o-oc )-ocu!ent to print& -i! oPrinter )Arra. o$ propertie# t(at de$ine t(e printer& -i! #0rlF )0R, o$ t(e docu!ent to load and print& -i! #PrinterF )Ha!e o$ t(e printer& REM Set t(e na!e o$ t(e printer a# 1no*n b. t(e #.#te!& #Printer 6 "HP9Color9,a#erMet9?A<7-H" REM ,oad t(e docu!ent in (idden !ode #o it i# not :i#ible REM on t(e #creen& oProp#B7C&Ha!e 6 "Hidden" oProp#B7C&Oalue 6 3rue REM Ho* load t(e docu!ent& #0rl 6 "$ile:+++c:+te#t5doc&#x*" o-oc 6 o-e#1&,oadCo!ponent"ro!0rlB#0rl= "5blan1"= A%= oProp#BCC REM Obtain t(e current printer obNect $ro! t(e docu!ent& REM 3(i# i# reall. an arra. o$ propert. :alue#& REM C(ane t(e na!e o$ t(e obNect to re$erence t(e printer t(at REM .ou *ant to u#e& Hotice t(at t(e printer na!e i# t(e #.#te! na!e& oPrinter 6 o-oc&etPrinterBC "or i 6 ,BoundBoPrinterC to 0BoundBoPrinterC I$ oPrinterBiC&Ha!e 6 "Ha!e" 3(en oPrinterBiC&Oalue 6 #Printer End I$ Hext i REM Set t(e printer bac1 into t(e docu!ent& 3(e onl. t(in REM t(at (a# c(aned i# t(e printer na!e& o-oc&#etPrinterBoPrinterC REM Ho*= #et up t(e print option# $or actual printin& 330 REM Hotice t(at t(e printer na!e i# #urrounded b. t(e c(aracter# E and D& REM Al#o notice t(at t(e printBC !et(od i# #et to not return until REM a$ter printin i# co!pleted& oOpt#B7C&Ha!e 6 "Ha!e" oOpt#B7C&Oalue 6 "E" 4 #Printer 4 "D" oOpt#B>C&Ha!e 6 "Wait" oOpt#B>C&Oalue 6 3rue o-oc&PrintBoOpt#BCC TIP Eistorica**y, it "as been e3perimenta**y determined t"at you must set t"e destination printer in t"e document before tryin$ to print to a printer ot"er t"an t"e defau*t& 1#.1,.1. <rinting 8riter documents Different document types support e3tra options for printin$& Te3t documents support t"e interface com&sun&star&te3t&I'a$e'rintab*e ,see Tab*e 116.& T"e I'a$e'rintab*e interface imp*ements an a*ternate met"od of printin$ t"e document t"at proides more contro* of t"e output& T"e primary adanta$e is t"at you can print mu*tip*e pa$es from t"e document on a sin$*e output pa$e& able ((G. Methods defined by the com.sun.star.te.t.:9age9rintable interface. O27ect )et6ods Description $et'a$e'rintSettin$s,. Returns an array of properties ,see Tab*e 11M.& set'a$e'rintSettin$s,properties. #"an$e t"e settin$s ,see Tab*e 11M.& print'a$es,properties. 'rint usin$ properties in Tab*e 11A& T"e ob/ect met"od print'a$es,. accepts t"e same properties as t"e print,. met"od ,see Tab*e 11A.& T"e met"ods to $et and set t"e pa$e print properties are out*ined in Tab*e 11M& T"e macro in Listin$ 302 obtains and prints t"e current pa$e print properties, s"o%n in 0i$ure B1& able ((T. 9roperties used by the com.sun.star.te.t.:9age9rintable interface. Property Description 'a$eRo%s 4umber of ro%s of pa$es on eac" printed pa$e& 'a$e#o*umns 4umber of co*umns of pa$es on eac" printed pa$e& LeftMar$in Left mar$in& Ri$"tMar$in Ri$"t mar$in& TopMar$in Top mar$in& +ottomMar$in +ottom mar$in& EoriMar$in Mar$in bet%een ro%s of pa$es& OertMar$in Mar$in bet%een co*umns of pa$es& )sLandscape True or 0a*se7 print in *andscape format& Listing 302. #isplay 9age 9rint 9roperties. Sub -i#pla.PaePrintPropertie# -i! Prop# )Arra. o$ co!&#un&#tar&bean#&Propert.Oalue -i! iG )Index :ariable o$ t.pe Inteer 331 -i! #F )-i#pla. #trin I$ Ha#0noInter$ace#B3(i#Co!ponent= "co!&#un&#tar&text&/PaePrintable"C 3(en Prop# 6 3(i#Co!ponent&etPaePrintSettin#BC "or i 6 7 3o 0BoundBProp#C # 6 # 4 prop#BiC&Ha!e 4 " 6 " 4 CStrBprop#BiC&OalueC 4 CHRFB>7C Hext M#Box #= 7= "Pae Print Propertie#" El#e Print "Sorr.= t(i# docu!ent doe# not #upport t(e /PaePrintable inter$ace" End I$ End Sub Figure 91. 9age print properties of a 'riter document. T"e macro in Listin$ 303 attempts to print a document %it" t%o pa$es on eac" printed pa$e in *andscape mode& ;it" my *atest testin$ in 11o ersion 3&3, t"e document is printed norma**y, %"ic" is an improement oer t"e preious be"aior of cras"in$ 11o& Listing 303. 9rint wo 9er 9age. Sub Print3*oPerPae -i! Prop#B7 3o >C A# He* co!&#un&#tar&bean#&Propert.Oalue Prop#B7C&Ha!e 6 "PaeColu!n#" : Prop#B7C&Oalue 6 ' Prop#B>C&Ha!e 6 "I#,and#cape" : Prop#B>C&Oalue 6 3rue I$ Ha#0noInter$ace#B3(i#Co!ponent= "co!&#un&#tar&text&/PaePrintable"C 3(en 3(i#Co!ponent&#etPaePrintSettin#BProp#BCC ) 3(i#Co!ponent&printPae#BArra.BCC )0#e de$ault propertie# El#e Print "Sorr.= t(i# docu!ent doe# not #upport t(e /PaePrintable inter$ace" End I$ End Sub TIP T"e print dia*o$ %as si$nificant*y improed in 11o 3&3, but t"e c"an$es bro(e print properties : "ttp:--openoffice&or$-bu$Ci**a-s"o%=bu$&c$i>id?11MM@3 A*t"ou$" t"e macro in Listin$ 303 stopped %or(in$ %it" 11o 1&1&1, a sma** modification a**o%s t"e macro to run& T"e ne% macro sti** causes 11o to cras" under Linu3 and to c*ose t"e document under ;indo%s, but it does mana$e to print t"e document& As %it" Listin$ 303, t"e document is printed in portrait mode rat"er t"an *andscape mode L t"is is an 11o bu$& 332 1#.1,.2. <rinting Calc documents To perform specia* printin$ functions %it" a ;riter document, a specia* ob/ect met"od is ca**ed& To perform specia* printin$ functions %it" #a*c documents, you must modify t"e document properties and pa$e9sty*e properties and t"en use t"e standard print,. met"od& 0or e3amp*e, it is common for a #a*c s"eet to be too *ar$e to fit on a sin$*e s"eet of paper& To sca*e t"e s"eet to fit on a specified number of pa$es, set t"e Sca*eTo'a$es property to contain t"e number of pa$es t"at s"ou*d contain t"e s"eet& To simp*y sca*e t"e pa$e based on a percenta$e, use t"e 'a$eSca*e property ,see Listin$ 30!.& Listing 304. 9rint a spreadsheet at =I percentE this is very small5 Sub PrintScaledSpread#(eet -i! #F )St.le na!e -i! oSt.le )3(e current pae #t.le REM 0#e t(e currentl. acti:e #(eet to obtain t(e pae #t.le& REM In a Calc docu!ent= t(e current controller 1no*# *(ic( #(eet REM i# acti:e& # 6 3(i#Co!ponent&CurrentController&etActi:eS(eetBC&PaeSt.le oSt.le 6 3(i#Co!ponent&St.le"a!ilie#&etB.Ha!eB"PaeSt.le#"C&etB.Ha!eB#C REM oSt.le&PaeScale 6 >77 -e$ault :alue i# >77 Ba# in >77GC REM oSt.le&Scale3oPae# 6 7 -e$ault :alue i# 7= a# in don)t #cale oSt.le&PaeScale 6 '< )Scale docu!ent to '<G B:er. :er. :er. #!allC 3(i#Co!ponent&PrintBArra.BCC )Print t(e docu!ent End Sub T"e second aspect to printin$ #a*c documents ino*es settin$ t"e area to print a*on$ %it" t"e co*umn and ro% tit*es ,see Tab*e 11@.& able ((0. 9roperties used by the com.sun.star.sheet.:9rint-reas interface. O27ect )et6od Description $et'rintAreas,. Return array of type com&sun&star&tab*e&#e**Ran$eAddress& set'rintAreas,ran$es. Set print areas for t"e s"eet %it" array of type #e**Ran$eAddress& 'rint eeryt"in$ if not"in$ is set& $et'rintTit*e#o*umns,. Return True if tit*e co*umns are repeated to t"e ri$"t& set'rintTit*e#o*umns,boo*ean. Set True if tit*e co*umns are repeated on a** print pa$es to t"e ri$"t& $etTit*e#o*umns,. Array of type com&sun&star&tab*e&#e**Ran$eAddress& setTit*e#o*umns,ran$es. Set co*umns to use as tit*es& Ro%s are i$nored7 on*y co*umns matter& $et'rintTit*eRo%s,. Return True if tit*e ro%s are repeated on a** print pa$es& set'rintTit*eRo%s,boo*ean. Set to True if ro% tit*es are repeated on a** print pa$es to t"e bottom& $etTit*eRo%s,. Return array of type com&sun&star&tab*e&#e**Ran$eAddress& setTit*eRo%s,ran$es. Set ro%s to use as tit*es& #o*umns are i$nored7 on*y ro%s matter& T"e met"ods in Tab*e 11@ are based on s"eets in a #a*c document7 as opposed to t"e entire #a*c document& T"e macro in Listin$ 30A sets t%o print ran$es and t"en prints t"e document& 2ac" print ran$e is printed on a ne% pa$e& Listing 305. *et and print multiple ranges in a /alc document. Sub PrintSpread#(eetArea# 333 -i! oRane#B>C A# He* co!&#un&#tar&table&CellRaneAddre## oRane#B7C&S(eet 6 7 oRane#B7C&StartColu!n 6 7 : oRane#B7C&StartRo* 6 7 )A> oRane#B7C&EndColu!n 6 % : oRane#B7C&EndRo* 6 ? )-<
3(i#Co!ponent&CurrentController&etActi:eS(eetBC&#etPrintArea#BoRane#BCC 3(i#Co!ponent&PrintBArra.BCC End Sub 1#.1,.#. ) Calc example 1ith a <rint listener S"eet1 in a #a*c document contains a button t"at prints S"eet2 and *eaes S"eet1 as t"e actie s"eet& To print S"eet2, it must be made t"e actie s"eet& T"e code %as structured as fo**o%s: 1& Set S"eet2 actie& 2& #a** t"e document *ee* print met"od& 3& Set S"eet1 actie& T"e print met"od returns immediate*y and t"e document is printed in t"e bac($round& S"eet1, t"erefore, becomes t"e actie s"eet before printin$ be$ins, so S"eet1 is printed rat"er t"an S"eet2& T"e correct so*ution is to re$ister a print *istener t"at sets S"eet1 actie after printin$ is comp*ete& A *istener is stored in a J*oba* ariab*e so t"at is *ies after t"e macro is finis"ed runnin$& +e %arned, "o%eer, t"at if you edit any macro t"e $*oba* ariab*e %i** be erased but t"e *istener %i** sti** be re$istered7 and you %i** "ae no %ay to unre$ister it %it"out c*osin$ t"e document& So, first, create t"e ariab*es to reference t"e *istener& T"e document is a*so stored, but ) cou*d "ae referenced T"is#omponent instead& Listing 306. <lobal variables that reference the listener and the document. Jlobal oPrint,i#tener Jlobal oPrintMob,i#tner-oc T"e current actie s"eet is set as part of t"e rea* %or*d macro, so it is a*so s"o%n "ere& Listing 307. Utility routine to set a /alc documentPs active sheet. REM ******************************* REM ** o-oc 9 Calc #(eet on *(ic( to operate& Ho error c(ec1in i# per$or!ed REM ** #S(eetHa!e 9 S(eet na!e to !a1e acti:e& 3(e #(eet i# :eri$ied to exi#t& REM ******************************* Sub #et5acti:e5#(eetBo-oc= #S(eetHa!eC -i! oS(eet# oS(eet# 6 o-oc&S(eet# I$ oS(eet#&(a#B.Ha!eB#S(eetHa!eC 3(en o-oc¤tController&#etActi:eS(eetBoS(eet#&etB.Ha!eB#S(eetHa!eCC End I$ End Sub 334 An eent is sent to t"e *istener if t"e *istener is bein$ disposed& T"e te3t Dprint=*istener=F prefi3es t"e routines used to imp*ement t"e *istener& Listing 308. 9rint listener disposing method. REM ******************************* REM ** 3(e print Nob i# di#po#in= #o= re!o:e it& REM ******************************* Sub print5li#tener5di#po#inBoE:entC On Error Re#u!e Hext -i! e!pt.ObN I$ HO3 I#HullBoPrintMob,i#tner-ocC AH- HO3 I#EMpt.BoPrintMob,i#tner-ocC 3(en oPrintMob,i#tner-oc&re!o:ePrintMob,i#tenerBoPrint,i#tenerC oPrintMob,i#tner-oc 6 e!pt.ObN End I$ End Sub T"e *istener is ca**ed eery time t"e print /ob c"an$es state& Listing 309. 9rint listener status changed event. REM ******************************* REM ** Called e:er.ti!e t(e #tate o$ t(e print Nob c(ane#& REM ** Error !e##ae# are printed i$ t(e. occur& REM ** I$ t(e e:ent announce# an error or t(at t(e Nob i# $ini#(ed= REM ** t(e print Nob li#tener i# re!o:ed and t(e "Input -ata" #(eet i# #et to acti:e& REM ******************************* Sub print5li#tener5printMobE:entBoPrintMobE:entC -i! bCleanup A# Boolean ) Set to true i$ t(e li#tener #(ould be re!o:ed& -i! #Me##aeF ) I$ not e!pt.= a !e##ae i# printed& REM All #upported e:ent #tate c(ane# are #(o*n& Select Ca#e oPrintMobE:ent&State Ca#e co!&#un&#tar&:ie*&PrintableState&MOB5S3AR3E- ) Renderin t(e docu!ent to print& bCleanup 6 "al#e Ca#e co!&#un&#tar&:ie*&PrintableState&MOB5COMP,E3E- ) Renderin i# $ini#(ed= #tart #poolin& bCleanup 6 "al#e Ca#e co!&#un&#tar&:ie*&PrintableState&MOB5SPOO,E- ) Succe##K )#Me##ae 6 "Print Nob #pooled to t(e printer&" bCleanup 6 3rue Ca#e co!&#un&#tar&:ie*&PrintableState&MOB5ABOR3E- #Me##ae 6 "Printin *a# aborted&" bCleanup 6 3rue Ca#e co!&#un&#tar&:ie*&PrintableState&MOB5"AI,E- #Me##ae 6 "Error printin&" bCleanup 6 3rue Ca#e co!&#un&#tar&:ie*&PrintableState&MOB5SPOO,IHJ5"AI,E- #Me##ae 6 "-ocu!ent $ailed to print or #pool to t(e print&" bCleanup 6 3rue Ca#e El#e #Me##ae 6 "0n1no*n unexpected print #tate&" bCleanup 6 3rue 335 End Select REM Re!o:e t(e li#tener i$ printin i# $ini#(ed= t(en call a *or1er !acro REM to #et S(eet> a# acti:e& I$ bCleanup AH- HO3 I#HullBoPrintMob,i#tner-ocC AH- HO3 I#EMpt.BoPrintMob,i#tner-ocC 3(en On Error Re#u!e Hext -i! e!pt.ObN oPrintMob,i#tner-oc&re!o:ePrintMob,i#tenerBoPrint,i#tenerC Call #et5acti:e5#(eetBoPrintMob,i#tner-oc= "S(eet>"C oPrintMob,i#tner-oc 6 e!pt.ObN End I$ I$ #Me##ae ED "" 3(en M#Box #Me##ae End I$ End Sub )f t"e s"eet name e3ists, t"e desired s"eet is set to be actie, t"e print /ob *istener is created and re$istered, and t"en document printin$ is re8uested& Listing 310. 9rint the specified sheet. Sub PrintS(eetBo-oc= #S(eet3oPrintC -i! #Pre$ixF ) Pre$ix u#ed to identi$. t(e print li#tener routine#& -i! #Ser:iceF ) Print li#tener #er:ice na!e& #Pre$ix 6 "print5li#tener5" #Ser:ice 6 "co!&#un&#tar&:ie*&/PrintMob,i#tener" I$ HO3 o-oc&#(eet#BC&(a#B.Ha!eB#S(eet3oPrintC 3(en M#Box "-ocu!ent doe# not contain a #(eet na!ed " 4 #S(eet3oPrint Exit #ub End I$ Call #et5acti:e5#(eetBo-oc= #S(eet3oPrintC
oPrint,i#tener 6 Create0no,i#tenerB#Pre$ix= #Ser:iceC o-oc&addPrintMob,i#tenerBoPrint,i#tenerC oPrintMob,i#tner-oc 6 o-oc o-oc&PrintBArra.BCC End Sub 1#.1,.$. <rint examples b" 5incent 5an ;outte ) found some ery nice e3amp*es by Oincent Oan Eoutte, t"at "e "as $racious*y a**o%ed me to reproduce "ere& Some "i$"*i$"ts of t"e contained macros: printDoc H 'rint a document %it" specific paper siCe, %it" specific paper trays, and %it" ,or %it"out. a pa$e bac($round ima$e& 4umerous stub met"ods are inc*uded to ca** t"is one routine& 4ote t"at t"e met"od direct*y specifies t"e destination printer& print'a$e H Same as printDoc, but prints a sin$*e pa$e& c*oseDocument H #*ose t"e specified document& 23portAs'dfAndSend2mai* H 23port as a 'D0 document and send an emai*& 336 TIP T"e ery popu*ar routine 0ind#reate4umber0ormatSty*e ,see Listin$ 3M0. is used by Listin$ 311& Listing 311. 9rint e.amples by 3incent 3an &outte. Sub PrintWit(Cop.Sta!pBC ) 999999999999999999999999999999 ) 3(i# !acro in#ert# a )COPP)9#ta!p and print# t(e docu!ent ) *it(out t(e bac1roundB9i!aeC to tra.>& ) ) Written b. Oincent Oan Houtte B'7>7C ) 999999999999999999999999999999 REM In#ert ti!e#ta!p o$ #endin -i! #Action3ext AS Strin #Action3ext 6 "^OPIE" In#ert-3#ta!pB#Action3extC REM Print t(e pae Print-ocWit(outB3o3ra.>BC
REM Re!o:e t(e cop.#ta!p9$ra!e Re!o:e-3#ta!pBC End Sub Sub In#ert-3#ta!pB#Action3extC ) 999999999999999999999999999999 ) 3(i# !acro in#ert# a )-A3E+3IME)9#ta!p *it( #Action3ext )Printed) or )Sent) ) ) Written b. Oincent Oan Houtte B'7>>C ) 999999999999999999999999999999 -IM oCur#or= o3ext= o-oc AS ObNect o-oc 6 3(i#Co!ponent o3ext 6 o-oc&et3extBC oCur#or 6 o3ext&create3extCur#orBC oCur#or&o3oStartB"A,SEC REM Create t(e date and ti!e obNect# -IM o-ate= o3i!e AS ObNect o-ate 6 o-oc&createIn#tanceB"co!&#un&#tar&text&3ext"ield&-ate3i!e"C o-ate&I#"ixed 6 3R0E o-ate&I#-ate 6 3R0E o-ate&Hu!ber"or!at 6 "indCreateHu!ber"or!atSt.leB"- MMMM MMMM"= o-ocC
o3i!e 6 o-oc&createIn#tanceB"co!&#un&#tar&text&3ext"ield&-ate3i!e"C o3i!e&I#"ixed 6 3rue o3i!e&I#-ate 6 "al#e o3i!e&Hu!ber"or!at 6 "indCreateHu!ber"or!atSt.leB"00:MM"= o-ocC REM Create t(e $ra!e -IM o"ra!e-3 AS ObNect 337 o"ra!e-3 6 o-oc&createIn#tanceB"co!&#un&#tar&text&3ext"ra!e"C Wit( o"ra!e-3 &#etHa!eB""ra!e-3"C &Anc(or3.pe 6 co!&#un&#tar&text&3extContentAnc(or3.pe&A35PAJE &HoriOrient 6 co!&#un&#tar&text&HoriOrientation&HOHE &OertOrient 6 co!&#un&#tar&text&OertOrientation&HOHE &HoriOrientPo#ition 6 9?@77 &OertOrientPo#ition 6 9>A77 &*idt( 6 ?777 &(ei(t 6 ><77 &Border-i#tance 6 >77 End Wit( REM In#ert t(e $ra!e into t(e text docu!ent o3ext&in#ert3extContentB oCur#or= o"ra!e-3= 3rue C REM Write t(e text in#ide t(e $ra!e -IM oCur#or' AS ObNect oCur#or' 6 o"ra!e-3&create3extCur#orBC Wit( oCur#or' &c(arHei(t 6 >A &c(arWei(t 6 co!&#un&#tar&a*t&"ontWei(t&BO,- ¶AdNu#t 6 co!&#un&#tar&#t.le&Pararap(AdNu#t&CEH3ER End Wit( o"ra!e-3&in#ertStrinB oCur#or'= #Action3ext= "al#e C Wit( oCur#or' &c(arHei(t 6 @ &c(arWei(t 6 co!&#un&#tar&a*t&"ontWei(t&HORMA, ¶AdNu#t 6 co!&#un&#tar&#t.le&Pararap(AdNu#t&CEH3ER End Wit( o"ra!e-3&in#ertControlC(aracterB oCur#or'= co!&#un&#tar&text&ControlC(aracter&PARAJRAPH5BREA^= "al#e C o"ra!e-3&in#ert3extContentB oCur#or'= o-ate= "al#e C o"ra!e-3&in#ertControlC(aracterB oCur#or'= co!&#un&#tar&text&ControlC(aracter&,IHE5BREA^= "al#e C o"ra!e-3&in#ert3extContentB oCur#or'= o3i!e= "al#e C End Sub Sub Re!o:e-3#ta!pBC ) 999999999999999999999999999999 ) 3(i# !acro re!o:e# t(e )-A3E+3IME)9#ta!p created *it( t(e pre:iou# !acro ) ) Written b. Oincent Oan Houtte B'7>>C ) 999999999999999999999999999999 -IM o-oc= o3ext"ra!e#= o"ra!e-3 AS ObNect o-oc 6 3(i#Co!ponent REM ,oo1 $or t(e dateti!e#ta!p9$ra!e and re!o:e it 338 o3ext"ra!e# 6 o-oc&et3ext"ra!e# I$ o3ext"ra!e#&(a#B.Ha!eB""ra!e-3"C 3(en o"ra!e-3 6 o3ext"ra!e#&etB.Ha!eB""ra!e-3"C o"ra!e-3&di#po#eBC EndI$ End Sub Sub Print-ocWit(B3o3ra.> ) 999999999999999999999999999999 ) 3(i# !acro print# t(e docu!ent *it( t(e bac1roundB9i!aeC to t(e ) $ir#t papertra.& 3(i# i# onl. u#ed to #a:e on #tationar.= i$ .ou ) (a:e run out on #tationar. or i$ t(e #econd printertra. i# Na!!ed \C ) ) Written b. Oincent Oan Houtte B'7>7C ) 999999999999999999999999999999 -IM #3ra.> AS Strin -IM #3ra.' AS Strin -IM bB> AS Boolean -IM bB' AS Boolean -IM *ait AS Boolean #3ra.> 6 "3ra.>" #3ra.' 6 "3ra.>" bB> 6 3rue bB' 6 "al#e *ait 6 3rue print-ocB#3ra.>= #3ra.'= bB>= bB'= *aitC End Sub Sub Print-ocWit(outB3o3ra.> ) 999999999999999999999999999999 ) 3(i# !acro print# t(e docu!ent *it(out t(e bac1roundB9i!aeC to t(e ) $ir#t papertra.& 3(i# i# u#e$ul $or copie# o$ t(e letter# .ou #ent out& ) ) Written b. Oincent Oan Houtte B'7>7C ) 999999999999999999999999999999 -IM #3ra.> AS Strin -IM #3ra.' AS Strin -IM bB> AS Boolean -IM bB' AS Boolean -IM *ait AS Boolean #3ra.> 6 "3ra.>" #3ra.' 6 "3ra.>" bB> 6 "al#e bB' 6 "al#e *ait 6 3rue print-ocB#3ra.>= #3ra.'= bB>= bB'= *aitC End Sub Sub Print-ocWit(outB3o3ra.'5old ) 999999999999999999999999999999 ) 3(i# !acro print# t(e docu!ent *it(out t(e bac1roundB9i!aeC to t(e ) #econd papertra.& 3(i# i# u#e$ul *(en .ou (a:e pre9printed #tationar.: ) .ou can #et an i!ae a# a bac1round= t(at .ou don)t *ant to print= 339 ) but t(at .ou *ant to #(o* up *(en con:erted to P-"& ) ) Written b. Oincent Oan Houtte B'7>7C ) 999999999999999999999999999999 -IM #3ra.> AS Strin -IM #3ra.' AS Strin -IM bB> AS Boolean -IM bB' AS Boolean -IM *ait AS Boolean #3ra.> 6 "3ra.'" #3ra.' 6 "3ra.>" bB> 6 "al#e bB' 6 "al#e *ait 6 3rue print-ocB#3ra.>= #3ra.'= bB>= bB'= *aitC End Sub Sub Print-ocWit(outB3o3ra.' ) 999999999999999999999999999999 ) 3(i# !acro print# t(e $ir#t pae B*it(out t(e bac1roundi!aeC to t(e ) #econd papertra. and all ot(er pae# B*it(out t(e bac1roundi!aeC to t(e ) $ir#t papertra.& ) 3(i# i# u#e$ul *(en .ou (a:e pre9printed #tationar.= but *ant to #a:e on it ) b. onl. printin t(e $ir#t pae on expen#i:e #tationar. ) .ou can #et an i!ae a# a bac1round= t(at .ou don)t *ant to print= ) but t(at .ou *ant to #(o* up *(en con:erted to P-"& ) ) Written b. Oincent Oan Houtte B'7>>C ) 999999999999999999999999999999 -IM o-oc AS ObNect -IM iPaeCount= n AS Inteer -IM #Pae AS Strin o-oc 6 3(i#Co!ponent REM Count t(e a!ount o$ pae# iPaeCount 6 o-oc&etCurrentControllerBC&etPropert.OalueB"PaeCount"C REM ,oop o:er e:er. pae n 6 > -o 0ntil n D iPaeCount
REM Print e:er. pae to t(e ri(t tra. I$ n 6 > 3(en Print5#tatBnC El#e Print5plainBnC End I$ n 6 n W > ,oop End Sub 340 Sub Print5#tatB#PaeHr AS StrinC ) 999999999999999999999999999999 ) 3(i# !acro print# t(e $ir#t pae *it(out t(e bac1roundB9i!aeC to t(e ) #econd papertra.& 3(i# i# u#e$ul *(en .ou (a:e pre9printed #tationar.: ) .ou can #et an i!ae a# a bac1round= t(at .ou don)t *ant to print= ) but t(at .ou *ant to #(o* up *(en con:erted to P-"& ) ) Written b. Oincent Oan Houtte B'7>>C ) 999999999999999999999999999999 -IM #3ra.> AS Strin -IM #3ra.' AS Strin -IM bB> AS Boolean -IM bB' AS Boolean -IM *ait AS Boolean #3ra.> 6 "3ra.'" #3ra.' 6 "3ra.>" bB> 6 "al#e bB' 6 "al#e *ait 6 3rue printPaeB#3ra.>= #3ra.'= bB>= bB'= *ait= #PaeHrC End Sub Sub Print5plainB#PaeHr AS StrinC ) 999999999999999999999999999999 ) 3(i# !acro print# t(e next pae *it(out t(e bac1roundB9i!aeC to t(e ) $ir#t papertra.& 3(i# i# u#e$ul *(en .ou *ant to #a:eon .our pre9printed #tationar.: ) .ou can #et an i!ae a# a bac1round= t(at .ou don)t *ant to print= ) but t(at .ou *ant to #(o* up *(en con:erted to P-"& ) ) Written b. Oincent Oan Houtte B'7>>C ) 999999999999999999999999999999 -IM #3ra.> AS Strin -IM #3ra.' AS Strin -IM bB> AS Boolean -IM bB' AS Boolean -IM *ait AS Boolean #3ra.> 6 "3ra.>" #3ra.' 6 "3ra.>" bB> 6 "al#e bB' 6 "al#e *ait 6 3rue printPaeB#3ra.>= #3ra.'= bB>= bB'= *ait= #PaeHrC End Sub Sub print-ocB#3ra.>= #3ra.'= bB>= bB'= *aitC ) 999999999999999999999999999999 ) 3(i# !acro print# t(e docu!ent i:en t(e c(o#en para!eter# ) ) Written b. Oincent Oan Houtte B'7>7C ) 999999999999999999999999999999 -IM o-oc AS ObNect o-oc 6 3(i#Co!ponent 341 REM Set bac1roundI!ae9option in -ocu!entSettin# to "al#e -IM oSettin# AS ObNect oSettin# 6 o-oc&createIn#tanceB"co!&#un&#tar&text&-ocu!entSettin#"C oSettin#&PrintPaeBac1round 6 bB> REM c(oo#e a certain printer -IM !PrinterOpt#B'C AS HEW co!&#un&#tar&bean#&Propert.Oalue !PrinterOpt#B7C&Ha!e 6 "Ha!e" !PrinterOpt#B7C&Oalue 6 "M"CQQQ7-H" !PrinterOpt#B>C&Ha!e 6 "Paper"or!at" !PrinterOpt#B>C&Oalue 6 co!&#un&#tar&:ie*&Paper"or!at&A? !PrinterOpt#B'C&Ha!e 6 "PaperOrientation" !PrinterOpt#B'C&Oalue 6 co!&#un&#tar&:ie*&PaperOrientation&POR3RAI3 o-oc&Printer 6 !PrinterOpt#BC REM #et Papertra. in St.le# -IM oSt.le AS ObNect -IM #PaeSt.le AS Strin #PaeSt.le 6 o-oc&CurrentController&etOie*Cur#orBC&PaeSt.leHa!e o#t.le 6 o-oc&St.le"a!ilie#&etB.Ha!eB"PaeSt.le#"C&etB.Ha!eB#PaeSt.leC oSt.le&PrinterPaper3ra. 6 #3ra.> REM Set printOption# -IM !PrintOpt#B'C AS HEW co!&#un&#tar&bean#&Propert.Oalue !PrintOpt#B7C&Ha!e 6 "Cop.Count" !PrintOpt#B7C&Oalue 6 > !PrintOpt#B>C&Ha!e 6 "Collate" !PrintOpt#B>C&Oalue 6 3rue !PrintOpt#B'C&Ha!e 6 "Wait" !PrintOpt#B'C&Oalue 6 3rue REM Print o-oc&PrintB!PrintOpt#BCC REM RESE3 OP3IOHS REM Re#et bac1roundI!ae9option in -ocu!entSettin# oSettin#&PrintPaeBac1round 6 bB' REM Re#et Papertra. in St.le# oSt.le&PrinterPaper3ra. 6 #3ra.' REM -o a 79print to co!plete t(e re#et -IM !PrintOpt#'B7C AS HEW co!&#un&#tar&bean#&Propert.Oalue !PrintOpt#'B7C&Ha!e 6 "Cop.Count" !PrintOpt#'B7C&Oalue 6 7 o-oc&PrintB!PrintOpt#'BCC End Sub Sub printPaeB#3ra.>= #3ra.'= bB>= bB'= *ait= #PaeHrC ) 999999999999999999999999999999 ) 3(i# !acro print# t(e docu!ent i:en t(e c(o#en para!eter# ) ) Written b. Oincent Oan Houtte B'7>7C ) 999999999999999999999999999999 342 -IM o-oc AS ObNect o-oc 6 3(i#Co!ponent REM Set bac1roundI!ae9option in -ocu!entSettin# to "al#e -IM oSettin# AS ObNect oSettin# 6 o-oc&createIn#tanceB"co!&#un&#tar&text&-ocu!entSettin#"C oSettin#&PrintPaeBac1round 6 bB> REM c(oo#e a certain printer -IM !PrinterOpt#B%C AS HEW co!&#un&#tar&bean#&Propert.Oalue !PrinterOpt#B7C&Ha!e 6 "Ha!e" !PrinterOpt#B7C&Oalue 6 "M"CQQQ7-H" !PrinterOpt#B>C&Ha!e 6 "Paper"or!at" !PrinterOpt#B>C&Oalue 6 co!&#un&#tar&:ie*&Paper"or!at&A? !PrinterOpt#B'C&Ha!e 6 "PaperOrientation" !PrinterOpt#B'C&Oalue 6 co!&#un&#tar&:ie*&PaperOrientation&POR3RAI3 o-oc&Printer 6 !PrinterOpt#BC REM #et Papertra. in St.le# -IM oSt.le AS ObNect -IM #PaeSt.le AS Strin #PaeSt.le 6 o-oc&CurrentController&etOie*Cur#orBC&PaeSt.leHa!e o#t.le 6 o-oc&St.le"a!ilie#&etB.Ha!eB"PaeSt.le#"C&etB.Ha!eB#PaeSt.leC oSt.le&PrinterPaper3ra. 6 #3ra.> REM Set printOption# -IM !PrintOpt#B%C AS HEW co!&#un&#tar&bean#&Propert.Oalue !PrintOpt#B7C&Ha!e 6 "Cop.Count" !PrintOpt#B7C&Oalue 6 > !PrintOpt#B>C&Ha!e 6 "Collate" !PrintOpt#B>C&Oalue 6 3rue !PrintOpt#B'C&Ha!e 6 "Pae#" !PrintOpt#B'C&Oalue 6 #PaeHr !PrintOpt#B%C&Ha!e 6 "Wait" !PrintOpt#B%C&Oalue 6 3rue REM Print o-oc&PrintB!PrintOpt#BCC REM RESE3 OP3IOHS REM Re#et bac1roundI!ae9option in -ocu!entSettin# oSettin#&PrintPaeBac1round 6 bB' REM Re#et Papertra. in St.le# oSt.le&PrinterPaper3ra. 6 #3ra.' REM -o a 79print to co!plete t(e re#et -IM !PrintOpt#'B7C AS HEW co!&#un&#tar&bean#&Propert.Oalue !PrintOpt#'B7C&Ha!e 6 "Cop.Count" !PrintOpt#'B7C&Oalue 6 7 o-oc&PrintB!PrintOpt#'BCC End Sub 343 Sub clo#e-ocu!entBo-oc AS ObNectC ) 999999999999999999999999999999 ) 3(i# !acro clo#e# t(e current docu!ent ) ) Written b. Andre* Piton.a1 B'7>7C ) Adapted b. Oincent Oan Houtte B'7>>C ) 999999999999999999999999999999 REM C(ec1 i$ t(e docu!ent exi#t# I$ I#HullBo-ocC 3(en Exit Sub End I$ REM Store t(e docu!ent i$ it *a# !odi$ied I$ Bo-oc&i#Modi$iedC 3(en I$ Bo-oc&(a#,ocation AH- BHot o-oc&i#ReadOnl.CC 3(en o-oc&#toreBC El#e o-oc&#etModi$iedB"al#eC End I$ End I$
REM Clo#e t(e docu!ent o-oc&clo#eBtrueC End Sub Sub ExportA#Pd$AndSendE!ail ) 999999999999999999999999999999 ) 3(i# !acro con:ert# t(e acti:e docu!ent to P-" and t(en add# t(e P-" ) to a ne* e!ail!e##ae& 3(e recipientaddre## and #ubNect are ) enerated auto!aicall. $ro! a text$ield in#ide t(e docu!ent ) ) 3(i# !acro a##u!e# t(e de$ault e!ail application i# #et ) in 3ool# 9D Option# 9D OpenO$$ice&or 9D External Prora!#& ) ) 3(i# !acro u#e# Si!pleCo!!andMail= *(ic( !i(t not *or1 in *indo*# ) 3r. Si!pleS.#te!Mail in#tead ) ) Written b. Oincent Oan Houtte B'7>7C ) 999999999999999999999999999999 -IM o-oc= MailClient= MailAent= MailMe##ae AS ObNect -IM #-oc0R,= #P-"0R,= #3o= #SubNect AS Strin REM Jet location o$ t(e doc o-oc 6 3(i#Co!ponent I$ BHot o-oc&(a#,ocationBCC 3(en o-oc&#toreBC End i$ REM In#ert ti!e#ta!p o$ #endin -i! #Action3ext AS Strin #Action3ext 6 "OERVOH-EH" In#ert-3#ta!pB#Action3extC 344 REM Print t(e pae Print-ocWit(outB3o3ra.>BC REM Replace &odt *it( &pd$ #-oc0R, 6 o-oc&et0R,BC #P-"0R, 6 ,e$tFB#-oc0R,=,enB#-oc0R,C9?C W "&pd$" REM Sa:e a# P-" -IM ar#B7C AS HEW co!&#un&#tar&bean#&Propert.Oalue ar#B7C&Ha!e 6 ""ilterHa!e" ar#B7C&Oalue 6 "*riter5pd$5Export" o-oc&#tore3o0R,B#P-"0R,=ar#BCC REM Re!o:e t(e -ate+ti!e9#ta!p Re!o:e-3#ta!pBC REM Jet t(e :alue# o$ t(e text$ield# in#ide t(e docu!ent to $or! t(e #ubNect line -IM enu3"= a3ext"ield AS ObNect -IM #-o#Ha!e= #-o#Hu!= #-o#0re$ AS Strin enu3" 6 o-oc&3ext"ield#&createEnu!eration -o W(ile enu3"&(a#MoreEle!ent# a3ext"ield 6 enu3"&nextEle!ent i$ a3ext"ield&#upport#Ser:iceB"co!&#un&#tar&text&3ext"ield&Input"C t(en Select Ca#e a3ext"ield&etPropert.OalueB"Hint"C Ca#e "-OS5HAAM": #-o#Ha!e 6 a3ext"ield&etPropert.OalueB"Content"C Ca#e "-OS5H0M": #-o#Hu! 6 a3ext"ield&etPropert.OalueB"Content"C Ca#e "RE"5O": #-o#Hu! 6 a3ext"ield&etPropert.OalueB"Content"C Ca#e "0RE"": #-o#0re$ 6 a3ext"ield&etPropert.OalueB"Content"C Ca#e "EMAI,5A--R": #3o 6 a3ext"ield&etPropert.OalueB"Content"C End Select end i$ ,oop #SubNect 6 #-o#Ha!e W " 9 " W #-o#0re$ W " 9 " W #-o#Hu! REM Send t(e P-" a# an attac(!ent MailAent 6 Create0noSer:iceB"co!&#un&#tar&#.#te!&Si!pleCo!!andMail"C MailClient 6 MailAent&;uer.Si!pleMailClientBC MailMe##ae6MailClient&createSi!pleMailMe##aeBC MailMe##ae&#etRecipientB#3oC MailMe##ae&#etSubNectB#SubNectC MailMe##ae&#etAttac(e!entBarra.B#P-"0R,CC MailClient&#endSi!pleMailMe##aeBMailMe##ae= 7C REM Sa:e and clo#e t(e docu!ent clo#e-ocu!entBo-ocC End Sub 345 13.1#. Creating services An ob/ect t"at supports t"e IMu*tiSerice0actory interface may create serices& An ob/ect is usua**y created by t"e ob/ect t"at %i** o%n it& As an e3amp*e, a te3t tab*e is created by t"e te3t document t"at %i** contain t"e te3t tab*e& Simi*ar*y, t"e DocumentSettin$s ob/ect is created by t"e document of interest& T"e function #reate5noSerice creates serices in t"e scope of t"e 11o app*ication& T"e oSettin$s ob/ect in Listin$ 312 supports t"e serice com&sun&star&te3t&DocumentSettin$s& T"e oSettin$s ob/ect is re*ated to T"is#omponent in t"at it ref*ects t"e settin$s for T"is#omponent L t"e current document L but not for any ot"er document& Listing 312. /reate an ob%ect that supports the #ocument*ettings service. oSettin#63(i#Co!ponent&createIn#tanceB"co!&#un&#tar&text&-ocu!entSettin#"C T"e create)nstance,. met"od returns an ob/ect t"at supports t"e re8uested serice if it can7 if it cannot, it returns 45LL& T"e returned ob/ect may support ot"er serices as %e** ,see Listin$ 301 and 0i$ure B2.& Listing 313. "nspect a te.t document settings ob%ect. Sub Write-ocu!entSettin# -i! oSettin# )Settin# obNect to create -i! #F )0tilit. #trin -i! iG )0itlit. index :ariable -i! : )3(i# *ill contain an arra. o$ #er:ice na!e# REM Create an obNect t(at #upport# t(e -ocu!entSettin# #er:ice oSettin#63(i#Co!ponent&createIn#tanceB"co!&#un&#tar&text&-ocu!entSettin#"C : 6 oSettin#&etSupportedSer:iceHa!e#BC # 6 "**** Speci$ied Supported Ser:ice# ****" 4 CHRFB>7C 4 MoinB:= CHRFB>7CC # 6 # 4 CHRFB>7C 4 CHRFB>7C 4 "**** 3e#ted Ser:ice# ****" 4 CHRFB>7C
REM Ho* c(ec1 to #ee i$ t(i# created obNect #upport# an. ot(er #er:ice#& : 6 Arra.B"co!&#un&#tar&co!p&Writer&-ocu!entSettin#"=5 "co!&#un&#tar&text&PrintSettin#"C
REM I could #et t(i# to 3rue or "al#e )oSettin#&Printcontrol# 6 3rue End Sub 346 Figure 92. *ome 'riter document settings. A carefu* inspection of Listin$ 301 and 0i$ure B2 demonstrate t"at t"e ob/ect supports mu*tip*e serices& T"e met"od $etSupportedSerice4ames,. *ists t"e serices supported by t"e ob/ect& T"e met"od $et)mp*ementation4ame,. returns t"e serice t"at uni8ue*y identifies t"e returned serice ,com&sun&star&comp&;riter&DocumentSettin$s.& T"e uni8ue serice name is not in t"e *ist of supported serice names& A*t"ou$" not s"o%n in Listin$ 301, t"e t%o DTested SericesF in 0i$ure B2 cannot be created usin$ t"e create)nstance,. ob/ect met"od& ) discoered t"e 'rintSettin$s serice entire*y by accident& ) inspected t"e db$=properties property, %"ic" contained 'rint#ontro*s& ) t"en searc"ed Joo$*e for Dsite:api&openoffice&or$ 'rintSettin$sF& T"e important t"in$s to notice are as fo**o%s: 1& T"ere are different met"ods of inspectin$ an ob/ect7 use a** of t"em& 2& T"e documentation is not comp*ete& 6ou must manua**y inspect an ob/ect to see %"at it supports& Eo%eer, undocumented met"ods and properties may be deprecated and remoed *ater L so do t"is carefu**y& 3& 6ou can searc" t"e )nternet for serices and properties& 13.1$. "ocument settings 11o contains numerous document options7 t"ese are aai*ab*e in t"e Tools Options dia*o$& 0or e3amp*e, Te3t Document contains a 'rint tab, %"ic" a**o%s $rap"ics to be printed, or not& T"e typica* met"od for modifyin$ properties in a document ino*es usin$ eit"er D$etF and DsetF met"ods, or direct*y accessin$ ob/ect properties& To access adanced document settin$s, "o%eer, you must use a comp*ete*y different met"od& 0irst t"e document "as to create an ob/ect t"at supports t"e document settin$s& 2ery document type, e3cept for t"e Mat" type, "as t"e abi*ity to create a serice usin$ t"e create)nstance,. met"od& Tab*e 11B contains a *ist of t"e properties common to a** of t"e document settin$ types7 t"ere are more& able ((1. /ommon document properties in com.sun.star.document.*ettings. Property Description 0orbidden#"aracters A**o% access to ot"er%ise forbidden c"aracters& Lin(5pdateMode T"e update mode for *in(s %"en *oadin$ te3t documents& 'rinter4ame 'rinter used by t"e document& 347 Property Description 'rinterSetup '*atform9 and drier9dependent printer setup data& )s<ernAsian'unctuation )s (ernin$ app*ied to Asian punctuation> #"aracter#ompressionType #ompression ,c"aracter spacin$. used for Asian c"aracters& App*y5serData S"ou*d user9specific settin$s saed in a document be *oaded a$ain> SaeOersion1n#*ose )s a ne% ersion created %"en a modified document is c*osed> 5pdate0romTemp*ate S"ou*d a document be updated %"en its creation temp*ate c"an$es> 0ie*dAuto5pdate Are te3t document fie*ds automatica**y updated> #urrentDatabaseDataSource 4ame of t"e data source from %"ic" t"e current data is ta(en& #urrentDatabase#ommand Disp*ayed ob/ectGs name ,or t"e S_L statement used.& #urrentDatabase#ommandType Specifies "o% to interpret t"e DataTab*e4ame property& Defau*tTabStop Defau*t tab %idt"& )s'rint+oo(*et )s t"e document printed as a boo(*et ,broc"ure.> )s'rint+oo(*et0ront )f True, on*y t"e front pa$es of a boo(*et are printed& )s'rint+oo(*et+ac( )f True, on*y t"e bac( pa$es of a boo(*et are printed& 'rint_ua*ity _ua*ity to use %"en printin$& #o*orTab*e5RL 5RL of t"e co*or tab*e ,S1# fi*e. s"o%in$ a pa*ette in dia*o$s t"at use co*ors& 'rinter)ndependentLayout )f true, do not use printer metrics for *ayout& Specific document settin$s serices e3ist for ;riter, #a*c, Dra%, and )mpress documents ,see Tab*e 120.& A*t"ou$" eac" of t"ese serices imp*ements t"e Settin$s serice as s"o%n in Tab*e 11B, a** of t"e properties e3cept for 'rinter4ame and 'rinterSetup are optiona*& able (=C. *pecific document settings service types. Docment Settin+s Service Docment Type com&sun&star&te3t&DocumentSettin$s ;riter com&sun&star&s"eet&DocumentSettin$s #a*c com&sun&star&dra%in$&DocumentSettin$s Dra% com&sun&star&presentation&DocumentSettin$s )mpress As s"o%n in Listin$ 301 and 0i$ure B2, t"e ;riter document settin$s support t"e 'rintSettin$s serice ,see Tab*e 121.& T"e Dra% and )mpress document settin$s serices eac" contain specia* settin$s t"at app*y on*y to t"eir respectie document types& able (=(. 9roperties defined by the com.sun.star.te.t.9rint*ettings service. Property Description 'rintJrap"ics )f True, print $rap"ic ob/ect& 'rintTab*es )f True, print te3t tab*es& 'rintDra%in$s )f True, print s"apes& 'rintLeft'a$es )f True, print *eft pa$es& 348 Property Description 'rintRi$"t'a$es )f True, print ri$"t pa$es& 'rint#ontro*s )f True, print contro* contained in t"e document& 'rintReersed )f True, print t"e pa$es in reerse order, startin$ %it" t"e *ast pa$e& 'rint'aper0romSetup )f True, use t"e paper tray specified for t"e system printer& )f 0a*se, use t"e paper tray specified by t"e pa$e sty*e& 'rint0a34ame 4ame of t"e fa3& 'rintAnnotationMode Specify "o% notes are printed& 5ses com&sun&star&te3t&4ote'rintMode enumerated a*ue& 'ossib*e a*ues inc*ude 41T, 14L6, D1#=24D, or 'AJ2=24D& 'rint'rospect )f True, prospect printin$ is used7 "o%eer, ) cannot find a definition for prospect printin$& 'rint'a$e+ac($round )f True, t"e bac($round co*or and-or bac($round $rap"ic is printed& 'rint+*ac(0onts )f True, c"aracters are a*%ays printed in b*ac(& 13.1&. 0he coolest tric* ! *now Sad*y, t"is on*y %or(s in Libre1ffice, and not in 11o& ;"i*e editin$ a document: 1& 5se +ile > Open to open t"e 1pen dia*o$& 2& 2nter Dnd&sun&star&tdoc:-F for t"e fi*e name and c*ic( 1pen& 3& #urrent*y open documents are s"o%n for se*ection& Se*ect a document7 and c*ic( open& 6ou are *oo(in$ at t"e documentVs interna* structures& 6ou can een open an ima$e embedded in a document& A document containin$ pictures is a $ood e3amp*e to try& 13.1(. Converting to a )%. in other languages +asic proides t"e met"ods #onertTo5RL and #onert0rom5RL, ot"er *an$ua$es do not& Some 5R) sc"emes *eae unspecified important aspects of "o% to interpret 5R)s of t"ose sc"emes& 0or e3amp*e, it is unspecified for Dfi*eF 5RLs "o% to map t"e byte se8uences t"at constitute t"e pat" se$ments of a Dfi*eF 5RL to fi*enames on a $ien p*atform: T"e 541 enironment a*%ays assumes t"at pat" se$ments of Dfi*eF 5RLs represent 5T09@Hencoded strin$s ,%"ic" "ae to be mapped to fi*enames in a p*atform9specific %ay., %"i*e ot"er app*ications typica**y assume t"at pat" se$ments of Dfi*eF 5RLs direct*y represent a p*atformVs byte9 se8uence fi*enames& T"e 23terna*5riReferenceTrans*ator offers met"ods to trans*ate bet%een suc" interna* 5R)s ,e&$&, 5T09@Hencoded Dfi*eF 5RLs used %it"in t"e 541 enironment. and e3terna* 5R)s ,e&$&, byte9 se8uenceHoriented Dfi*eF 5RLs used by ot"er app*ications.& Typica**y, on*y Dfi*eF 5RLs are affected by t"is trans*ation& x 6 Create0noSer:iceB"co!&#un&#tar&uri&External0riRe$erence3ran#lator"C Print x&tran#late3oExternalB"$ile:+++c:+M.-oc&oot"C Print x&tran#late3oInternalB"$ile:+c:+M.-oc&oot"C 13.2+. Conclusion T"e interfaces and serices introduced in t"is c"apter proide a $ood introduction to t"e capabi*ities of 11o t"at are not direct*y re*ated to a specific document type& 11o contains numerous ot"er capabi*ities t"at ) cou*d "ae inc*uded in t"is c"apter, but it isnGt possib*e to e3"austie*y coer eery sub/ect& 5se t"ese topics and met"ods as a startin$ point to inesti$ate t"e ot"er capabi*ities of 1pen1ffice&or$& 349 1$. 8riter (ocuments ;riter documents primari*y dea* %it" te3t content arran$ed in para$rap"s& T"is c"apter introduces appropriate met"ods to manipu*ate, traerse, searc", format, and modify t"e content contained in an 1pen1ffice&or$ ;riter document& 0irst, a bit of reie% t"at is app*icab*e to most document types& #onceptua**y, a** document types "ae t%o components: t"e data t"ey contain and t"e contro**er t"at determines "o% t"e data is disp*ayed& ;riter documents primari*y contain simp*e formatted te3t& )n addition to simp*e te3t, ;riter documents may contain ot"er content suc" as tab*es, frames, $rap"ics, te3t fie*ds, boo(mar(s, footnotes, endnotes, te3t sections, inde3 entries, trac(ed document c"an$es ,ca**ed red*inin$., ob/ects for sty*in$, and ob/ects for numberin$& 11o uses t"e same met"ods and interfaces to interact %it" most of t"ese capabi*ities& #onse8uent*y, *earnin$ to manipu*ate a fe% types of content %i** $ie you a so*id basis for dea*in$ %it" a** of t"em& TIP )n 11o, t"e data contained in a document is ca**ed t"e Dmode*&F T"e base mode* interface is com&sun&star&frame&IMode*& )n 1pen1ffice&or$, t"e data contained in a document is ca**ed t"e mode*& 2ac" mode* "as a contro**er t"at is responsib*e for t"e isua* presentation of t"e data& T"e contro**er (no%s t"e *ocation of t"e isib*e te3t cursor, t"e current pa$e, and %"at is current*y se*ected& TIP ;"i*e tryin$ to determine %"ic" portion of t"e 11o A') to use to so*e a specific prob*em, first as( if t"e prob*em is disp*ay9centric or data9centric& 0or e3amp*e, a para$rap" boundary is specified in t"e data, but a ne% *ine is usua**y determined by t"e contro**er %"en t"e data is formatted& 2ery te3t document supports t"e com&sun&star&te3t&Te3tDocument serice& ;"en ) %rite a macro t"at must be user friend*y and re8uires a te3t document, ) erify t"at t"e document is t"e correct type by usin$ t"e ob/ect met"od supportsSerice ,see Listin$ 31!.& Listing 314. e.t documents support the com.sun.star.te.t.e.t#ocument service. REM I$ it reall. !atter#= .ou #(ould c(ec1 t(e docu!ent t.pe REM to a:oid a run9ti!e error& I$ HO3 3(i#Co!ponent&#upport#Ser:iceB"co!&#un&#tar&text&3ext-ocu!ent"C 3(en M#Box "3(e current docu!ent i# not a Writer text docu!ent"= ?Q= "Error" Exit Sub End I$ An interface defines a series of met"ods& )f an ob/ect imp*ements an interface, it a*so imp*ements eery met"od defined by t"at interface& A serice defines an ob/ect by specifyin$ t"e interfaces t"at it imp*ements, t"e properties t"at it contains, and t"e ot"er serices t"at it e3ports& A serice indirect*y specifies t"e imp*emented met"ods by specifyin$ interfaces& T"e interfaces supported by t"e Te3tDocument serice proide a $ood oerie% of t"e proided functiona*ity ,see Tab*e 122.& 350 Table 122. "nterfaces supported by te.t documents. Service Description com&sun&star&te3t&ITe3tDocument Main te3t document interface& com&sun&star&te3t&I+oo(mar(sSupp*ier Access t"e boo(mar(s& com&sun&star&te3t&I#"apter4umberin$Supp*ier 4umberin$ ru*es for c"apters& com&sun&star&te3t&IDocument)nde3esSupp*ier Access t"e co**ection of inde3es& com&sun&star&te3t&ITe3t2mbedded1b/ectsSupp*ier Access embedded ob/ects& com&sun&star&te3t&I2ndnotesSupp*ier Access endnote content& com&sun&star&te3t&I0ootnotesSupp*ier Access footnote content& com&sun&star&te3t&ILine4umberin$Supp*ier 4umberin$ ru*es for *ine numbers& com&sun&star&te3t&I'a$e'rintab*e 'rint mu*tip*e pa$es on one pa$e& com&sun&star&te3t&IReferenceMar(sSupp*ier Access t"e document reference mar(s, %"ic" are used to refer to te3t positions in a te3t document& com&sun&star&te3t&ITe3t0ie*dsSupp*ier Access contained fie*ds& com&sun&star&te3t&ITe3t0ramesSupp*ier Access contained te3t frames& com&sun&star&te3t&ITe3tJrap"ic1b/ectsSupp*ier Access embedded and *in(ed $rap"ics& com&sun&star&te3t&ITe3tSectionsSupp*ier Access contained te3t sections& com&sun&star&te3t&ITe3tTab*esSupp*ier Access contained tab*es& com&sun&star&sty*e&ISty*e0ami*iesSupp*ier Access contained sty*es by type& com&sun&star&uti*&I4umber0ormatsSupp*ier Access contained number formats& com&sun&star&uti*&IRefres"ab*e Refres" data t"at can be refres"ed from a database& com&sun&star&uti*&IRep*aceab*e Rep*ace te3t found %it" a searc" descriptor& com&sun&star&uti*&ISearc"ab*e Searc" a te3t ran$e for a specific strin$ pattern& com&sun&star&beans&I'ropertySet Access document properties by name& 14.1. Basic building bloc*s ;"i*e dea*in$ %it" ;riter documents, youG** see t"at a fe% simp*e interfaces and concepts recur& T"ese basic bui*din$ b*oc(s are interre*ated in t"at t"eir respectie interfaces are circu*ar*y defined ,t"ey refer to eac" ot"er.& 0ortunate*y, t"e concepts are intuitie and t"erefore easy to $rasp, een %it" a brief introduction& T"is section brief*y introduces t"ese basic bui*din$ b*oc(s, *ayin$ t"e $round%or( for detai*ed coera$e *ater& 1$.1.1. <rimar" text contentA the BText interface Te3t content is contained in an ob/ect t"at imp*ements t"e ITe3t interface& T"e primary purpose of a te3t ob/ect is to contain te3t content, create te3t cursors to moe t"rou$" te3t, insert te3t, and remoe te3t ,see Ta'le )./.& 351 Table 123. Methods defined by the com.sun.te.t.:e.t interface. )et6od Description createTe3t#ursor,. Return a Te3t#ursor serice used to traerse t"e te3t ob/ect& createTe3t#ursor+yRan$e,ITe3tRan$e. Return a Te3t#ursor t"at is *ocated at t"e specified Te3tRan$e& insertStrin$,ITe3tRan$e, Strin$, boo*ean. )nsert a strin$ of c"aracters into t"e te3t at t"e specified te3t ran$e& 2ac" #R ,AS#)) 13. inserts a ne% para$rap" and eac" L0 ,AS#)) 10. inserts a ne% *ine& )f t"e +oo*ean a*ue is True, t"e te3t in t"e ran$e is oer%ritten7 ot"er%ise, t"e te3t c"aracters are inserted after t"e te3t ran$e& insert#ontro*#"aracter,ITe3tRan$e, S"ort, boo*ean. )nsert a contro* c"aracter ,suc" as a para$rap" brea( or a "ard space. into t"e te3t& T"e s"ort inte$er is a a*ue from t"e constant $roup com&sun&star&te3t&#ontro*#"aracter: 'ARAJRA'E=+R2A< ? 0 H Start a ne% para$rap"& L)42=+R2A< ? 1 H Start a ne% *ine in a para$rap"& EARD=E6'E24 ? 2 H )nsert a das" t"at %i** not "yp"enate& S10T=E6'E24 ? 3 H Define a preferred "yp"enation point if t"e %ord must be sp*it at t"e end of a *ine& EARD=S'A#2 ? ! H )nsert a space t"at preents t%o %ords from sp*ittin$ at a *ine brea(& A''24D='ARAJRA'E ? A H Append a ne% para$rap"& )f t"e +oo*ean a*ue is True, t"e te3t in t"e te3t ran$e is oer%ritten7 ot"er%ise, t"e contro* c"aracter is inserted after t"e te3t ran$e& insertTe3t#ontent,ITe3tRan$e, ITe3t#ontent, boo*ean. )nsert te3t content suc" as a te3t tab*e, te3t frame, or te3t fie*d& )n $enera*, t"e te3t content s"ou*d be created by t"e te3t ob/ect& )f t"e +oo*ean a*ue is True, t"e te3t in t"e te3t ran$e is oer%ritten7 ot"er%ise, t"e te3t content is inserted after t"e te3t ran$e& remoeTe3t#ontent,ITe3t#ontent. Remoe t"e specified te3t content from t"e te3t ob/ect& +ecause t"e ITe3t interface is deried from t"e ITe3tRan$e interface, a** ob/ects t"at imp*ement t"e ITe3t interface a*so support t"e ob/ect met"ods defined by t"e ITe3tRan$e interface ,see Tab*e 12!.& 1$.1.2. Text rangesA the BText6ange interface A te3t ran$e is one of t"e most important concepts in a te3t document because so many interfaces derie from t"e ITe3tRan$e interface& T"e primary purpose of a te3t ran$e is to define a start and end position in t"e te3t ,see Tab*e 12!.& )t is possib*e t"at t"e start position and t"e end position in a te3t ran$e are t"e same& ;"en t"e start and end positions are t"e same, t"e te3t ran$e identifies a position in t"e te3tLfor e3amp*e, t"e cursor in a te3t document %"en no te3t is se*ected& )f t"e start and end positions of a te3t ran$e are not t"e same, t"ey represent a section of te3t& 352 Table 124. Methods defined by the com.sun.te.t.:e.tRange interface. )et6od Description $etTe3t,. Return t"e ITe3t interface t"at contains t"e te3t ran$e& $etStart,. A te3t ran$e "as a start and end position& T"e $etStart,. met"od returns a te3t ran$e t"at contains on*y t"e start position of t"is te3t ran$e& $et2nd,. A te3t ran$e "as a start and end position& T"e $etStart,. met"od returns a te3t ran$e t"at contains on*y t"e end position of t"is te3t ran$e& setStrin$,Strin$. A te3t ran$e "as a start and end position& T"e setStrin$,. met"od rep*aces a** of t"e te3t bet%een t"e start and end positions %it" t"e ar$ument strin$& A** sty*es are remoed and a** te3t in t"is te3t ran$e is rep*aced& $etStrin$,. Return a strin$ t"at represents t"e te3t in t"is te3t ran$e& Strin$s in 11o +asic are *imited to 6!<+ in siCe, but te3t ran$es and te3t ob/ects are not7 use t"is %it" care& 2ery ITe3tRan$e ob/ect is associated %it" a te3t ob/ect& )t can be said t"at an ITe3tRan$e ob/ect is contained in an ob/ect t"at imp*ements t"e ITe3t interface& T"e ITe3t interface is itse*f deried from t"e ITe3tRan$e interface& 5se t"e $etTe3t,. ob/ect met"od to obtain t"e te3t ob/ect t"at is associated %it" t"e te3t ran$e& TIP #ommon tas(s inc*ude obtainin$ a boo(mar(, obtainin$ t"e boo(mar(Gs anc"or position ,a te3t ran$e., and t"en insertin$ te3t content at t"e boo(mar(Gs anc"or position& A*t"ou$" t"e setStrin$,. met"od is t"e 8uic(est %ay to add te3t at t"e anc"or position, insertin$ te3t content re8uires an ob/ect t"at supports t"e ITe3t interface& T"e $etTe3t,. met"od returns an ob/ect t"at can insert te3t content usin$ t"e te3t ran$e& ;riter documents primari*y contain formatted te3t& To access t"e formatted te3t, eit"er ca** t"e documentGs ob/ect met"od $etTe3t,. or direct*y access t"e documentGs Te3t property& ) usua**y direct*y access t"e Te3t property because it re8uires *ess typin$& 3(i#Co!ponent&3ext )Current docu!ent)# text obNect 3(i#Co!ponent&et3extBC )Current docu!ent)# text obNect T"e documentGs te3t ob/ect imp*ements t"e ITe3tRan$e interface& T"e simp*est met"od to obtain a** of t"e te3t c"aracters contained in a te3t document is to ca** t"e $etStrin$,. ob/ect met"od ,see Tab*e 12!.& T"e $etStrin$,. met"od returns a sin$*e strin$ containin$ a te3t ersion of t"e document& 2ac" ce** in a te3t tab*e is returned as a sin$*e para$rap", and a** formattin$ is *ost& T"e ob/ect met"od setStrin$,. can be used to set t"e entire documentGs te3t in one ca**L%"en setStrin$,. is used, a** of t"e e3istin$ te3t is *ostT See Listin$ 31A. Listing 315. <et and set the entire document te.t with no formatting. M#Box 3(i#Co!ponent&3ext&etStrinBC= 7= "-ocu!ent 3ext Strin" 3(i#Co!ponent&3ext&#etStrinB"3(i# i# text to #et"C TIP 5se $etStrin$,. on*y on sma** te3t documents& ) %rote a macro t"at computed %ord9usa$e statistics by first ca**in$ t"e $etStrin$,. ob/ect met"od& +ecause 11o +asic strin$s are *imited to 6!<+ c"aracters, t"e macro fai*ed on *ar$e documents& T"e $etStrin$,. and setStrin$,. ob/ect met"ods are *imited, because 11o +asic strin$s are *imited to 6!<+ in siCe and t"ey contain no formattin$ information& Due to t"ese *imitations, ot"er met"ods are usua**y used to $et and set t"e document te3t& Jenera**y, *ar$e or comp*e3 documents are best "and*ed %it" t"e $etTe3t,. 353 met"od and re*ated met"ods, because t"ey support arbitrary siCe and modu*ar mana$ement of comp*e3 documents& 1$.1.#. Inserting simple text ;it" t"e *imited information a*ready presented, you can a*ready insert simp*e te3t content at t"e be$innin$ and t"e end of a document& T"e $etStart,. and $et2nd,. ob/ect met"ods bot" return a te3t ran$e t"at can be used to insert te3t into a te3t ob/ect ,see Tab*e 123 and Tab*e 12!.& T"e code in Listin$ 316 inserts simp*e te3t at t"e start of t"e document and a ne% para$rap" at t"e end of t"e document& Listing 316. "nsert simple te.t at the start and end of the document. Sub In#ertSi!ple3ext -i! o3ext A# ObNect o3ext 6 3(i#Co!ponent&3ext
REM In#ert #o!e #i!ple text at t(e #tart o3ext&in#ertStrinBo3ext&etStartBC= "3ext obNect #tart&" 4 CHRFB>%C= "al#eC REM Append a ne* pararap( at t(e end o3ext&In#ertControlC(aracterBo3ext&etEndBC=5 co!&#un&#tar&text&ControlC(aracter&APPEH-5PARAJRAPH= "al#eC End Sub 1$.1.$. Text contentA the TextContent ser'ice T"e primary purpose of t"e Te3t#ontent serice is to anc"or an ob/ect ,te3t content. to its surroundin$ te3t& #onceptua**y t"ere are t%o types of te3t content: content t"at is part of t"e surroundin$ te3t ,a te3t fie*d, for e3amp*e., and content t"at is more *i(e a f*oatin$ fie*d ,a $rap"ic ima$e, for e3amp*e.& To determine %"ere te3t content is anc"ored in t"e te3t, ca** t"e $etAnc"or,. ob/ect met"od& T"is returns a te3t ran$e t"at defines t"e anc"or *ocation& 0or f*oatin$ te3t content ob/ects, t"e te3t needs to (no% "o% to f*o% around t"e ob/ect and "o% t"e ob/ect is anc"ored to t"e te3t ,see Tab*e 12A.& T"e be"aior of te3t content inserted as a c"aracter s"ou*d be %e** understood& T"e content acts /ust *i(e a c"aracter %ou*d act: T"e te3t content is moed a*on$ bet%een t%o ot"er c"aracters& ;"en te3t content is anc"ored at a para$rap", "o%eer, t"e te3t content is not re8uired to moe as t"e c"aracters before and after it are moed& )t is on*y re8uired t"at t"e ob/ect stay attac"ed to a para$rap", and t"e ob/ect is not inserted into a para$rap"& ) usua**y anc"or an ob/ect to a para$rap" %"en ) %ant te3t to f*o% around t"e ob/ect7 for e3amp*e, a $rap"ic on t"e ri$"t and te3t on t"e *eft& 354 Table 125. 9roperties supported by the com.sun.star.te.t.e.t/ontent service. Property Description Anc"orType 2numeration of type com&sun&star&te3t&Te3t#ontentAnc"orType t"at defines "o% t"is te3t content is attac"ed to t"e surroundin$ te3t& AT='ARAJRA'E H T"e anc"or is set at t"e top *eft position of t"e para$rap"& T"e ob/ect moes if t"e para$rap" moes& AS=#EARA#T2R H T"e te3t content ob/ect is anc"ored as a c"aracter& T"e siCe of t"e ob/ect inf*uences t"e "ei$"t of t"e te3t *ine and t"e ob/ect can moe as a c"aracter if t"e surroundin$ te3t moes& AT='AJ2 H T"e te3t content ob/ect is anc"ored to t"e pa$e& T"e ob/ect does not moe een if t"e te3t content around it c"an$es& AT=0RAM2 H T"e te3t content ob/ect is anc"ored to a te3t frame& AT=#EARA#T2R H T"e te3t content ob/ect is anc"ored to a c"aracter& T"e ob/ect moes if t"e c"aracter moes& Anc"orTypes Array of Te3t#ontentAnc"orType t"at contains t"e anc"or types of t"e te3t content& Te3t;rap 2numeration of type com&sun&star&te3t&;rapTe3tMode t"at defines "o% t"e surroundin$ te3t %raps around t"is te3t content ob/ect& 4142 H Te3t does not f*o% around t"e ob/ect& TER15JET H Te3t f*o% i$nores t"e ob/ect& ,6es, it is TER15JET&. T"is can be t"ou$"t of as TER15JE iT, as in, Dt"e te3t f*o%s t"rou$" t"e ob/ect&F 'ARALL2L H Te3t f*o%s to t"e *eft and ri$"t of t"e ob/ect& D64AM)# H T"e te3t formattin$ decides t"e best %rappin$ met"od& L20T H Te3t f*o%s to t"e *eft of t"e ob/ect& R)JET H Te3t f*o%s to t"e ri$"t of t"e ob/ect& T"e te3t ob/ect contains met"ods to insert Te3t#ontent ob/ects at specified *ocations ,see Tab*e 123.& )n $enera*, t"e Te3t#ontent type must be created by t"e document before it is inserted ,see Listin$ 31M.& Listing 317. "nsert te.t content 6a te.t table7 at the end of the current document. Sub In#ertSi!ple3ableAtEnd -i! o3able )He*l. created table to in#ert REM ,et t(e docu!ent create t(e text table& o3able 6 3(i#Co!ponent&createIn#tanceB "co!&#un&#tar&text&3ext3able" C o3able&initiali8eB%= 'C )3(ree ro*#= t*o colu!n#
REM Ho* in#ert t(e text table at t(e end o$ t(e docu!ent& 3(i#Co!ponent&3ext&in#ert3extContentB5 3(i#Co!ponent&3ext&etEndBC= o3able= "al#eC End Sub TIP )n $enera*, t"e Te3t#ontent type must be created by t"e document before it is inserted& #a** t"e remoeTe3t#ontent,ITe3t#ontent. ob/ect met"od ,see Tab*e 123. to remoe te3t content& Anot"er met"od of remoin$ te3t content is to %rite ne% te3t content in its p*ace& A simp*e e3amp*e of t"is is to ca** t"e setStrin$,. met"od on a te3t ran$e t"at inc*udes t"e te3t content ,see Listin$ 31@.& 355 Listing 318. /lear the entire document of all te.t content. 3(i#Co!ponent&3ext&#etStrinB""C )Clear an entire docu!entK 14.2. Enumerating paragraphs ;riter documents primari*y contain formatted te3t t"at is arran$ed into para$rap"s& ;riter met"ods can operate on %ords, sentences, para$rap"s, and entire te3t ob/ects& 'ara$rap"s are t"e most basic or$aniCationa* unit for formatted te3t, and met"ods on para$rap"s are often t"e most re*iab*e, meanin$ t"ey contain fe%er bu$s& T"e para$rap"s can be enumerated se8uentia**y usin$ t"e I2numerationAccess interface defined in t"e documentGs te3t ob/ect& 11o treats tab*es as a specia* type of para$rap", and t"ey are returned %"i*e enumeratin$ para$rap"s ,see Listin$ 31B.& Listing 319. /ount paragraphs and te.t tables. Sub enu!eratePararap(# -i! oEnu! )co!&#un&#tar&container&/Enu!erationAcce## -i! oPar )Pararap( o$ #o!e #ort -i! nPar# A# Inteer )Hu!ber o$ pararap(# -i! n3able# A# Inteer )Hu!ber o$ table#
REM 3(i#Co!ponent re$er# to t(e current OOo docu!ent REM 3ext i# a propert. o$ 3(i#Co!ponent $or a text docu!ent REM 3(e et3extBC obNect !et(od return# t(e #a!e t(in& REM createEnu!erationBC i# an obNect !et(od& oEnu! 6 3(i#Co!ponent&3ext&createEnu!erationBC -o W(ile oEnu!&(a#MoreEle!ent#BC oPar 6 oEnu!&nextEle!entBC
REM 3(e returned pararap( *ill be a pararap( or a text table I$ oPar&#upport#Ser:iceB"co!&#un&#tar&text&Pararap("C 3(en nPar# 6 nPar# W > El#eI$ oPar&#upport#Ser:iceB"co!&#un&#tar&text&3ext3able"C 3(en n3able# 6 n3able# W > End I$ ,oop M#Box CStrBnPar#C 4 " Pararap(B#C" 4 CHRFB>%C 45 CStrBn3able#C 4 " 3ableB#C" 4 CHRFB>%C= 7=5 "Pararap( 3.pe# In -ocu!ent" End Sub TIP Oisua* +asic for App*ications ,O+A. supports accessin$ para$rap"s usin$ an inde37 11o does not& ;"i*e enumeratin$ t"e para$rap"s in a ;riter document, bot" para$rap"s and tab*es are returned& T"e ob/ect met"od supportsSerice,. is used to determine if a para$rap" or a tab*e is returned& 'ara$rap" ob/ects support bot" t"e ITe3tRan$e interface and t"e ITe3t#ontent interface& Te3tTab*e ob/ects, "o%eer, support on*y t"e ITe3t#ontent interface& T"e macro in Listin$ 31B enumerates para$rap"s in t"e "i$" *ee* te3t ob/ect& Many ob/ects contains t"eir o%n te3t ob/ect7 fore e3amp*e, eac" ce** in a te3t tab*e and eac" frame& 356 1$.2.1. <aragraph properties 'ara$rap"s contain numerous para$rap"9re*ated properties encapsu*ated in serices& T"e properties t"at are primari*y re*ated to t"e entire para$rap" are encapsu*ated in t"e 'ara$rap"'roperties serice ,see Tab*e 126.& TIP T"e 'ara$rap" serice is not t"e on*y serice t"at supports t"e 'ara$rap"'roperties serice& 1t"er serices, especia**y t"ose t"at are a*so a te3t ran$e, a*so support para$rap" properties& Tec"ni8ues used to modify para$rap" properties in para$rap"s app*y to t"ese serices as %e**& Table 126. 9roperties supported by the com.sun.style.9aragraph9roperties service. Property Description 'araAd/ust Specify "o% t"e para$rap" is a*i$ned ,or /ustified.& 0ie a*ues are supported from t"e com&sun&star&sty*e&'ara$rap"Ad/ust enumeration: L20T H Left9a*i$n t"e para$rap"& R)JET H Ri$"t9a*i$n t"e para$rap"& #24T2R H #enter9a*i$n t"e para$rap"& +L1#< H 0i**9/ustify eery *ine e3cept for t"e *ast *ine& STR2T#E H 0i**9/ustify eery *ine inc*udin$ t"e *ast *ine& 'araLastLineAd/ust Ad/ust t"e *ast *ine if t"e 'araAd/ust is set to +L1#<& 'araLineSpacin$ Specify t"e para$rap" *ine spacin$& T"e property is a structure of type com&sun&star&sty*e&LineSpacin$, %"ic" contains t%o properties of type S"ort& T"e Eei$"t property specifies t"e "ei$"t and t"e Mode property specifies "o% to use t"e Eei$"t property& T"e Mode property supports a*ues defined in t"e com&sun&star&sty*e&LineSpacin$Mode constants $roup& 'R1' ? 0 H T"e "ei$"t is proportiona*& M)4)M5M ? 1 H T"e "ei$"t is t"e minimum *ine "ei$"t& L2AD)4J ? 2 H T"e "ei$"t is t"e distance to t"e preious *ine& 0)I ? 3 H T"e "ei$"t is fi3ed& 'ara+ac(#o*or Specify t"e para$rap" bac($round co*or as a Lon$ )nte$er& 'ara+ac(Transparent )f True, set t"e para$rap" bac($round co*or to transparent& 'ara+ac(Jrap"ic5RL Specify t"e 5RL of t"e para$rap" bac($round $rap"ic& 'ara+ac(Jrap"ic0i*ter Specify t"e name of t"e $rap"ic fi*ter for t"e para$rap" bac($round $rap"ic& 'ara+ac(Jrap"icLocation Specify t"e position of t"e bac($round $rap"ic usin$ t"e enumeration sun&star&sty*e&Jrap"icLocation: 4142 H A *ocation is not yet assi$ned& L20T=T1' H T"e $rap"ic is in t"e top *eft corner& M)DDL2=T1' H T"e $rap"ic is in t"e midd*e of t"e top ed$e& R)JET=T1' H T"e $rap"ic is in t"e top ri$"t corner& L20T=M)DDL2 H T"e $rap"ic is in t"e midd*e of t"e *eft ed$e& M)DDL2=M)DDL2 H T"e $rap"ic is in t"e center of t"e surroundin$ ob/ect& R)JET=M)DDL2 H T"e $rap"ic is in t"e midd*e of t"e ri$"t ed$e& L20T=+1TT1M H T"e $rap"ic is in t"e bottom *eft corner& M)DDL2=+1TT1M H T"e $rap"ic is in t"e midd*e of t"e bottom ed$e& R)JET=+1TT1M H T"e $rap"ic is in t"e bottom ri$"t corner& 357 Property Description AR2A H T"e $rap"ic is sca*ed to fi** t"e %"o*e surroundin$ area& T)L2D H T"e $rap"ic is repeated oer t"e surroundin$ ob/ect *i(e ti*es& 'ara23pandSin$*e;ord )f True, sin$*e %ords may be stretc"ed& 'araLeftMar$in Specify t"e *eft para$rap" mar$in in 0&01 mm as a Lon$ )nte$er& 'araRi$"tMar$in Specify t"e ri$"t para$rap" mar$in in 0&01 mm as a Lon$ )nte$er& 'araTopMar$in Specify t"e top para$rap" mar$in in 0&01 mm as a Lon$ )nte$er& T"e distance bet%een t%o para$rap"s is t"e ma3imum of t"e bottom mar$in of t"e preious para$rap" and t"e top mar$in of t"e ne3t para$rap"& 'ara+ottomMar$in Specify t"e bottom para$rap" mar$in in 0&01 mm as a Lon$ )nte$er& T"e distance bet%een t%o para$rap"s is t"e ma3imum of t"e bottom mar$in of t"e preious para$rap" and t"e top mar$in of t"e ne3t para$rap"& 'araLine4umber#ount )f True, t"is para$rap" is inc*uded in *ine numberin$& 'araLine4umberStartOa*ue Specify t"e start a*ue for *ine numberin$ as a Lon$ )nte$er& 'a$eDesc4ame Settin$ t"is strin$ causes a pa$e brea( to occur before t"e para$rap"& T"e ne% pa$e uses t"e specified pa$e sty*e name& 'a$e4umber1ffset Specify a ne% pa$e number if a pa$e brea( occurs& 'araRe$isterModeActie )f True, and if t"e para$rap"Vs pa$e sty*e a*so "as t"e re$ister mode set to True, t"e re$ister mode is actie for t"is para$rap"& )f re$ister mode is actie, eac" *ine "as t"e same "ei$"t& 'araTabStops Specify t"e tab stops for t"is para$rap"& T"is is an array of structures of type com&sun&star&sty*e&TabStop& 2ac" structure contains t"e fo**o%in$ properties: 'osition H Lon$ inte$er position re*atie to t"e *eft border& A*i$nment H A*i$nment of t"e te3t ran$e before t"e tab& T"is is an enumeration of type com&sun&star&sty*e&TabA*i$n& Oa*id a*ues inc*ude L20T, R)JET, #24T2R, D2#)MAL, and D20A5LT& Decima*#"ar H Specifies %"ic" c"aracter is t"e decima*& 0i**#"ar H #"aracter used to fi** space bet%een t"e te3t& 'araSty*e4ame Specify t"e name of t"e current para$rap" sty*e& Drop#ap0ormat Structure t"at determines if t"e first c"aracters of t"e para$rap" use dropped capita* *etters& T"e com&sun&star&sty*e&Drop#ap0ormat contains t"e fo**o%in$ properties: Lines H 4umber of *ines used for a drop cap& #ount H 4umber of c"aracters in t"e drop cap& Distance H Distance bet%een t"e drop cap and t"e fo**o%in$ te3t& Drop#ap;"o*e;ord )f True, t"e Drop#ap0ormat is app*ied to t"e entire first %ord& 'ara<eepTo$et"er )f True, preents a pa$e or co*umn brea( after t"is para$rap"Lfor e3amp*e, to preent a tit*e from bein$ t"e *ast *ine on a pa$e or co*umn& 'araSp*it )f 0a*se, preents t"e para$rap" from sp*ittin$ into t%o pa$es or co*umns& 4umberin$Lee* Specify t"e numberin$ *ee* of t"e para$rap"& 4umberin$Ru*es Specify t"e numberin$ ru*es app*ied to t"is para$rap"& T"is ob/ect imp*ements t"e com&sun&star&container&I)nde3Rep*ace interface& 4umberin$StartOa*ue Specify t"e start a*ue for numberin$ if 'ara)s4umberin$Restart is True& 'ara)s4umberin$Restart Specify if numberin$ restarts at t"e current para$rap" ,see 4umberin$StartOa*ue.& 4umberin$Sty*e4ame Specify t"e name of t"e sty*e for numberin$ ,see 'araLine4umber#ount.& 358 Property Description 'ara1rp"ans Specify t"e minimum number of *ines at t"e bottom of a pa$e if t"e para$rap" spans more t"an one pa$e& 'ara;ido%s Specify t"e minimum number of *ines at t"e top of a pa$e if t"e para$rap" spans more t"an one pa$e& 'araS"ado%0ormat Specify t"e para$rap" s"ado% format as a com&sun&star&tab*e&S"ado%0ormat: Location H Specify t"e s"ado% *ocation as an enumeration of type com&sun&star&tab*e&S"ado%Location& Oa*id a*ues inc*ude 4142, T1'=L20T, T1'=R)JET, +1TT1M=L20T, and +1TT1M=R)JET& S"ado%;idt" H Specify t"e siCe of t"e s"ado% as an )nte$er& )sTransparent H )f True, t"e s"ado% is transparent& #o*or H Specify t"e co*or of t"e s"ado% as a Lon$ )nte$er& Left+order Specify t"e *eft border as a com&sun&star&tab*e&+orderLine: #o*or H Specify t"e co*or of t"e *ine& )nnerLine;idt" H Specify t"e inner %idt" of a doub*e *ine ,in 0&01 mm.& )f Cero, a sin$*e *ine is dra%n& 1uterLine;idt" H Specify t"e %idt" of a sin$*e *ine or t"e outer %idt" of a doub*e *ine ,in 0&01 mm.& )f Cero, no *ine is dra%n& LineDistance H Specify t"e distance bet%een t"e inner and outer parts of a doub*e *ine ,in 0&01 mm.& Ri$"t+order Specify t"e ri$"t border ,see Left +order.& Top+order Specify t"e top border ,see Left +order.& +ottom+order Specify t"e bottom border ,see Left +order.& +orderDistance Specify t"e distance from t"e border to t"e ob/ect ,in 0&01 mm.& Left+orderDistance Specify t"e distance from t"e *eft border to t"e ob/ect ,in 0&01 mm.& Ri$"t+orderDistance Specify t"e distance from t"e ri$"t border to t"e ob/ect ,in 0&01 mm.& Top+orderDistance Specify t"e distance from t"e top border to t"e ob/ect ,in 0&01 mm.& +ottom+orderDistance Specify t"e distance from t"e bottom border to t"e ob/ect ,in 0&01 mm.& +rea(Type Specify t"e type of brea( t"at is app*ied at t"e start of t"e para$rap"& T"is is an enumeration of type com&sun&star&sty*e&+rea(Type %it" t"e fo**o%in$ a*ues: 4142 H 4o co*umn or pa$e brea( is app*ied& #1L5M4=+201R2 H A co*umn brea( is app*ied before t"e current para$rap"& T"e current para$rap", t"erefore, is t"e first in t"e co*umn& #1L5M4=A0T2R H A co*umn brea( is app*ied after t"e current para$rap"& T"e current para$rap", t"erefore, is t"e *ast in t"e co*umn& #1L5M4=+1TE H A co*umn brea( is app*ied before and after t"e current para$rap"& T"e current para$rap", t"erefore, is t"e on*y para$rap" in t"e co*umn& 'AJ2=+201R2 H A pa$e brea( is app*ied before t"e current para$rap"& T"e current para$rap", t"erefore, is t"e first on t"e pa$e& 'AJ2=A0T2R H A pa$e brea( is app*ied after t"e current para$rap"& T"e current para$rap", t"erefore, is t"e *ast on t"e pa$e& 'AJ2=+1TE H A pa$e brea( is app*ied before and after t"e current para$rap"& T"e current para$rap", t"erefore, is t"e on*y para$rap" on t"e pa$e& Drop#ap#"arSty*e4ame Specify t"e name of t"e c"aracter sty*e for drop caps& 'ara0irstLine)ndent Specify t"e indent for t"e first *ine in a para$rap"& 359 Property Description 'ara)sAuto0irstLine)ndent )f True, t"e first *ine is indented automatica**y& 'ara)sEyp"enation )f True, automatic "yp"enation is app*ied& 'araEyp"enationMa3Eyp"ens Specify t"e ma3imum number of consecutie "yp"ens for eac" %ord contained in t"e current para$rap"& 'araEyp"enationMa3Leadin$#"a rs Specify t"e ma3imum number of c"aracters to remain before a "yp"en c"aracter& 'araEyp"enationMa3Trai*in$#"a rs Specify t"e ma3imum number of c"aracters to remain after a "yp"en c"aracter& 'araOertA*i$nment Specify t"e ertica* a*i$nment of t"e para$rap"& T"is is a constant $roup of type com&sun&star&te3t&'ara$rap"OertA*i$n %it" a*id a*ues: A5T1MAT)# ? 0 H )n automatic mode, "oriConta* te3t is a*i$ned to t"e base*ine& T"e same app*ies to te3t t"at is rotated B0 de$rees& Te3t t"at is rotated 2M0 de$rees is a*i$ned to t"e center& +AS2L)42 ? 1 H T"e te3t is a*i$ned to t"e base*ine& T1' ? 2 H T"e te3t is a*i$ned to t"e top& #24T2R ? 3 H T"e te3t is a*i$ned to t"e center& +1TT1M ? ! H T"e te3t is a*i$ned to bottom& 'ara5serDefinedAttributes Stores IML attributes t"at are saed and restored from t"e automatic sty*es inside IML fi*es& T"e ob/ect imp*ements t"e com&sun&star&container&I4ame#ontainer interface& 4umberin$)s4umber )f True, t"e numberin$ of a para$rap" is a number but "as no symbo*& T"is is oid if t"e para$rap" is not part of a para$rap" numberin$ se8uence& 'ara)s#onnect+order )f True, para$rap" borders are mer$ed %it" t"e preious para$rap" if t"e borders are identica*& T"is property may be oid& TIP 'ara$rap" properties are usua**y set usin$ para$rap" sty*esLat *east t"ey s"ou*d be& Many of t"e properties in Tab*e 126 are structures7 t"ey re8uire specia* care if you %ant to modify t"em, because a structure is copied by a*ue rat"er t"an by reference& 0or e3amp*e, t"e 'araLineSpacin$ property is a structure& A*t"ou$" t"e code in Listin$ 320 *oo(s correct, it fai*s7 t"is usa$e is a ery common error committed by 11o +asic pro$rammers& Listing 320. his code fails because 9araLine*pacing is a structure. oPar&Para,ineSpacin&Mode 6 co!&#un&#tar&#t.le&,ineSpacin&,EA-IHJ T"e code in Listin$ 320 fai*s because t"e code Do'ar&'araLineSpacin$F made a copy of t"e structure& T"e Mode is set, but it is set on*y on t"e copy, *eain$ t"e ori$ina* intact& T"e code in Listin$ 321 demonstrates t"e proper %ay to modify t"e a*ue of a structure %"en it is used as a property& A copy of t"e structure is stored in t"e ariab*e , %"ic" is t"en modified and copied bac(& Listing 321. his works because it makes a copy and then copies it back. : 6 oPar&Para,ineSpacin :&Mode 6 co!&#un&#tar&#t.le&,ineSpacin&,EA-IHJ oPar&Para,ineSpacin 6 : 360 !nsert a page brea* To insert a pa$e brea(, set t"e 'a$eDesc4ame property to t"e name of t"e pa$e sty*e to use after t"e pa$e brea(& T"is sty*e may be t"e same as t"e current pa$e sty*e7 it is t"e act of settin$ t"e 'a$eDesc4ame propertyLnot c"an$in$ it to a ne% a*ueLt"at causes a pa$e brea( to occur& T"e pa$e sty*e name must e3ist in t"e document or a pa$e brea( is not inserted& ;"en you insert a pa$e brea(, you can a*so set a ne% pa$e number by settin$ t"e 'a$e4umber1ffset property to t"e ne% pa$e number& See Listin$ 322& TIP )t is rare to insert a pa$e brea( %"i*e enumeratin$ para$rap"s& )t is more common to insert a pa$e brea( usin$ a te3t cursor or a te3t ran$e& 6ou can use any serice t"at supports para$rap" properties to insert a pa$e brea(& Listing 322. "nsert a page break after the last paragraph. Sub SetPaeBrea1AtEnd"ro!Enu!eration -i! oEnu! )co!&#un&#tar&container&/Enu!erationAcce## -i! oPar3e#t )Pararap( o$ #o!e #ort -i! oPar ),a#t Pararap( obNect REM "ind t(e la#t pararap( oEnu! 6 3(i#Co!ponent&3ext&createEnu!erationBC -o W(ile oEnu!&(a#MoreEle!ent#BC oPar3e#t 6 oEnu!&nextEle!entBC I$ oPar3e#t&#upport#Ser:iceB"co!&#un&#tar&text&Pararap("C 3(en oPar 6 oPar3e#t End I$ ,oop
REM Hote t(at t(i# doe# not actuall. c(ane t(e pae #t.le na!e oPar&Pae-e#cHa!e 6 oPar&PaeSt.leHa!e
REM Set t(e ne* pae nu!ber to be 2 oPar&PaeHu!berO$$#et 6 2 End Sub /et the paragraph st'le T"e 'araSty*e4ame property indicates t"e para$rap" sty*e for t"at para$rap"& T"is property may be direct*y set& Listing 323. $numerate the paragraph styles in the current document. Sub Enu!erateParSt.le#BC -i! oEnu! )co!&#un&#tar&container&/Enu!erationAcce## -i! oCurPar ),a#t Pararap( obNect& -i! #F )Jeneral #trin :ariable& oEnu! 6 3(i#Co!ponent&3ext&createEnu!erationBC -o W(ile oEnu!&(a#MoreEle!ent#BC oCurPar 6 oEnu!&nextEle!entBC # 6 # 4 oCurPar&ParaSt.leHa!e 4 CHRFB>7C ,oop M#Box # End Sub 361 1$.2.2. Character properties 'ara$rap"s contain numerous c"aracter9re*ated properties& Li(e t"e para$rap"9specific properties, t"ese properties are optiona* and are encapsu*ated in serices& T"e properties t"at are primari*y re*ated to c"aracters are found t"e #"aracter'roperties serice ,see Ta'le ).0.& TIP Many of t"e properties are represented by a a*ue in a constant $roup& #onstant $roups associate meanin$fu* names to constant a*ues& 0or e3amp*e, t"e #"ar0ont0ami*y accepts t"e a*ue com&sun&star&a%t&0ont0ami*y&R1MA4 to specify a Roman font %it" serifs& A a*ue of 3 may a*so be used& )n a*most a** cases, t"e first a*ue is 0, t"e second a*ue is 1, and so on& #ode t"at uses t"e descriptie names is easier to read and understand& Table 127. 9roperties supported by the com.sun.style./haracter9roperties service. Property Description #"ar0ont4ame Specify t"e name of t"e font in %estern te3t& T"is may be a comma9separated *ist of names& #"ar0ontSty*e4ame Specify t"e name of t"e font sty*e& #"ar0ont0ami*y Specify t"e name of t"e font fami*y as specified in com&sun&star&a%t&0ont0ami*y constant $roup& D14T<41; ? 0 H T"e font fami*y is not (no%n& D2#1RAT)O2 ? 1 H T"e font fami*y uses decoratie fonts& M1D2R4 ? 2 H T"e font fami*y is a modern font7 t"is is a specific sty*e& R1MA4 ? 3 H T"e font fami*y is a Roman font %it" serifs& S#R)'T ? ! H T"e font fami*y is a script font& S;)SS ? A H T"e font fami*y is a Roman font %it"out serifs& S6ST2M ? 6 H T"e font fami*y is a system font& #"ar0ont#"arSet Specify t"e te3t encodin$ of t"e font usin$ t"e com&sun&star&a%t&#"arSet constant $roup& T"e a*ues are se*f9e3p*anatory: D14T<41;, A4S), MA#, )+M'#=!3M ,)+M '# c"aracter set number !3M., )+M'#=@A0, )+M'#=@60, )+M'#=@6, )+M'#=@63, )+M'#=@6A, S6ST2M, and S6M+1L& #"ar0ont'itc" Specify t"e c"aracter font pitc" usin$ t"e com&sun&star&a%t&0ont'itc" constant $roup& T"e a*ues are se*f9e3p*anatory: D14T<41;, 0)I2D, and OAR)A+L2& #"ar#o*or Specify t"e te3t co*or as a Lon$ )nte$er& #"ar2scapement Specify t"e S"ort )nte$er representin$ t"e percenta$e of raisin$ or *o%erin$ for superscript-subscript c"aracters& 4e$atie a*ues *o%er t"e c"aracters& #"arEei$"t Specify t"e c"aracter "ei$"t in points as a decima* number& #"ar5nder*ine Specify t"e c"aracter under*ine type usin$ t"e com&sun&star&a%t&0ont5nder*ine constant $roup& 4142 ? 0 H 4o under*inin$& S)4JL2 ? 1 H Sin$*e *ine& D15+L2 ? 2 H Doub*e *ine& D1TT2D ? 3 H Dotted *ine& D14T<41; ? ! H 5n(no%n under*inin$& DASE ? A H Das"ed *ine& L14JDASE ? 6 H Lon$ das"es& DASED1T ? M H Das" and dot se8uence& 362 Property Description DASED1TD1T ? @ H Das", dot, dot se8uence& SMALL;AO2 ? B H Sma** %ae& ;AO2 ? 10 H ;ae& D15+L2;AO2 ? 11 H Doub*e %ae& +1LD ? 12 H +o*d *ine& +1LDD1TT2D ? 13 H +o*d dots& +1LDDASE ? 1! H +o*d das"es& +1LDL14JDASE ? 1A H Lon$ bo*d das"es& +1LDDASED1T ? 16 H Das" and dot se8uence in bo*d& +1LDDASED1TD1T ? 1M H Das", dot, dot se8uence in bo*d& +1LD;AO2 ? 1@ H +o*d %ae& #"ar;ei$"t Specify t"e font %ei$"t usin$ t"e com&sun&star&a%t&0ont;ei$"t constant $roup& D14T<41; ? 0&000 H 4ot specified-un(no%n& TE)4 ? A0&00 H A0X font %ei$"t& 5LTRAL)JET ? 60&00 H 60X font %ei$"t& L)JET ? MA&00 H MAX font %ei$"t& S2M)L)JET ? B0&00 H B0X font %ei$"t& 41RMAL ? 100&00 H norma* font %ei$"t ,100X.& S2M)+1LD ? 110&00 H 110X font %ei$"t& +1LD ? 1A0&00 H 1A0X font %ei$"t& 5LTRA+1LD ? 1MA&00 H 1MAX font %ei$"t& +LA#< ? 200&00 H 200X font %ei$"t& #"ar'osture Specify t"e c"aracter posture usin$ t"e com&sun&star&a%t&0ontS*ant enumeration %it" a*ues: 4142 H 4o s*ant, re$u*ar te3t& 1+L)_52 H 1b*i8ue font ,s*ant not desi$ned into t"e font.& )TAL)# H )ta*ic font ,s*ant desi$ned into t"e font.& D14T<41; H 5n(no%n s*ant& R2O2RS2=1+L)_52 H Reerse ob*i8ue ,s*ant not desi$ned into t"e font.& R2O2RS2=)TAL)# H Reerse ita*ic font ,s*ant desi$ned into t"e font.& #"arAuto<ernin$ Set to True to use t"e (ernin$ tab*es for t"e current font& Automatic (ernin$ ad/usts t"e spacin$ bet%een certain pairs of c"aracters to improe readabi*ity& #"ar+ac(#o*or Specify t"e te3t bac($round co*or as a Lon$ )nte$er& #"ar+ac(Transparent )f True, t"e te3t bac($round co*or is transparent& #"ar#aseMap Specify "o% c"aracters s"ou*d be disp*ayed usin$ t"e com&sun&star&sty*e&#aseMap constant $roup& T"is does not c"an$e t"e actua* te3tLon*y t"e %ay it is disp*ayed& 4142 ? 0 H 4o case mappin$ is performed7 t"is is t"e most common*y used a*ue& 5''2R#AS2 ? 1 H A** c"aracters are disp*ayed in uppercase& L1;2R#AS2 ? 2 H A** c"aracters are disp*ayed in *o%ercase& T)TL2 ? 3 H T"e first c"aracter of eac" %ord is disp*ayed in uppercase& SMALL#A'S ? ! H A** c"aracters are disp*ayed in uppercase, but %it" a sma**er font& 363 Property Description #"ar#rossed1ut )f True, t"e c"aracters "ae a *ine t"rou$" t"em& #"ar0*as" )f True, t"e c"aracters are disp*ayed f*as"in$& #"arStri(eout Specify c"aracter stri(eout usin$ t"e com&sun&star&a%t&0ontStri(eout constant $roup: 4142 ? 0 H Do not stri(e out c"aracters& S)4JL2 ? 1 H Stri(e out t"e c"aracters %it" a sin$*e *ine& D15+L2 ? 2 H Stri(e out t"e c"aracters %it" a doub*e *ine& D14T<41; ? 3 H T"e stri(eout mode is not specified& +1LD ? ! H Stri(e out t"e c"aracters %it" a bo*d *ine& SLASE ? A H Stri(e out t"e c"aracters %it" s*as"es& I ? 6 H Stri(e out t"e c"aracters %it" IVs& #"ar;ordMode )f True, %"ite spaces ,spaces and tabs. i$nore t"e #"arStri(eout and #"ar5nder*ine properties& #"ar<ernin$ Specify t"e c"aracter (ernin$ a*ue as a S"ort )nte$er& #"arLoca*e Specify t"e c"aracter *oca*e as a com&star&*an$&Loca*e structure& #"ar<eepTo$et"er )f True, 11o tries to (eep t"e c"aracter ran$e on t"e same *ine& )f a brea( must occur, it occurs before t"e c"aracters& #"ar4oLine+rea( )f True, 11o i$nores a *ine brea( in t"e c"aracter ran$e& )f a brea( must occur, it occurs after t"e c"aracters so it is possib*e t"at t"ey %i** cross a border& #"arS"ado%ed )f True, t"e c"aracters are formatted and disp*ayed %it" a s"ado% effect& #"ar0ontType Specify t"e fundamenta* tec"no*o$y of t"e font usin$ t"e com&sun&star&a%t&0ontType constant $roup& D14T<41; ? 0 H T"e type of t"e font is not (no%n& RAST2R ? 1 H T"e font is a raster ,bitmapped. font& D2O)#2 ? 2 H T"e font is output9deice specific, suc" as a printer font& S#ALA+L2 ? 3 H T"e font is sca*ab*e& #"arSty*e4ame Specify t"e name of t"e font sty*e as a strin$& #"ar#ontoured )f True, c"aracters are formatted and disp*ayed %it" a contour ,39D out*ine. effect& #"ar#ombine)s1n )f True, te3t is formatted and disp*ayed usin$ t%o *ines& T"e #"ar#ombine'refi3 strin$ precedes t"e te3t in fu** siCe, and t"e #"ar#ombineSuffi3 fo**o%s t"e te3t in fu** siCe& #"ar#ombine'refi3 Specify t"e prefi3 ,usua**y parent"eses. used %it" t"e #"ar#ombine)s1n property& #"ar#ombineSuffi3 Specify t"e suffi3 ,usua**y parent"eses. used %it" t"e #"ar#ombine)s1n property& #"ar2mp"asiCe Specify t"e type and position of emp"asis mar(s in Asian te3ts usin$ t"e com&sun&star&te3t&0ont2mp"asis constant $roup: 4142 ? 0 H 4o emp"asis mar( is used& D1T=A+1O2 ? 1 H A dot is set aboe ,or ri$"t from ertica* te3t. t"e te3t& #)R#L2=A+1O2 ? 2 H A circ*e is set aboe ,or ri$"t from ertica* te3t. t"e te3t& D)S<=A+1O2 ? 3 H A dis( is set aboe ,or ri$"t from ertica* te3t. t"e te3t& A##24T=A+1O2 ? ! H An accent is set aboe ,or ri$"t from ertica* te3t. t"e te3t& D1T=+2L1; ? 11 H A dot is set be*o% ,or *eft from ertica* te3t. t"e te3t& #)R#L2=+2L1; ? 12 H A circ*e is set be*o% ,or *eft from ertica* te3t. t"e 364 Property Description te3t& D)S<=+2L1; ? 13 H A dis( is set be*o% ,or *eft from ertica* te3t. t"e te3t& A##24T=+2L1; ? 1! H An accent is set be*o% ,or *eft from ertica* te3t. t"e te3t& #"arRe*ief Specify t"e re*ief a*ue from t"e com&sun&star&te3t&0ontRe*ief constant $roup: 4142 ? 0 H 4o re*ief is used7 norma* te3t& 2M+1SS2D ? 1 H #"aracters *oo( embossed ,raised.& 24JRAO2D ? 2 H #"aracters *oo( en$raed ,*o%ered.& RubyTe3t Specify t"e te3t t"at is set as ruby& DRuby Te3tF acts as an annotation and is associated %it" a DRuby +ase&F T"is is typica**y used in Asian %ritin$ systems, proidin$ a "e*per for uncommon*y used %ritin$ c"aracters t"at are not easi*y reco$niCab*e, especia**y by c"i*dren& 0or e3amp*e, in Kapanese %ritin$, t"e p"onetic Eira$ana a*p"abet is used to pair p"onetic D"e*perF readin$s ,ca**ed 0uri$ana or 6omi$ana in Kapanese. %it" t"e #"inese c"aracter counterpart& RubyAd/ust Specify t"e ruby te3t ad/ustment usin$ t"e com&sun&star&te3t&RubyAd/ust enumeration: L20T H Ad/ust to t"e *eft& #24T2R H Ad/ust to t"e center& R)JET H Ad/ust to t"e ri$"t& +L1#< H Ad/ust to bot" borders ,stretc"ed.& )4D24T=+L1#< H Ad/ust to bot" borders %it" a sma** indent on bot" sides& Ruby#"arSty*e4ame Specify t"e name of t"e c"aracter sty*e t"at is app*ied to RubyTe3t& Ruby)sAboe )f True, t"e Ruby is printed aboe t"e te3t ,ri$"t if t"e te3t is ertica*.& #"arRotation Specify t"e rotation of a c"aracter in de$rees as a S"ort )nte$er& 4ot a** imp*ementations support a** a*ues& #"arRotation)s0itToLine )f True, 11o tries to fit t"e rotated te3t to t"e surroundin$ *ine "ei$"t& #"arSca*e;idt" Specify t"e sca*in$ for superscript and subscript as a percenta$e usin$ a S"ort )nte$er& EyperLin(5RL Specify t"e 5RL of a "yper*in( ,if set. as a Strin$& EyperLin(Tar$et Specify t"e name of t"e tar$et for a "yper*in( ,if set. as a Strin$& EyperLin(4ame Specify t"e name of t"e "yper*in( ,if set. as a Strin$& Oisited#"arSty*e4ame Specify t"e c"aracter sty*e for isited "yper*in(s as a Strin$& 5nisited#"arSty*e4ame Specify t"e c"aracter sty*e name for unisited "yper*in(s as a Strin$& #"ar2scapementEei$"t Specify t"e additiona* "ei$"t used for subscript or superscript c"aracters as an )nte$er percent& 0or subscript c"aracters t"e a*ue is ne$atie& #"ar4oEyp"enation )f True, t"e %ord cannot be "yp"enated at t"e c"aracter& #"ar5nder*ine#o*or Specify t"e co*or of t"e under*ine as a Lon$ )nte$er& #"ar5nder*ineEas#o*or )f True, t"e #"ar5nder*ine#o*or is used for an under*ine& #"arSty*e4ames An array of c"aracter sty*e names app*ied to t"e te3t& T"e order is not necessari*y re*eant& 365 TIP ;"en a property supports a D14T<41; a*ue, t"e property is usua**y used as a "int to perform certain operations more efficient*y or to find a c*ose rep*acement a*ue if t"e re8uested a*ue is not aai*ab*e& 0or e3amp*e, if a particu*ar font is not aai*ab*e, you can use t"e #"ar0ont0ami*y to c"oose a font of t"e correct type& T"e code in Listin$ 32! demonstrates modifyin$ t"e c"aracter properties by modifyin$ t"e 0ontRe*ief property and t"en c"an$in$ it bac(& Listing 324. *et then restore the font relief. Sub Oie*"ontRelie$ -i! oEnu! )co!&#un&#tar&container&/Enu!erationAcce## -i! oPar )Pararap( o$ #o!e #ort -i! iG )Jeneral Countin :ariable -i! #F
REM 3(e returned pararap( *ill be a pararap( or a text table I$ oPar&#upport#Ser:iceB"co!&#un&#tar&text&Pararap("C 3(en i 6 i W > oPar&C(arRelie$ 6 i MO- % End I$ ,oop
REM 3(e returned pararap( *ill be a pararap( or a text table I$ oPar&#upport#Ser:iceB"co!&#un&#tar&text&Pararap("C 3(en i 6 i W > oPar&C(arRelie$ 6 co!&#un&#tar&text&"ontRelie$&HOHE End I$ ,oop End Sub 1$.2.#. Enumerating text sections >paragraph portions? )t is not unusua* for a para$rap" to contain te3t %it" dissimi*ar formattin$Lfor e3amp*e, a sin$*e %ord may be disp*ayed in 'ol& in t"e midd*e of a sentence t"at is disp*ayed in t"e fontGs norma* state& Kust as you can enumerate t"e para$rap"s in a document, you can enumerate t"e te3t sections in a para$rap"& Te3t %it"in eac" enumerated portion uses t"e same properties and is of t"e same type& Tab*e 12@ *ists t"e properties direct*y supported by t"e Te3t'ortion serice& T"e Te3t'ortion serice e3ports t"e Te3tRan$e serice so it a*so supports t"e para$rap" properties in Tab*e 126 and t"e c"aracter properties in Tab*e 12M& 366 TIP An ob/ect t"at supports para$rap" or c"aracter properties typica**y proides a %ay to enc*ose a ran$e of te3t& )f a specific property c"an$es a*ue in t"e te3t ran$e, it usua**y isnGt aai*ab*e to be set& 0or e3amp*e, a te3t ran$e can contain more t"an one para$rap"& )f a** of t"e contained para$rap"s in t"e te3t ran$e do not support t"e same para$rap" sty*e, t"e para$rap" sty*e property is not aai*ab*e to t"e te3t ran$e& )f, "o%eer, t"e te3t ran$e is reduced to contain on*y para$rap"s t"at support a sin$*e para$rap" sty*e, t"e para$rap" sty*e property %i** be aai*ab*e to t"at te3t ran$e& Table 128. 9roperties supported by the com.sun.te.t.e.t9ortion service. Property Description Te3t'ortionType Strin$ containin$ t"e type of t"e te3t portion& Oa*id content type names are: Te3t H Strin$ content& Te3t0ie*d H Te3t0ie*d content& Te3t#ontent H )ndicates t"at te3t content is anc"ored as or to a c"aracter t"at is not rea**y part of t"e para$rap"Lfor e3amp*e, a te3t frame or a $rap"ic ob/ect& As of 11o 1&1&0 and 11o 1&1&1, t"e type D0rameF is returned rat"er t"an DTe3t#ontentF& T"e 11o team refers to t"is as issue W2!!!!& 0rame H T"is is not a documented return a*ue, but it is returned rat"er t"an t"e type DTe3t#ontentF& 0ootnote H 0ootnote or endnote& #ontro*#"aracter H #ontro* c"aracter& ReferenceMar( H Reference mar(& Document)nde3Mar( H Document inde3 mar(& +oo(mar( H +oo(mar(& Red*ine H Red*ine portion, %"ic" is a resu*t of t"e c"an$e9trac(in$ feature& Ruby H Ruby attribute ,used in Asian te3t.& #ontro*#"aracter S"ort )nte$er containin$ t"e contro* c"aracter if t"e te3t portion contains a #ontro*#"aracter& +oo(mar( )f t"e te3t content is a boo(mar(, t"is is a reference to t"e boo(mar(& T"e property imp*ements t"e com&sun&star&te3t&ITe3t#ontent interface& )s#o**apsed )f True, t"e te3t portion is a point& )sStart )f True, t"e te3t portion is a start portion if t%o portions are needed to inc*ude an ob/ect& 0or e3amp*e, a Docment)nde3Mar( "as a start and end te3t portion surroundin$ t"e te3t to be inde3ed& T"e macro in Listin$ 32A demonstrates enumeratin$ t"e te3t content inside a para$rap"& )t disp*ays t"e para$rap" number and t"e inc*uded te3t portion types in a dia*o$& T"e para$rap" number is ca*cu*ated and is not a property of t"e para$rap"& Listing 325. *ee te.t portion types. Sub Enu!erate3extSection# -i! oParEnu! )Pararap( enu!erator -i! o#ecEnu! )3ext #ection enu!erator -i! oPar )Current pararap( -i! oParSection )Current #ection -i! nPar# A# Inteer )Hu!ber o$ pararap(# -i! #F
I$ oPar&#upport#Ser:iceB"co!&#un&#tar&text&Pararap("C 3(en nPar# 6 nPar# W > oSecEnu! 6 oPar&createEnu!erationBC # 6 # 4 nPar# 4 ":" -o W(ile oSecEnu!&(a#MoreEle!ent#BC oParSection 6 oSecEnu!&nextEle!entBC # 6 # 4 oParSection&3extPortion3.pe 4 ":" ,oop # 6 # 4 CHRFB>7C I$ nPar# MO- >7 6 7 3(en M#Box #= 7= "Pararap( 3ext Section#" # 6 "" End I$ End I$ ,oop M#Box #= 7= "Pararap( 3ext Section#" End Sub 14.3. 5raphics T"e fo**o%in$ macro inserts a te3t $rap"ic ob/ect as a *in( in to t"e current document& T"is is a te3t $rap"ics ob/ect, %"ic" is inserted at a cursor position& A*t"ou$" you must set t"e ima$e siCe, you do not need to set t"e position& Listing 326. "nsert a <raphics as a link at the start of the document. Sub In#ertJrap(icObNectBo-oc= #0R,FC -i! oCur#or -i! oJrap( -i! o3ext o3ext 6 o-oc&et3extBC oCur#or 6 o3ext&create3extCur#orBC oCur#or&o3oStartB"A,SEC oJrap( 6 o-oc&createIn#tanceB"co!&#un&#tar&text&Jrap(icObNect"C Wit( oJrap( &Jrap(ic0R, 6 #0R, &Anc(or3.pe 6 co!&#un&#tar&text&3extContentAnc(or3.pe&AS5CHARAC3ER &Widt( 6 A777 &Hei(t 6 Q777 End Wit( )no* in#ert t(e i!ae into t(e text docu!ent o3ext&in#ert3extContentB oCur#or= oJrap(= "al#e C End Sub 6ou can a*so insert a $rap"ics ob/ect s"ape, %"ic" is inserted into t"e dra% pa$e rat"er t"an at a cursor *ocation, but you must use a com&sun&star&dra%in$&Jrap"ic1b/ectS"ape, and t"en set bot" t"e *ocation and t"e siCe& 368 Sometimes, you must $uess t"e ima$e siCe because it is not aai*ab*e& T"e fo**o%in$ met"od assumes t"at t"e ar$ument is a serice of type com&sun&star&$rap"ic&Jrap"icDescriptor, %"ic" optiona**y proides t"e ima$e siCe in 100t" mm and in pi3e*s& T"e met"od returns a a*ue in 100t" mm, %"ic" is %"at is re8uired for t"e interna* disp*ay& )nte$ers are not used because t"e intermediate a*ues may be *ar$e& )f t"e siCe is aai*ab*e in 100t" mm, t"en t"is is used& 4e3t, t"e siCe is c"ec(ed in 'i3e*s& An ima$e "as bot" a siCe in pi3e*s, and an e3pected pi3e* density ,Dots 'er )nc".& ;e may "ae t"e number of pi3e*s, but %e do not "ae t"e D')& ) $uess t"e pi3e* density as t"e pi3e* density of t"e computer disp*ay& )n ot"er %ords, if t"e e3pected siCe is not aai*ab*e, t"en assume t"at t"is %as created for disp*ay on t"e current monitor& Listing 327. <uess image size. "unction Reco!!endJrap(Si8eBoJrap(C -i! oSi8e -i! lMaxW A# -ouble ) Maxi!u! *idt( in >77t( !! -i! lMaxH A# -ouble ) Maxi!u! (ei(t in >77t( !! lMaxW 6 A&2< * '<?7 ) A&2< inc(e# lMaxH 6 @&< * '<?7 ) @&< inc(e#
I$ I#HullBoJrap(C OR I#E!pt.BoJrap(C 3(en Exit "unction End I$ oSi8e 6 oJrap(&Si8e>77t(MM I$ oSi8e&Hei(t 6 7 OR oSi8e&Widt( 6 7 3(en ) '<?7 i# '<&?7 !! in an inc(= but I need >77t( !!& ) 3(ere are >??7 t*ip# in an inc( oSi8e&Hei(t 6 oJrap(&Si8ePixel&Hei(t * '<?7&7 * 3*ip#PerPixelPBC + >??7 oSi8e&Widt( 6 oJrap(&Si8ePixel&Widt( * '<?7&7 * 3*ip#PerPixel/BC + >??7 End I$ I$ oSi8e&Hei(t 6 7 OR oSi8e&Widt( 6 7 3(en )oSi8e&Hei(t 6 '<?7 )oSi8e&Widt( 6 '<?7 Exit "unction End I$ I$ oSi8e&Widt( D lMaxW 3(en oSi8e&Hei(t 6 oSi8e&Hei(t * lMaxW + oSi8e&Widt( oSi8e&Widt( 6 lMaxW End I$ I$ oSi8e&Hei(t D lMaxH 3(en oSi8e&Widt( 6 oSi8e&Widt( * lMaxH + oSi8e&Hei(t oSi8e&Hei(t 6 lMaxH End I$ Reco!!endJrap(Si8e 6 oSi8e End "unction An ima$e is embedded as fo**o%s: 1& A s"ape is created and added to t"e dra% pa$e& 2& T"e $rap"ic proider serice is used to obtain ima$e descriptor from dis( before it is *oaded& 369 3& T"e ima$e descriptor is used to $uess t"e ima$e siCe& T"e ima$e siCe is $uessed, because %e on*y (no% %"at is in t"e descriptor, and t"e descriptor may not rea**y (no%& !& T"e s"ape is set to ima$e as proided by t"e $rap"ic proider serice& At t"is point, t"e ima$e is *oaded and (no%n by 11o& A& A ne%*y created $rap" ob/ect sets its 5RL to t"e 5RL used by t"e s"ape ob/ect& As suc", t"e $rap"ic and t"e s"ape s"ou*d reference t"e same ima$e& 6& T"e $rap" is anc"ored as a c"aracter and t"en inserted into t"e document at t"e cursor& M& T"e s"ape is no *on$er re8uired, so it is remoed& 0or reasons ) do not understand, a** ima$es inserted as a ery sma** ima$es ,*ess t"an 1 cm.& ) use t"e $uessed ima$e siCe to set t"e $rap"ic siCe& Listing 328. $mbed an image in a document. ) o-oc 9 docu!ent to contain t(e i!ae& ) oCur# 9 Cur#or *(ere t(e i!ae i# added ) #0R, 9 0R, o$ t(e i!ae to in#ert& ) #ParSt.le 9 #et t(e pararap( #t.le to t(i#& Sub E!bedJrap(icBo-oc= oCur#= #0R,F= #ParSt.leFC -i! oS(ape -i! oJrap( )3(e rap(ic obNect i# text content& -i! oPro:ider )Jrap(icPro:ider #er:ice& -i! o3ext oS(ape 6 o-oc&createIn#tanceB"co!&#un&#tar&dra*in&Jrap(icObNectS(ape"C oJrap( 6 o-oc&createIn#tanceB"co!&#un&#tar&text&Jrap(icObNect"C o-oc&et-ra*PaeBC&addBoS(apeC oPro:ider 6 create0noSer:iceB"co!&#un&#tar&rap(ic&Jrap(icPro:ider"C -i! oProp#B7C a# ne* co!&#un&#tar&bean#&Propert.Oalue oProp#B7C&Ha!e 6 "0R," oProp#B7C&Oalue 6 #0R, REM Sa:e t(e oriinal #i8e& -i! oSi8e>77t(MM -i! lHei(t A# ,on -i! lWidt( A# ,on oSi8e>77t(MM 6 Reco!!endJrap(Si8eBoPro:ider&;uer.Jrap(ic-e#criptorBoProp#CC I$ HO3 I#HullBoSi8e>77t(MMC AH- HO3 I#E!pt.BoSi8e>77t(MMC 3(en lHei(t 6 oSi8e>77t(MM&Hei(t lWidt( 6 oSi8e>77t(MM&Widt( End I$ oS(ape&Jrap(ic 6 oPro:ider&;uer.Jrap(icBoProp#BCC oJrap(&rap(icurl 6 oS(ape&rap(icurl oJrap(&Anc(or3.pe 6 co!&#un&#tar&text&3extContentAnc(or3.pe&AS5CHARAC3ER o3ext6 oCur#&et3extBC o3ext&in#ert3extContentBoCur#= oJrap(= $al#eC o-oc&et-ra*PaeBC&re!o:eBoS(apeC 370 I$ lHei(t D 7 AH- lWidt( D 7 3(en -i! oSi8e oSi8e 6 oJrap(&Si8e oSi8e&Hei(t 6 lHei(t oSi8e&Widt( 6 lWidt( oJrap(&Si8e 6 oSi8e End I$
) Set t(e pararap( #t.le i$ it i# in t(e docu!ent& -i! oSt.le# oSt.le# 6 o-oc&St.le"a!ilie#&etB.Ha!eB"Pararap(St.le#"C I$ oSt.le#&(a#B.Ha!eB#ParSt.leC 3(en oCur#&ParaSt.leHa!e 6 #ParSt.le End I$ End Sub After copyin$ a %eb pa$e and pastin$ it into a te3t document, a** of t"e ima$es are embedded& Jrap"ics in a document contain t"e Jrap"ic5RL property& T"e 5RL for a $rap"ic contained in t"e document be$ins %it" t"e Dnd&sun&star&Jrap"i1b/ect:F& Jrap"ic inserted usin$ t"e A') are inserted as *in(s H t"ey are not embedded into t"e document %it"out some %or(& T"e fo**o%in$ macro brin$s many concepts to$et"er to find a** *in(ed ima$es and conert t"em into embedded ima$es contained in t"e document& Listing 329. /onvert all linked images to embedded images. Sub Con:ertAll,in1edJrap(ic#BOptional a-ocC -i! o-oc ) Wor1in docu!ent -i! o-P ) -ra* pae -i! iG ) Index counter -i! oJrap( ) Jrap( obNect in t(e dra* pae -i! i,in1edG ) Hu!ber o$ lin1ed i!ae# -i! iE!beddedG ) Hu!ber o$ e!bedded i!ae# -i! iCon:ertedG ) ,in1ed i!ae# con:erted to e!bedded -i! #>F ) Jrap(ic #er:ice na!e -i! #'F ) Jrap(ic #er:ice na!e REM Onl. 1no* (o* to con:ert t(e#e t.pe# #> 6 "co!&#un&#tar&dra*in&Jrap(icObNectS(ape" #' 6 "co!&#un&#tar&text&3extJrap(icObNect" I$ I#Mi##inBa-ocC OR I#HullBa-ocC OR I#E!pt.Ba-ocC 3(en o-oc 6 3(i#Co!ponent El#e o-oc 6 a-oc End I$ REM Jet t(e docu!ent dra* pae and t(en enu!erate t(e i!ae#& o-P 6 o-oc&et-ra*PaeBC "or i67 3o o-P&etCountBC9> oJrap( 6 o-P&etB.IndexBiC I$ oJrap(&#upport#Ser:iceB#>C OR oJrap(&#upport#Ser:iceB#'C 3(en I$ InStrBoJrap(&Jrap(ic0R,= ":nd&#un"C ED 7 3(en 371 iE!bedded 6 iE!bedded W > El#e i,in1ed 6 i,in1ed W > I$ E!bed,in1edJrap(icBoJrap(= o-ocC 3(en iCon:erted 6 iCon:erted W > End I$ End I$ End I$ Hext Print ""ound " 4 i,in1ed 4 " lin1ed and " 4 iE!bedded 4 5 " e!bedded i!ae# and con:erted " 4 iCon:erted End Sub "unction E!bed,in1edJrap(icBoJrap(= o-ocC A# Boolean REM Aut(or: Andre* Piton.a1 -i! #Jrap(0R,F ) External 0R, o$ t(e i!ae& -i! oJrap(5' ) Created i!ae& -i! oCur# ) Cur#or *(ere t(e i!ae i# located& -i! o3ext ) 3ext obNect containin i!ae& -i! oAnc(or ) Anc(or point o$ t(e i!ae -i! #>F ) Jrap(ic #er:ice na!e -i! #'F ) Jrap(ic #er:ice na!e E!bed,in1edJrap(ic 6 "al#e I$ InStrBoJrap(&Jrap(ic0R,= ":nd&#un"C ED 7 3(en REM Inore an i!ae t(at i# alread. e!bedded Exit "unction End I$ #> 6 "co!&#un&#tar&dra*in&Jrap(icObNectS(ape" #' 6 "co!&#un&#tar&text&3extJrap(icObNect" I$ oJrap(&#upport#Ser:iceB#>C 3(en REM Con:ert a Jrap(icObNectS(ape& oAnc(or 6 oJrap(&etAnc(orBC o3ext 6 oAnc(or&et3extBC
REM Con:ert a 3extJrap(icObNect& -i! oBit!ap# -i! #He*0R,F -i! #Ha!eF #Ha!eF 6 oJrap(&,in1-i#pla.Ha!e oBit!ap# 6 o-oc&createIn#tanceB "co!&#un&#tar&dra*in&Bit!ap3able" C 372 I$ oBitMap#&(a#B.Ha!eB#Ha!eC 3(en Print ",in1 di#pla. na!e " 4 #Ha!e 4 " alread. exi#t#" Exit "unction End I$ )Print "Read. to in#ert " 4 #Ha!e oBit!ap#&in#ertB.Ha!eB #Ha!e= oJrap(&Jrap(ic0R, C #He*0R,F 6 oBit!ap#&etB.Ha!eB #Ha!e C )Print "in#erted 0R, " 4 #He*0R, oJrap(&Jrap(ic0R, 6 #He*0R, E!bed,in1edJrap(ic 6 3rue End I$ End "unction 14.4. Cursors T"e capabi*ity to enumerate t"e entire te3t content is primari*y used for tas(s suc" as e3portin$ a document, because e3portin$ re8uires a** of t"e content to be accessed in se8uentia* order& A more typica* met"od for accessin$ and manipu*atin$ a document ino*es t"e use of cursors& A Te3t#ursor is a Te3tRan$e, %"ic" can be moed %it"in a Te3t ob/ect& )n ot"er %ords, a te3t cursor not on*y can specify a sin$*e point in t"e te3t, but it a*so can encompass a ran$e of te3t& 6ou can use t"e cursor moement met"ods to reposition t"e cursor and to e3pand t"e section of se*ected te3t& T%o primary types of te3t cursors are aai*ab*e in 11o: cursors t"at are ie% cursors ,see Tab*e 12B. and cursors t"at are not ,see Tab*e 131.& 1$.$.1. 5ie1 cursors As its name imp*ies, t"e ie% cursor dea*s %it" t"e isib*e cursor& )n a sin$*e document %indo%, you see one ie% at a time& Ana*o$ous*y, you can "ae one ie% cursor at a time& Oie% cursors support commands t"at are direct*y re*ated to ie%in$& To moe a cursor one *ine at a time, or one screen at a time, re8uires a ie% cursor& T"e ie% cursor (no%s "o% t"e te3t is disp*ayed ,see Tab*e 130.& Table 129. "n general) view cursors are not related to te.t ranges or :e.t/ursor. Crsor Description com&sun&star&ie%&IOie%#ursor Simp*e cursor %it" basic moement met"ods t"at %or( in bot" te3t and tab*es& com&sun&star&te3t&ITe3tOie%#ursor Deried from ITe3t#ursor, t"is describes a cursor in a te3t documentGs ie%& )t supports on*y ery simp*e moements& com&sun&star&ie%&ILine#ursor Defines *ine9re*ated met"ods7 t"is interface is not deried from a te3t ran$e& com&sun&star&te3t&I'a$e#ursor Defines pa$e9re*ated met"ods7 t"is interface is not deried from a te3t ran$e& com&sun&star&ie%&IScreen#ursor Defines met"ods to moe up and do%n one screen at a time& Most of t"e cursor moement met"ods accept a +oo*ean ar$ument t"at determines %"et"er t"e te3t ran$e of t"e cursor is e3panded ,True. or %"et"er t"e cursor is simp*y moed to t"e ne% position ,0a*se.& )n ot"er %ords, if t"e +oo*ean e3pression is 0a*se, t"e cursor is moed to t"e ne% position and no te3t is se*ected by t"e cursor& T"e description of t"e +oo*ean ariab*e is assumed and not e3p*icit*y stated for eac" of t"e cursor moement met"ods in Tab*e 130& Anot"er commona*ity %it" t"e moement met"ods is t"at t"ey return a +oo*ean a*ue& A True a*ue means t"at t"e moement %or(ed, and a 0a*se a*ue means t"at t"e moement fai*ed& A moement re8uest fai*s if it cannot be comp*eted successfu**y& )t is not possib*e, for e3amp*e, to 373 moe t"e cursor do%n if it is a*ready at t"e end of t"e document& T"e screen cursor is obtained from t"e documentGs current contro**er ,see Listin$ 330.& Table 130. Ob%ect methods related to view cursors. Defined )et6od Description IOie%#ursor $oDo%n,n, +oo*ean. Moe t"e cursor do%n by n *ines& IOie%#ursor $o5p,n, +oo*ean. Moe t"e cursor up by n *ines& IOie%#ursor $oLeft,n, +oo*ean. Moe t"e cursor *eft by n c"aracters& IOie%#ursor $oRi$"t,n, +oo*ean. Moe t"e cursor ri$"t by n c"aracters& ITe3tOie%#ursor isOisib*e,. Return True if t"e cursor is isib*e& ITe3tOie%#ursor setOisib*e,+oo*ean. S"o% or "ide t"e cursor& ITe3tOie%#ursor $et'osition,. Return a com&sun&star&a%t&'oint structure specifyin$ t"e cursorGs coordinates re*atie to t"e top9*eft position of t"e first pa$e of t"e document& ILine#ursor isAtStart1fLine,. Return True if t"e cursor is at t"e start of t"e *ine& ILine#ursor isAt2nd1fLine,. Return True if t"e cursor is at t"e end of t"e *ine& ILine#ursor $oto2nd1fLine,+oo*ean. Moe t"e cursor to t"e end of t"e current *ine& ILine#ursor $otoStart1fLine,+oo*ean. Moe t"e cursor to t"e start of t"e current *ine& I'a$e#ursor /umpTo0irst'a$e,. Moe t"e cursor to t"e first pa$e& I'a$e#ursor /umpToLast'a$e,. Moe t"e cursor to t"e *ast pa$e& I'a$e#ursor /umpTo'a$e,n. Moe t"e cursor to t"e specified pa$e& I'a$e#ursor $et'a$e,. Return t"e current pa$e as a S"ort )nte$er& I'a$e#ursor /umpTo4e3t'a$e,. Moe t"e cursor to t"e ne3t pa$e& I'a$e#ursor /umpTo'reious'a$e,. Moe t"e cursor to t"e preious pa$e& I'a$e#ursor /umpTo2nd1f'a$e,. Moe t"e cursor to t"e end of t"e current pa$e& I'a$e#ursor /umpToStart1f'a$e,. Moe t"e cursor to t"e start of t"e current pa$e& IScreen#ursor screenDo%n,. Scro** t"e ie% for%ard by one isib*e pa$e& IScreen#ursor screen5p,. Scro** t"e ie% bac(%ard by one isib*e pa$e& Listing 330. *croll#ownOne*creen is found in the 'riter module in this chapterSs source code files as */(F.s.w. Sub Scroll-o*nOneScreen REM Jet t(e :ie* cur#or $ro! t(e current controller 3(i#Co!ponent¤tController&etOie*Cur#orBC&#creen-o*nBC End Sub A more typica* use of t"e ie% cursor is to insert some specia* te3t content at t"e current cursor position& T"e macro in Listin$ 331 inserts t"e c"aracter %it" 5nicode a*ue 2AM ,DaF %it" a bar oer it. at t"e current cursor position& T"is type of macro is typica**y associated %it" a (eystro(e to insert specia* c"aracters t"at are not present on t"e (eyboard& T"e macro in Listin$ 331 is s"ort and simp*e, yet ery usefu*& 374 Listing 331. "nsert the character with Unicode value =IT at the current cursor. Sub In#ertControlC(aracterAtCurrentCur#or -i! oOie*Cur#or A# ObNect oOie*Cur#or 6 3(i#Co!ponent&CurrentController&etOie*Cur#orBC oOie*Cur#or&et3ext&in#ertStrinBoOie*Cur#or&etStartBC= CHRFB'<2C= "al#eC End Sub 1$.$.2. Text >non7'ie1? cursors T"e ie% cursor (no%s "o% t"e data is disp*ayed, but doesnGt (no% about t"e data itse*f& Te3t cursors ,non9 ie% cursors., "o%eer, (no% a *ot about t"e data but ery *itt*e about "o% it is disp*ayed& 0or e3amp*e, ie% cursors do not (no% about %ords or para$rap"s, and te3t cursors do not (no% about *ines, screens, or pa$es ,see Tab*e 131.& Table 131. e.t cursor interfaces all implement the :e.t/ursor interface. Crsor Description com&sun&star&te3t&ITe3t#ursor T"e primary te3t cursor t"at defines simp*e moement met"ods& com&sun&star&te3t&I;ord#ursor 'roides %ord9re*ated moement and testin$ met"ods& com&sun&star&te3t&ISentence#ursor 'roides sentence9re*ated moement and testin$ met"ods& com&sun&star&te3t&I'ara$rap"#ursor 'roides para$rap"9re*ated moement and testin$ met"ods& com&sun&star&te3t&ITe3tOie%#ursor Deried from ITe3t#ursor, t"is describes a cursor in a te3t documentGs ie%& TIP Te3t cursors and ie% cursors "ae some oer*ap& T"e ITe3tOie%#ursor is deried from t"e ITe3t#ursor so it supports t"e ITe3t#ursor met"ods& T"is does not proide functiona*ity %it" respect to t"e under*yin$ data suc" as %ord9re*ated or para$rap"9re*ated met"ods ,see Tab*e 132.& T"e %ord cursor, sentence cursor, and para$rap" cursor a** define essentia**y identica* ob/ect met"ods ,see Tab*e 132.& T"e ITe3tOie%#ursor interface is *isted in Tab*e 130 so it is omitted from Tab*e 132& Table 132. Ob%ect methods related to te.t cursors. Defined )et6od Description ITe3t#ursor co**apseToStart,. Set t"e end position to t"e start position& ITe3t#ursor co**apseTo2nd,. Set t"e start position to t"e end position& ITe3t#ursor is#o**apsed,. Return True if t"e start and end positions are t"e same& ITe3t#ursor $oLeft,n, +oo*ean. Moe t"e cursor *eft by n c"aracters& ITe3t#ursor $oRi$"t,n, +oo*ean. Moe t"e cursor ri$"t by n c"aracters& ITe3t#ursor $otoStart,+oo*ean. Moe t"e cursor to t"e start of t"e te3t& ITe3t#ursor $oto2nd,+oo*ean. Moe t"e cursor to t"e end of t"e te3t& ITe3t#ursor $otoRan$e,ITe3tRan$e, +oo*ean. Moe or e3pand t"e cursor to t"e Te3tRan$e& I;ord#ursor isStart1f;ord,. Return True if at t"e start of a %ord& I;ord#ursor is2nd1f;ord,. Return True if at t"e end of a %ord& 375 Defined )et6od Description I;ord#ursor $oto4e3t;ord,+oo*ean. Moe to t"e start of t"e ne3t %ord& I;ord#ursor $oto'reious;ord,+oo*ean. Moe to t"e end of t"e preious %ord& I;ord#ursor $oto2nd1f;ord,+oo*ean. Moe to t"e end of t"e current %ord& I;ord#ursor $otoStart1f;ord,+oo*ean. Moe to t"e start of t"e current %ord& ISentence#ursor isStart1fSentence,. Return True if at t"e start of a sentence& ISentence#ursor is2nd1fSentence,. Return True if at t"e end of a sentence& ISentence#ursor $oto4e3tSentence,+oo*ean. Moe to t"e start of t"e ne3t sentence& ISentence#ursor $oto'reiousSentence,+oo*ean. Moe to t"e end of t"e preious sentence& ISentence#ursor $oto2nd1fSentence,+oo*ean. Moe to t"e end of t"e current sentence& ISentence#ursor $otoStart1fSentence,+oo*ean. Moe to t"e start of t"e current sentence& I'ara$rap"#ursor isStart1f'ara$rap",. True if at t"e start of a para$rap"& I'ara$rap"#ursor is2nd1f'ara$rap",. True if at t"e end of a para$rap"& I'ara$rap"#ursor $oto4e3t'ara$rap",+oo*ean. Moe to t"e start of t"e ne3t para$rap"& I'ara$rap"#ursor $oto'reious'ara$rap",+oo*ean. Moe to t"e end of t"e preious para$rap"& I'ara$rap"#ursor $oto2nd1f'ara$rap",+oo*ean. Moe to t"e end of t"e current para$rap"& I'ara$rap"#ursor $otoStart1f'ara$rap",+oo*ean. Moe to t"e start of t"e current para$rap"& 1$.$.#. 9sing cursors to tra'erse text A*t"ou$" traersin$ te3t usin$ a cursor is not in"erent*y difficu*t, ) stru$$*ed %it" cursors for a *on$ time before ) fina**y rea*iCed t"at ) "ad a ery basic and yet simp*e misunderstandin$& A ery common, and yet subt*y incorrect, met"od of traersin$ te3t content usin$ cursors is s"o%n in Listin$ 332& T"is macro attempts to moe t"e cursor from one para$rap" to t"e ne3t, se*ectin$ one para$rap" at a time& Typica**y, somet"in$ %ou*d be done to manipu*ate or modify t"e para$rap", suc" as settin$ t"e para$rap" sty*e& Listing 332. $.ample of incorrect use of cursorsJ his code misses the last paragraph in the document. -i! oCur#or REM Create a text cur#or oCur#or 6 3(i#Co!ponent&3ext&create3extCur#orBC REM Start at t(e beinnin o$ t(e docu!ent& REM 3(i# i# t(e #a!e a# t(e #tart o$ t(e $ir#t docu!ent& oCur#or&otoStartB"al#eC REM And t(i# i# *(ere t(in# o *ronK REM 3(e cur#or no* #pan# $ro! t(e #tart o$ t(e REM $ir#t pararap( to t(e #tart o$ t(e #econd pararap(& -o W(ile oCur#or&otoHextPararap(B3rueC REM Proce## t(e pararap( (ereK REM Ho*= de#elect all o$ t(e text= lea:in t(e cur#or at t(e REM #tart o$ t(e next pararap(& oCur#or&oRi(tB7= "al#eC ,oop TIP ) produced incorrect code as s"o%n in Listin$ 332 before ) understood cursors& 376 T"e prob*em in Listin$ 332 is t"at t"e met"od $oto4e3t'ara$rap",True. causes t"e cursor to e3tend its se*ection from t"e start of one para$rap" to t"e start of t"e ne3t& T"e first prob*em %it" se*ectin$ from t"e start of one para$rap" to t"e start of t"e ne3t is t"at more t"an /ust one para$rap" is se*ected& )f t"e t%o different para$rap"s do not "ae t"e same para$rap" sty*e, t"e 'araSty*e4ame property %i** return an empty strin$ rat"er t"an a a*ue& T"e second prob*em is t"at %"en t"e cursor ,as s"o%n in Listin$ 332. is positioned at t"e start of t"e *ast para$rap", it is not possib*e to $o to t"e ne3t para$rap" because t"e ne3t para$rap" does not e3ist& T"erefore, t"e statement D$oto4e3t'ara$rap",True.F returns 0a*se and t"e *ast para$rap" is neer processed& T"e code in Listin$ 333 demonstrates one correct met"od of traersin$ a** of t"e para$rap"s usin$ a cursor& Listing 333. he correct way to use cursors. -i! oCur#or REM Create a text cur#or& oCur#or 6 3(i#Co!ponent&3ext&create3extCur#orBC REM Start at t(e beinnin o$ t(e docu!ent& REM 3(i# i# t(e #a!e a# t(e #tart o$ t(e $ir#t docu!ent& oCur#or&otoStartB"al#eC -o REM 3(e cur#or i# alread. po#itioned at t(e #tart REM o$ t(e current pararap(= #o #elect t(e entire pararap(& oCur#or&otoEndO$Pararap(B3rueC REM Proce## t(e pararap( (ereK REM 3(e ,oop #tate!ent !o:e# to t(e next pararap( and REM it al#o de#elect# t(e text in t(e cur#or& ,oop W(ile oCur#or&otoHextPararap(B"al#eC T"e point is to a*i$n t"e cursor oer t"e current para$rap", and t"en iterate a*i$ned %it" t"e para$rap"s, rat"er t"an eer *oo(in$ a"ead to t"e ne3t para$rap" %"i*e in t"e midst of dea*in$ %it" t"e cursor& TIP 6ou can use cursors and enumeration to traerse an entire document and obtain a** of t"e para$rap"s& 5sin$ a cursor is fie times faster t"an usin$ an enumerator& )t is ery simp*e to %rite an iterator t"at traerses t"e te3t %"i*e countin$ t"e %ords, sentences, and para$rap"s ,see Listin$ 33!.& Listing 334. /ount paragraphs) sentences) and words. Sub CountWordSentPar -i! oCur#or -i! nPar# A# ,on -i! nSentence# A# ,on -i! nWord# A# ,on
REM Create a text cur#or& oCur#or 6 3(i#Co!ponent&3ext&create3extCur#orBC oCur#or&otoStartB"al#eC -o nPar# 6 nPar# W > ,oop W(ile oCur#or&otoHextPararap(B"al#eC oCur#or&otoStartB"al#eC -o nSentence# 6 nSentence# W > ,oop W(ile oCur#or&otoHextSentenceB"al#eC 377
oCur#or&otoStartB"al#eC -o nWord# 6 nWord# W > ,oop W(ile oCur#or&otoHextWordB"al#eC
M#Box "Pararap(#: " 4 nPar# 4 CHRFB>7C 45 "Sentence#: " 4 nSentence# 4 CHRFB>7C 45 "Word#: " 4 nWord# 4 CHRFB>7C= 7= "-oc Stati#tic#" End Sub TIP ;it" 11o 1&1, ) found $oto4e3tSentence,. and $oto4e3t;ord,. to be unre*iab*e, but t"e para$rap" cursor %or(ed %e**& To count %ords, t"erefore, ) used t"e %ord count macros from Andre% +ro%s: http122www.&arwinwars.com2lunatic2'ugs2oo3macros.html& Heep the view cursor and te:t cursor in s'nc A para$rap" is bro(en into *ines based on t"e pa$e mar$ins& Ad/ust t"e pa$e mar$ins and t"e *ine brea(s c"an$e& A*so, te3t copied from %riter as te3t do not contain t"e pa$e brea(s& 0or t"e rea* %or*d e3amp*e in Listin$ 33A adds rea* *ine brea(s into t"e te3t based on "o% t"e *ines brea( on screen& Both a view cursor and a non-view cursor are required to move through the text. The view cursor knows where a line ends, but it does not know where the paragraph starts or ends. A non-view cursor knows about paragraphs, but the view cursor does not. Listin$ 33A moes t"e ie% cursor around on t"e screen, demonstratin$ "o% to c"an$e its *ocation& Listing 335. -dd line breaks in a paragraph. Sub ,ineBrea1#InPararap( -i! o3ext )Sa:e t.pin 3(i#Co!ponent&3ext -i! oOie*Cur#or )Sa:e t.pin 3(i#Co!ponent&CurrentController&etOie*Cur#orBC -i! o3extCur#or )Created text cur#or -i! oSa:eCur#or )In ca#e I *ant to re#tore t(e :ie* cur#or
o3ext 6 3(i#Co!ponent&3ext
REM Pou re;uire a :ie* cur#or REM becau#e onl. t(e :ie* 1no*# *(ere a line end#& oOie*Cur#or 6 3(i#Co!ponent&CurrentController&etOie*Cur#orBC
REM Pou re;uire a text cur#or #o t(at .ou 1no* *(ere t(e pararap( end#& REM 3oo bad t(e :ie* cur#or i# not a pararap( cur#or& o3extCur#or 6 o3ext&create3extCur#orB.RaneBoOie*Cur#orC
REM Pou onl. need t(i# i$ .ou *ant to re#tore t(e :ie* cur#or oSa:eCur#or 6 o3ext&create3extCur#orB.RaneBoOie*Cur#orC REM Mo:e t(e cur#or to t(e #tart o$ t(e current pararap( REM #o t(at t(e entire pararap( can be proce##ed& I$ HO3 o3extCur#or&i#StartO$Pararap(BC 3(en 378 o3extCur#or&otoStartO$Pararap(B"al#eC oOie*Cur#or&otoRaneBo3extCur#or= "al#eC End I$ REM Ho* :i#it eac( line o$ t(e pararap(& -o W(ile 3rue REM Onl. t(e :ie* cur#or 1no*# *(ere t(e end o$ t(e line i# REM becau#e t(i# i# a $or!attin i##ue and not deter!ined b. REM punctuation& oOie*Cur#or&otoEndO$,ineB$al#eC
REM Mo:e *it( t(e :ie* cur#or to t(e end o$ t(e current line REM and t(en #ee i$ .ou)re at t(e end o$ t(e pararap(& o3extCur#or&otoRaneBoOie*Cur#or= "al#eC
REM C(ec1 $or end o$ pararap( BE"ORE in#ertin t(e line brea1& I$ o3extCur#or&i#EndO$Pararap(BC 3(en Exit -o
REM In#ert a line brea1 at t(e current :ie* cur#or& o3ext&in#ertControlC(aracterBoOie*Cur#or=5 co!&#un&#tar&text&ControlC(aracter&,IHE5BREA^= $al#eC ,oop REM I$ .ou onl. *ant to !o:e t(e cur#or a*a. $ro! t(e end o$ t(e REM current pararap(= t(en t(i# *ill #u$$ice& oOie*Cur#or&oRi(tB>= "al#eC REM I *ant to re#tore t(e :ie* cur#or location= (o*e:er& REM oOie*Cur#or&otoRaneBoSa:eCur#or= "al#eC End Sub 1$.$.$. )ccessing content using cursors ) "ae a "abit of inspectin$ t"e ob/ects returned to me by 11o& ;"i*e inspectin$ a ie% cursor, ) noticed t"at t"e ie% cursor contained usefu* undocumented properties& Accordin$ to t"e dee*opers at Sun, t"ese %i** eentua**y be documented& Some of t"e properties t"at ) noticed inc*ude: #e**, Document)nde3, Document)nde3Mar(, 2ndnote, 0ootnote, ReferenceMar(, Te3t, Te3t0ie*d, Te3t0rame, Te3tSection, and Te3tTab*e& )f a cursor is in a te3t tab*e, t"e cursorGs Te3tTab*e property is not empty& )f a cursor is on a te3t fie*d, t"e cursorGs Te3t0ie*d property is not empty& T"ese specia* properties are empty if t"ey are not re*eant& ) first used t"ese undocumented properties %"en ) %as as(ed "o% to determine if t"e ie% cursor %as positioned in a te3t tab*e, and if so, %"at ce** contains t"e ie% cursor& See Listin$ 336& Listing 336. esting view cursor properties. I$ HO3 I#E!pt.BoOie*Cur#or&3ext3ableC 3(en #ursors proide t"e abi*ity to 8uic(*y find ob/ects in c*ose pro3imity to somet"in$ e*se& 0or e3amp*e, ) %as recent*y as(ed "o% to find a te3t fie*d contained in t"e current para$rap"Lt"e current para$rap" is defined as t"e para$rap" containin$ t"e ie% cursor& )tGs easy to obtain t"e ie% cursor, and you can use a para$rap" cursor to moe around t"e current para$rap"& My first attempt ca**ed t"e create#ontent2numeration,Zcom&sun&star&te3t&Te3t#ontentZ. ob/ect met"od on t"e cursor& T"is creates an enumeration of te3t content, enumeratin$ ob/ects suc" as inserted buttons& ) "ad mista(en*y assumed t"at t"is %ou*d inc*ude te3t fie*ds in t"e enumeration& My second attempt to find a te3t fie*d, %"ic" %as successfu*, uses t"e create2numeration,. ob/ect met"od& T"e create2numeration,. met"od returns an enumeration of t"e para$rap"s contained in t"e cursor& 2numeratin$ t"e content contained in a 379 para$rap" proides access to t"e te3t fie*d& My fina* attempt, %"ic" %as a*so successfu*, moes t"e cursor to t"e start of t"e document and t"en moes t"rou$" t"e para$rap" one *ocation at a time *oo(in$ for a te3t fie*d& T"e macro in Listin$ 33M demonstrates a** of t"e met"ods t"at ) used to try to find a te3t fie*d in t"e current para$rap"& Listing 337. /heck current paragraph for a te.t field. Sub 3ext"ieldInCurrentPararap( -i! oEnu! )Cur#or enu!erator -i! oSection )Current #ection -i! oOie*Cur#or )Current :ie* cur#or -i! o3extCur#or )Created text cur#or -i! o3ext )3ext obNect in current docu!ent -i! #F -i! #3extContentF )Ser:ice na!e $or text content& #3extContent 6 "co!&#un&#tar&text&3extContent"
REM Obtain t(e :ie* cur#or= and t(en #elect t(e pararap( REM containin t(e :ie* cur#or& o3extCur#or 6 o3ext&create3extCur#orB.RaneBoOie*Cur#orC
REM Mo:e to t(e #tart o$ t(e pararap( a# a #inle point& o3extCur#or&otoStartO$Pararap(B"al#eC REM Mo:e to t(e end o$ t(e current pararap( and expand t(e REM #election #o t(at t(e entire pararap( i# #elected& o3extCur#or&otoEndO$Pararap(B3rueC
REM I *ant to enu!erate t(e text content contained b. t(i# text cur#or& REM Alt(ou( t(i# *ill $ind in#erted dra*in obNect#= #uc( a# t(e #(ape REM u#ed b. a button= it *ill not $ind a text $ieldK oEnu! 6 o3extCur#or&createContentEnu!erationB#3extContentC -o W(ile oEnu!&(a#MoreEle!ent#BC oSection 6 oEnu!&nextEle!entBC Print "Enu!eratin 3extContent: " 4 oSection&I!ple!entationHa!e ,oop REM And t(i# enu!erate# t(e pararap(# t(at are contained in REM t(e text cur#or& oEnu! 6 o3extCur#or&createEnu!erationBC -i! : -o W(ile oEnu!&(a#MoreEle!ent#BC : 6 oEnu!&nextEle!entBC -i! oSubSection -i! oSecEnu!
REM Ho* create an enu!eration o$ t(e pararap(#& REM We can enu!erate t(e #ection# o$ t(e pararap( to REM obtain t(e text $ield and ot(er pararap( content& oSecEnu! 6 :&createEnu!erationBC # 6 "Enu!eratin #ection t.pe: " 4 :&I!ple!entationHa!e 380 -o W(ile oSecEnu!&(a#MoreEle!ent#BC oSubSection 6 oSecEnu!&nextEle!entBC # 6 # 4 CHRFB>7C 4 oSubSection&3extPortion3.pe I$ oSubSection&3extPortion3.pe 6 "3ext"ield" 3(en # 6 # 4 " E66 3.pe " 4 oSubSection&3ext"ield&I!ple!entationHa!e End I$ ,oop M#Box #= 7= "Enu!erate Sinle Pararap(" ,oop
REM And t(i# i# .et anot(er *a. to $ind t(e text $ield& REM Start at t(e beinnin o$ t(e pararap( and t(en !o:e t(e cur#or REM t(rou( it= loo1in $or text $ield#& o3extCur#or&otoStartO$Pararap(B"al#eC -o W(ile o3extCur#or&oRi(tB>= "al#eC AH- 5 HO3 o3extCur#or&i#EndO$Pararap(BC I$ HO3 I#E!pt.Bo3extCur#or&3ext"ieldC 3(en Print "It i# HO3 e!pt.= .ou can u#e t(e text $ield" End I$ ,oop End Sub TIP As unintuitie as it sounds, it is not on*y possib*eLbut commonLfor t"e end of a te3t ran$e to come before t"e start of a te3t ran$e& T"e order of t"e start and end is primari*y an issue %"en dea*in$ %it" te3t se*ected by a "uman user but may a*so occur due to t"e moement of a te3t cursor %"i*e e3pandin$ t"e te3t ran$e& As t"e ob/ect met"ods $etStart,. and $et2nd,. imp*y, itGs possib*e for a te3t ran$e to represent a sin$*e point& )tGs a*so possib*e t"at t"e start position comes after t"e end position& 5ne3pected start and end positions are typica**y a prob*em %"i*e dea*in$ %it" se*ected te3t& ;"en you se*ect te3t usin$ a mouse or your (eyboard, t"e initia* se*ection point is $enera**y t"e start *ocation& Moin$ t"e fina* se*ection point to%ard t"e start of t"e document causes t"e end position to occur before t"e start position in t"e te3t ran$e& T"e same be"aior may occur %"i*e manua**y moin$ and e3pandin$ a cursor& T"is be"aior is not documented, but it "as been obsered in 11o 1&1&0, and *i(e a** undocumented be"aior, it may c"an$e at any time& T"e te3t ob/ect can compare t%o ran$es ,see Tab*e 133., but t"e te3t ob/ect must contain bot" te3t ran$esLa te3t ran$e "as t"e $etTe3t,. ob/ect met"od to return t"e te3t ob/ect t"at contains t"e te3t ran$e& Table 133. Methods defined by the com.sun.star.te.t.:e.tRange/ompare interface. )et6od Description compareRe$ionStarts,ITe3tRan$e, ITe3tRan$e. Return 1 if t"e first ran$e starts before t"e second& Return 0 if t"e first ran$e starts at t"e same position as t"e second& Return 91 if t"e first ran$e starts after t"e second& compareRe$ion2nds,ITe3tRan$e, ITe3tRan$e. Return 1 if t"e first ran$e ends before t"e second& Return 0 if t"e first ran$e ends at t"e same position as t"e second& Return 91 if t"e first ran$e ends after t"e second& 381 14.. /elected te:t Se*ected te3t refers to t"e te3t t"at "as been se*ected by a user, probab*y usin$ t"e (eyboard or t"e mouse& Se*ected te3t is represented as not"in$ more t"an a te3t ran$e& After you find a te3t se*ection, itGs possib*e to $et t"e te3t c$etStrin$,.d and set t"e te3t csetStrin$,.d& A*t"ou$" strin$s are *imited to 6!<+ in siCe, se*ections are not& T"ere are some instances, t"erefore, %"en you canGt use t"e $etStrin$,. and setStrin$,. met"ods& T"erefore, itGs probab*y better to use a cursor to traerse t"e se*ected te3t and t"en use t"e cursorGs te3t ob/ect to insert te3t content& Most prob*ems usin$ se*ected te3t *oo( t"e same at an abstract *ee*& I$ not(in i# #elected t(en do *or1 on entire docu!ent el#e $or eac( #elected area do *or1 on #elected area T"e difficu*t part t"at c"an$es eac" time is %ritin$ a macro t"at iterates oer a se*ection or bet%een t%o te3t ran$es& 1$.,.1. Is text selected: Te3t documents support t"e ITe3tSectionsSupp*ier interface ,see Tab*e 122., %"ic" defines t"e sin$*e met"od $et#urrentSe*ection,.& )f t"ere is no current contro**er ,%"ic" means t"at youGre an adanced user runnin$ 1pen1ffice&or$ as a serer %it" no user interface and you %onGt be *oo(in$ for se*ected te3t any%ay., $et#urrentSe*ection,. returns a nu** rat"er t"an any se*ected te3t& )f t"e se*ection count is Cero, not"in$ is se*ected& ) "ae neer seen a se*ection count of Cero, but ) c"ec( for it any%ay& )f no te3t is se*ected, t"ere is one se*ection of Cero *en$t"Lt"e start and end positions are t"e same& ) "ae seen e3amp*es, %"ic" ) consider unsafe, %"ere a Cero9*en$t" se*ection is determined as fo**o%s: I$ ,enBoSel&etStrinBCC 6 7 3(en not(in i# #elected )t is possib*e t"at se*ected te3t %i** contain more t"an 6!<+ c"aracters, and a strin$ cannot contain more t"an 6!<+ c"aracters& T"erefore, donGt c"ec( t"e *en$t" of t"e se*ected strin$ to see if it is Cero7 t"is is not safe& T"e better so*ution is to create a te3t cursor from t"e se*ected ran$e and t"en c"ec( to see if t"e start and end points are t"e same& oCur#or 6 o-oc&3ext&Create3extCur#orB.RaneBoSelC I$ oCur#or&I#Collap#edBC 3(en not(in i# #elected T"e macro function in Listin$ 33@ performs t"e entire c"ec(, returnin$ True if somet"in$ is se*ected, and 0a*se if not"in$ is se*ected& Listing 338. #etermine if anything is selected. "unction I#An.t(inSelectedBo-oc A# ObNectC A# Boolean -i! oSelection# )Contain# all o$ t(e #election# -i! oSel )Contain# one #peci$ic #election -i! oCur#or )3ext cur#or to c(ec1 $or a collap#ed rane REM A##u!e not(in i# #elected I#An.t(inSelected 6 "al#e I$ I#HullBo-ocC 3(en Exit "unction ) 3(e current #election in t(e current controller& )I$ t(ere i# no current controller= it return# H0,,& oSelection# 6 o-oc&etCurrentSelectionBC I$ I#HullBoSelection#C 3(en Exit "unction 382 I$ oSelection#&etCountBC 6 7 3(en Exit "unction I$ oSelection#&etCountBC D > 3(en REM 3(ere i# !ore t(an one #election #o return 3rue I#An.t(inSelected 6 3rue El#e REM 3(ere i# onl. one #election #o obtain t(e $ir#t #election oSel 6 oSelection#&etB.IndexB7C
REM Create a text cur#or t(at co:er# t(e rane and t(en #ee i$ it i# REM collap#ed& oCur#or 6 o-oc&3ext&Create3extCur#orB.RaneBoSelC I$ Hot oCur#or&I#Collap#edBC 3(en I#An.t(inSelected 6 3rue REM Pou can al#o co!pare t(e#e to #ee i$ t(e #election #tart# and end# at REM t(e #a!e location& REM I$ o-oc&3ext&co!pareReionStart#BoSel&etStartBC=5 REM oSel&etEndBCC ED 7 3(en REM I#An.t(inSelected 6 3rue REM End I$ End I$ End "unction 1btainin$ a se*ection is comp*icated because itGs possib*e to "ae mu*tip*e non9conti$uous se*ections& Some se*ections are empty and some are not& )f you %rite code to "and*e te3t se*ection, it s"ou*d "and*e a** of t"ese cases because t"ey occur fre8uent*y& T"e e3amp*e in Listin$ 33B iterates t"rou$" a** se*ected sections and disp*ays t"em in a messa$e bo3& Listing 339. #isplay selected te.t. Sub PrintMultiple3extSelection -i! oSelection# )Contain# all o$ t(e #election# -i! oSel )Contain# one #peci$ic #election -i! lW(ic(Selection A# ,on )W(ic( #election to print
I$ HO3 I#An.t(inSelectedB3(i#Co!ponentC 3(en Print "Hot(in i# #elected" El#e oSelection# 6 3(i#Co!ponent&etCurrentSelectionBC "or lW(ic(Selection 6 7 3o oSelection#&etCountBC 9 > oSel 6 oSelection#&etB.IndexBlW(ic(SelectionC M#Box oSel&etStrinBC= 7= "Selection " 4 lW(ic(Selection Hext End I$ End Sub 1$.,.2. elected textA 8hich end is 1hich: Se*ections are te3t ran$es %it" a start and an end& A*t"ou$" se*ections "ae bot" a start and an end, %"ic" side of t"e te3t is %"ic" is determined by t"e se*ection met"od& 0or e3amp*e, position t"e cursor in t"e midd*e of a *ine, and t"en se*ect te3t by moin$ t"e cursor eit"er ri$"t or *eft& )n bot" cases, t"e start position is t"e same& )n one of t"ese cases, t"e start position is after t"e end position& T"e te3t ob/ect proides met"ods to compare startin$ and endin$ positions of te3t ran$es ,see Tab*e 133.& ) use t"e t%o met"ods in Listin$ 3!0 to find t"e *eftmost and ri$"tmost cursor position of se*ected te3t& 383 Listing 340. <et left and right cursor. )oSel i# a text #election or cur#or rane )o3ext i# t(e text obNect "unction Jet,e$tMo#tCur#orBoSel= o3extC -i! oRane -i! oCur#or I$ o3ext&co!pareReionStart#BoSel&etEndBC= oSelC D6 7 3(en oRane 6 oSel&etEndBC El#e oRane 6 oSel&etStartBC End I$ oCur#or 6 o3ext&Create3extCur#orB.RaneBoRaneC oCur#or&oRi(tB7= "al#eC Jet,e$tMo#tCur#or 6 oCur#or End "unction )oSel i# a text #election or cur#or rane )o3ext i# t(e text obNect "unction JetRi(tMo#tCur#orBoSel= o3extC -i! oRane -i! oCur#or
I$ o3ext&co!pareReionStart#BoSel&etEndBC= oSelC D6 7 3(en oRane 6 oSel&etStartBC El#e oRane 6 oSel&etEndBC End I$ oCur#or 6 o3ext&Create3extCur#orB.RaneBoRaneC oCur#or&o,e$tB7= "al#eC JetRi(tMo#tCur#or 6 oCur#or End "unction ;"i*e usin$ te3t cursors to moe t"rou$" a document, ) noticed t"at cursors remember t"e direction in %"ic" t"ey are trae*in$& T"e cursors returned by t"e macros in Listin$ 3!0 are oriented to trae* into t"e te3t se*ection by moin$ t"e cursor *eft or ri$"t Cero c"aracters& T"is is a*so an issue %"i*e moin$ a cursor to t"e ri$"t and t"en turnin$ it around to moe *eft& ) a*%ays start by moin$ t"e cursor Cero c"aracters in t"e desired direction before actua**y moin$ t"e cursor& T"en my macro can use t"ese cursors to traerse t"e se*ected te3t from t"e start ,moin$ ri$"t. or t"e end ,moin$ *eft.& 1$.,.#. elected text frame1ork ;"i*e dea*in$ %it" se*ected te3t, ) use a frame%or( t"at returns a t%o9dimensiona* array of start and end cursors oer %"ic" to iterate& 5sin$ a frame%or( a**o%s me to use a ery minima* code base to iterate oer se*ected te3t or t"e entire document& )f no te3t is se*ected, t"e frame%or( as(s if t"e macro s"ou*d use t"e entire document& )f t"e ans%er is yes, a cursor is created at t"e start and t"e end of t"e document& )f te3t is se*ected, eac" se*ection is retrieed, and a cursor is obtained at t"e start and end of eac" se*ection& See Listin$ 3!1& Listing 341. /reate cursors with selected areas. )#Pro!pt : Ho* to a#1 i$ #(ould iterate o:er t(e entire text )oCur#or#BC : Ha# t(e return cur#or# 384 )Return# 3rue i$ #(ould iterate and "al#e i$ #(ould not "unction CreateSelected3extIteratorBo-oc= #Pro!ptF= oCur#or#BCC A# Boolean -i! oSelection# )Contain# all o$ t(e #election# -i! oSel )Contain# one #peci$ic #election -i! o3ext )-ocu!ent text obNect -i! lSelCount A# ,on )Hu!ber o$ #election# -i! lW(ic(Selection A# ,on )Current #election -i! o,Cur#or= oRCur#or )3e!porar. cur#or# CreateSelected3extIterator 6 3rue o3ext 6 o-oc&3ext I$ Hot I#An.t(inSelectedBo-ocC 3(en -i! iG iG 6 M#BoxB"Ho text #electedK" W CHRFB>%C W #Pro!pt= 5 > OR %' OR '<A= "Warnin"C I$ iG 6 > 3(en o,Cur#or 6 o3ext&create3extCur#orB.RaneBo3ext&etStartBCC oRCur#or 6 o3ext&create3extCur#orB.RaneBo3ext&etEndBCC oCur#or# 6 -i!Arra.B7= >C )3*o9-i!en#ional arra. *it( one ro* oCur#or#B7= 7C 6 o,Cur#or oCur#or#B7= >C 6 oRCur#or El#e oCur#or# 6 -i!Arra.BC )Return an e!pt. arra. CreateSelected3extIterator 6 "al#e End I$ El#e oSelection# 6 o-oc&etCurrentSelectionBC lSelCount 6 oSelection#&etCountBC oCur#or# 6 -i!Arra.BlSelCount 9 >= >C "or lW(ic(Selection 6 7 3o lSelCount 9 > oSel 6 oSelection#&etB.IndexBlW(ic(SelectionC o,Cur#or 6 Jet,e$tMo#tCur#orBoSel= o3extC oRCur#or 6 JetRi(tMo#tCur#orBoSel= o3extC oCur#or#BlW(ic(Selection= 7C 6 o,Cur#or oCur#or#BlW(ic(Selection= >C 6 oRCur#or Hext End I$ End "unction TIP T"e ar$ument o#ursors,. is an array t"at is set in t"e macro in Listin$ 3!1& T"e macro in Listin$ 3!2 uses t"e se*ected te3t frame%or( to print t"e 5nicode a*ues of t"e se*ected te3t& Listing 342. #isplay Unicode of the selected te.t. Sub Print0nicodeExa!ple# -i! oCur#or#BC= iG I$ Hot CreateSelected3extIteratorB3(i#Co!ponent= 5 "Print 0nicode $or t(e entire docu!entU"= oCur#or#BCC 3(en Exit Sub "or iG 6 ,BoundBoCur#or#BCC 3o 0BoundBoCur#or#BCC Print0nicode5*or1erBoCur#or#BiG= 7C= oCur#or#BiG= >C= 3(i#Co!ponent&3extC Hext iG End Sub 385 Sub Print0nicode5*or1erBo,Cur#or= oRCur#or= o3extC -i! # A# Strin )contain# t(e pri!ar. !e##ae #trin -i! ## A# Strin )u#ed a# a te!porar. #trin I$ I#HullBo,Cur#orC Or I#HullBoRCur#orC Or I#HullBo3extC 3(en Exit Sub I$ o3ext&co!pareReionEnd#Bo,Cur#or= oRCur#orC E6 7 3(en Exit Sub REM Start t(e cur#or in t(e correct direction *it( no text #elected o,Cur#or&oRi(tB7= "al#eC -o W(ile o,Cur#or&oRi(tB>= 3rueC5 AH- o3ext&co!pareReionEnd#Bo,Cur#or= oRCur#orC D6 7 ## 6 o,Cur#or&etStrinBC REM 3(e #trin !a. be e!pt. I$ ,enB##C D 7 3(en # 6 # 4 o,Cur#or&etStrinBC 4 "6" 4 ASCBo,Cur#or&etStrinBCC 4 " " End I$ o,Cur#or&oRi(tB7= "al#eC ,oop !#Box #= 7= "0nicode Oalue#" End Sub 1$.,.$. 6emo'e empt" spaces and linesA ) larger example A common re8uest is for a macro t"at remoes e3tra b*an( spaces& To remoe a** empty para$rap"s, itGs better to use t"e Remoe +*an( 'ara$rap"s option from t"e Auto#orrect dia*o$ ,Tools AutoCorrect Options Options.& To remoe on*y se*ected para$rap"s or runs of b*an( space, a macro is re8uired& T"is section presents a set of macros t"at rep*aces a** runs of %"ite9space c"aracters %it" a sin$*e %"ite9 space c"aracter& 6ou can easi*y modify t"is macro to de*ete different types of %"ite space& T"e different types of space are ordered by importance, so if you "ae a re$u*ar space fo**o%ed by a ne% para$rap", t"e ne% para$rap" stays and t"e sin$*e space is remoed& T"e end effect is t"at *eadin$ and trai*in$ %"ite space is remoed from eac" *ine& 1hat is white spaceE T"e term D%"ite spaceF typica**y refers to any c"aracter t"at is disp*ayed as a b*an( space& T"is inc*udes tabs ,AS#)) a*ue B., re$u*ar spaces ,AS#)) a*ue 32., non9brea(in$ spaces ,AS#)) a*ue 160., ne% para$rap"s ,AS#)) a*ue 13., and ne% *ines ,AS#)) a*ue 10.& +y encapsu*atin$ t"e definition of %"ite space into a function ,see Listin$ 3!3., you can triia**y c"an$e t"e definition of %"ite space to i$nore certain c"aracters& Listing 343. #etermine if a character is white space. "unction I#W(iteSpaceBiC(ar A# InteerC A# Boolean Select Ca#e iC(ar Ca#e @= >7= >%= %'= >A7 I#W(iteSpace 6 3rue Ca#e El#e I#W(iteSpace 6 "al#e End Select End "unction )f time is a serious issue, it is faster to create an array t"at is inde3ed by t"e 5nicode a*ue t"at contains true or fa*se to indicate if a c"aracter is %"ite space& T"e prob*em is t"at t"e array must be set before t"e ca**& "or i 6 ,BoundBi#W(iteArra.C 3o 0BoundBi#W(iteArra.C 386 i#W(iteArra.BiC 6 "al#e Hext i#W(iteArra.B@C 6 3rue i#W(iteArra.B>7C 6 3rue i#W(iteArra.B>%C 6 3rue i#W(iteArra.B%'C 6 3rue i#W(iteArra.B>A7C 6 3rue T"e function to test is as fo**o%s: "unction I#W(iteSpace'BiC(ar A# InteerC A# Boolean I$ iC(ar D 0BoundBi#W(iteArra.C 3(en I#W(iteSpace' 6 "al#e El#e I#W(iteSpace' 6 i#W(iteArra.BiC(arC End I$ End "unction %an* characters for deletion ;"i*e remoin$ runs of %"ite space, eac" c"aracter is compared to t"e c"aracter before it& )f bot" c"aracters are %"ite space, t"e *ess important c"aracter is de*eted& 0or e3amp*e, if t"ere is bot" a space and a ne% para$rap", t"e space is de*eted& T"e Ran(#"ar,. function ,see Listin$ 3!!. accepts t%o c"aracters: t"e preious c"aracter and t"e current c"aracter& T"e returned inte$er indicates %"ic", if any, c"aracter s"ou*d be de*eted& Listing 344. Rank characters for deletion. )9> !ean# delete t(e pre:iou# c(aracter ) 7 !ean# inore t(i# c(aracter ) > !ean# delete t(i# c(aracter ) I$ an input c(aracter i# 7= t(i# i# t(e #tart o$ a line& ) Ran1 $ro! (i(e#t to lo*e#t i#: 7= >%= >7= @= >A7= %' "unction Ran1C(arBiPre:C(ar= iCurC(arC A# Inteer I$ Hot I#W(iteSpaceBiCurC(arC 3(en )Current not *(ite #pace= inore it Ran1C(ar 6 7 El#eI$ iPre:C(ar 6 7 3(en ),ine #tart= current i# *(ite #pace Ran1C(ar 6 > ) delete t(e current c(aracter& El#eI$ Hot I#W(iteSpaceBiPre:C(arC 3(en )Current i# #pace but not pre:iou# Ran1C(ar 6 7 ) inore t(e current c(aracter&
REM At t(i# point= bot( c(aracter# are *(ite #pace El#eI$ iPre:C(ar 6 >% 3(en )Pre:iou# i# (i(e#t ran1ed #pace Ran1C(ar 6 > ) delete t(e current c(aracter& El#eI$ iCurC(ar 6 >% 3(en )Current i# (i(e#t ran1ed #pace Ran1C(ar 6 9> ) delete t(e pre:iou# c(aracter& REM Heit(er c(aracter i# a ne* pararap(= t(e (i(e#t ran1ed El#eI$ iPre:C(ar 6 >7 3(en )Pre:iou# i# ne* line Ran1C(ar 6 > ) delete t(e current c(aracter& El#eI$ iCurC(ar 6 >7 3(en )Current i# ne* line Ran1C(ar 6 9> ) delete t(e pre:iou# c(aracter& REM At t(i# point= t(e (i(e#t ran1in po##ible i# a tab El#eI$ iPre:C(ar 6 @ 3(en )Pre:iou# c(ar i# tab 387 Ran1C(ar 6 > ) delete t(e current c(aracter& El#eI$ iCurC(ar 6 @ 3(en )Current c(ar i# tab Ran1C(ar 6 9> ) delete t(e pre:iou# c(aracter& El#eI$ iPre:C(ar 6 >A7 3(en )Pre:iou# c(ar i# a (ard #pace Ran1C(ar 6 > ) delete t(e current c(aracter& El#eI$ iCurC(ar 6 >A7 3(en )Current c(ar i# a (ard #pace Ran1C(ar 6 9> ) delete t(e pre:iou# c(aracter& El#eI$ iPre:C(ar 6 %' 3(en )Pre:iou# c(ar i# a reular #pace Ran1C(ar 6 > ) delete t(e current c(aracter& REM Probabl. #(ould ne:er et (ere&&& bot( c(aracter# are *(ite #pace REM and t(e pre:iou# i# not an. 1no*n *(ite #pace c(aracter& El#eI$ iCurC(ar 6 %' 3(en )Current c(ar i# a reular #pace Ran1C(ar 6 9> ) delete t(e pre:iou# c(aracter& El#e )S(ould probabl. not et (ere Ran1C(ar 6 7 )#o #i!pl. inore itK End I$ End "unction )se the standard framewor* T"e standard frame%or( is used to remoe t"e empty spaces& T"e primary routine is simp*e enou$" t"at it bare*y %arrants mentionin$& Listing 345. Remove empty space. Sub Re!o:eE!pt.Space -i! oCur#or#BC= iG I$ Hot CreateSelected3extIteratorB3(i#Co!ponent= 5 "A,, e!pt. #pace *ill be re!o:ed $ro! t(e EH3IRE docu!entU"= oCur#or#BCC 3(en Exit Sub "or iG 6 ,BO0H-BoCur#or#BCC 3o 0BO0H-BoCur#or#BCC Re!o:eE!pt.SpaceWor1er BoCur#or#BiG= 7C= oCur#or#BiG= >C= 3(i#Co!ponent&3extC Hext iG End Sub 0he wor*er macro T"e macro in Listin$ 3!6 represents t"e interestin$ part of t"is prob*em7 it decides %"at is de*eted and %"at is *eft untouc"ed& Some interestin$ points s"ou*d be noted: Because a text cursor is used, the formatting is left unchanged. A text range (cursor) may contain text content that returns a zero-length string. This includes, for example, buttons and graphic images contained in the document. Handling exceptional cases adds complexity to the macro. Many tasks are very simple if you ignore the exceptional cases, such as inserted graphics. If you know that your macro will run with simple controlled data, you may choose to sacrifice robustness to reduce complexity. Listing 346 handles the exceptional cases. If the selected text starts or ends with white space, it will be removed even if it does not start or end the document. Listing 346. Remove$mpty*pace'orker. Sub Re!o:eE!pt.SpaceWor1erBo,Cur#or= oRCur#or= o3extC -i! # A# Strin )3e!porar. text #trin 388 -i! i A# Inteer )3e!porar. inteer u#ed $or co!parin text rane# -i! i,a#tC(ar A# Inteer )0nicode o$ la#t c(aracter -i! i3(i#C(ar A# Inteer )0nicode o$ t(e current c(aracter -i! iRan1 A# Inteer )Inteer ran1in t(at decide# *(at to delete
REM I$ #o!et(in i# null= t(en do not(in I$ I#HullBo,Cur#orC Or I#HullBoRCur#orC Or I#HullBo3extC 3(en Exit Sub REM Inore an. collap#ed rane# I$ o3ext&co!pareReionEnd#Bo,Cur#or= oRCur#orC E6 7 3(en Exit Sub REM -e$ault t(e $ir#t and la#t c(aracter to indicate #tart o$ ne* line i,a#tC(ar 6 7 i3(i#C(ar 6 7 REM Start t(e le$t!o#t cur#or !o:in to*ard t(e end o$ t(e docu!ent REM and !a1e certain t(at no text i# currentl. #elected& o,Cur#or&oRi(tB7= "al#eC REM At t(e end o$ t(e docu!ent= t(e cur#or can no loner !o:e ri(t -o W(ile o,Cur#or&oRi(tB>= 3rueC
REM It i# po##ible t(at t(e #trin i# 8ero lent(& REM 3(i# can (appen *(en #teppin o:er certain obNect# anc(ored into REM t(e text t(at contain no text& Extra care !u#t be ta1en becau#e REM t(i# routine can delete t(e#e ite!# becau#e t(e cur#or #tep# o:er REM t(e! but t(e. (a:e no text lent(& I arbitraril. call t(i# a reular REM ASCII c(aracter *it(out obtainin t(e #trin& # 6 o,Cur#or&etStrinBC I$ ,enB#C 6 7 3(en o,Cur#or&oRi(tB7= "al#eC i3(i#C(ar 6 A< El#e i3(i#C(ar 6 A#cBo,Cur#or&etStrinBCC End I$
REM I$ at t(e la#t c(aracter 3(en al*a.# re!o:e *(ite #pace i 6 o3ext&co!pareReionEnd#Bo,Cur#or= oRCur#orC I$ i 6 7 3(en I$ I#W(iteSpaceBi3(i#C(arC 3(en o,Cur#or&#etStrinB""C Exit -o End I$
REM I$ *ent pa#t t(e end t(en et out I$ i E 7 3(en Exit -o
iRan1 6 Ran1C(arBi,a#tC(ar= i3(i#C(arC I$ iRan1 6 > 3(en REM Read. to delete t(e current c(aracter& REM 3(e i,a#tC(ar i# not c(aned& REM -eletin t(e current c(aracter b. #ettin t(e text to t(e REM e!pt. #trin cau#e# no text to be #elected& )Print "-eletin Current *it( " W i,a#tC(ar W " and " W i3(i#C(ar 389 o,Cur#or&#etStrinB""C El#eI$ iRan1 6 9> 3(en REM Read. to delete t(e pre:iou# c(aracter& One c(aracter i# alread. REM #elected& It *a# #elected b. !o:in ri(t #o !o:in le$t t*o REM de#lect# t(e currentl. #elected c(aracter and #elect# t(e REM c(aracter to t(e le$t& o,Cur#or&o,e$tB'= 3rueC )Print "-eletin to t(e le$t *it( " W i,a#tC(ar W " and " W i3(i#C(ar o,Cur#or&#etStrinB""C REM Ho* t(e cur#or i# !o:ed o:er t(e current c(aracter aain but REM t(i# ti!e it i# not #elected& o,Cur#or&oRi(tB>= "al#eC REM Set t(e pre:iou# c(aracter to t(e current c(aracter& i,a#tC(ar 6 i3(i#C(ar El#e REM In#tructed to inore t(e current c(aracter #o de#elect an. text REM and t(en #et t(e la#t c(aracter to t(e current c(aracter& o,Cur#or&oRi(tB7= "al#eC i,a#tC(ar 6 i3(i#C(ar End I$ ,oop End Sub 1$.,.,. elected text& closing thoughts Anyone %"o "as studied a*$orit"ms %i** te** you t"at a better a*$orit"m is a*most a*%ays better t"an a faster computer& An ear*y prob*em t"at ) so*ed %as countin$ %ords in se*ected te3t& ) created t"ree so*utions %it" aryin$ de$rees of success& My first solution converted the selected text to OOo Basic strings and then manipulated the strings. This solution was fast, counting 8000 words in 2.7 seconds. This solution failed when text strings exceeded 64KB in size, rendering it useless for large documents. My second solution used a cursor as it walked through the text one character at a time. This solution, although able to handle any length of text, required 47 seconds to count the same 8000 words. In other words, the users found the solution unusably slow. My final solution used a word cursor, which counted the words in 1.7 seconds. Unfortunately, sometimes the word cursor is sometimes unreliable. TIP To count %ords correct*y, isit Andre% +ro%nGs usefu* macro ;eb site: http122www.&arwinwars.com2lunatic2'ugs2oo3macros.html& 14.#. /earch and replace T"e searc" process is directed by a searc" descriptor, %"ic" is ab*e to searc" on*y t"e ob/ect t"at created it& )n ot"er %ords, you cannot use t"e same searc" descriptor to searc" mu*tip*e documents& T"e searc" descriptor specifies t"e searc" te3t and "o% t"e te3t is searc"ed ,see Tab*e 13!.& T"e searc" descriptor is t"e most comp*icated component of searc"in$& 390 Table 134. 9roperties of the com.sun.star.util.*earch#escriptor service. Property Description Searc"+ac(%ards )f True, searc" t"e document bac(%ards& Searc"#aseSensitie )f True, t"e case of t"e *etters affects t"e searc"& Searc";ords )f True, on*y comp*ete %ords are found& Searc"Re$u*ar23pression )f True, t"e searc" strin$ is treated as a re$u*ar e3pression& Searc"Sty*es )f True, te3t is found based on app*ied sty*e namesLnot on t"e te3t content& Searc"Simi*arity )f True, a Dsimi*arity searc"F is performed& Searc"Simi*arityRe*a3 )f True, t"e properties Searc"Simi*arityRe*a3, Searc"Simi*arityRemoe, Searc"Simi*arityAdd, and Searc"Simi*arity23c"an$e are a** used& Searc"Simi*arityRemoe S"ort )nte$er specifyin$ "o% many c"aracters may be i$nored in a matc"& Searc"Simi*arityAdd S"ort )nte$er specifyin$ "o% many c"aracters may be added in a matc"& Searc"Simi*arity23c"an$e S"ort )nte$er specifyin$ "o% many c"aracters may be rep*aced in a matc"& A*t"ou$" not inc*uded in Tab*e 13!, a searc" descriptor supports t"e strin$ property Searc"Strin$, %"ic" represents t"e strin$ to searc"& T"e ISearc"Descriptor interface defines t"e met"ods $etSearc"Strin$,. and setSearc"Strin$,. to $et and set t"e property if you prefer to use a met"od rat"er t"an direct*y settin$ t"e property& T"e ISearc"ab*e interface defines t"e met"ods used for searc"in$ and creatin$ t"e searc" descriptor ,see Tab*e 13A.& Table 135. Methods defined by the com.sun.star.util.:*earchable interface. )et6od Description createSearc"Descriptor,. #reate a ne% Searc"Descriptor& findA**,ISearc"Descriptor. Return an Iinde3Access containin$ a** occurrences& find0irst,ISearc"Descriptor. Startin$ from t"e be$innin$ of t"e searc"ab*e ob/ect, return a te3t ran$e containin$ t"e first found te3t& find4e3t,ITe3tRan$e, ISearc"Descriptor. Startin$ from t"e proided te3t ran$e, return a te3t ran$e containin$ t"e first found te3t& T"e macro in Listin$ 3!M is ery simp*e7 it sets t"e #"ar;ei$"t c"aracter property of a** occurrences of t"e te3t D"e**oF to com&sun&start&a%t&0ont;ei$"t&+1LDLte3t ran$es support c"aracter and para$rap" properties& Listing 347. *et all occurrences of the word >helloA to bold te.t. Sub SetHello3oBold -i! o-e#criptor )3(e #earc( de#criptor -i! o"ound )3(e $ound rane o-e#criptor 6 3(i#Co!ponent&createSearc(-e#criptorBC Wit( o-e#criptor &Searc(Strin 6 "(ello" &Searc(Word# 6 true )3(e attribute# de$ault to "al#e &Searc(Ca#eSen#iti:e 6 "al#e )So #ettin one to "al#e i# redundant End Wit( 391 ) "ind t(e $ir#t one o"ound 6 3(i#Co!ponent&$ind"ir#tBo-e#criptorC -o W(ile Hot I#HullBo"oundC Print o"ound&etStrinBC o"ound&C(arWei(t 6 co!&#un&#tar&a*t&"ontWei(t&BO,- o"ound 6 3(i#Co!ponent&$indHextBo"ound&End= o-e#criptorC ,oop End Sub 1$...1. earching selected text or a specified range T"e tric( to searc"in$ a specified ran$e of te3t is to notice t"at you can use any te3t ran$e, inc*udin$ a te3t cursor, in t"e find4e3t routine& After eac" ca** to find4e3t,., c"ec( t"e end points of t"e find to see if t"e searc" %ent too far& 6ou may, t"erefore, constrain a searc" to any te3t ran$e& T"e primary purpose of t"e find0irst met"od is to obtain t"e initia* te3t ran$e for t"e find4e3t routine& 6ou can use t"e se*ected te3t frame%or( ery easi*y to searc" a ran$e of te3t& Listing 348. "terate through all occurrences of te.t between two cursors. Sub Searc(SelectedWor1erBo,Cur#or= oRCur#or= o3ext= o-e#criptorC I$ o3ext&co!pareReionEnd#Bo,Cur#or= oRCur#orC E6 7 3(en Exit Sub o,Cur#or&oRi(tB7= "al#eC -i! o"ound REM 3(ere i# no rea#on to per$or! a $ind"ir#t& o"ound 6 o-oc&$indHextBo,Cur#or= o-e#criptorC -o W(ile Hot I#HullBo"oundC REM See i$ *e #earc(ed pa#t t(e end I$ 9> 6 o3ext&co!pareReionEnd#Bo"ound= oRCur#orC 3(en Exit -o Print o"ound&etStrinBC o"ound 6 3(i#Co!ponent&$indHextBo"ound&End= o-e#criptorC ,oop End Sub T"e te3t ob/ect cannot compare t%o re$ions un*ess t"ey bot" be*on$ to t"at te3t ob/ect& Te3t t"at resides in a different frame, section, or een a te3t tab*e, uses a different te3t ob/ect t"an t"e main document te3t ob/ect& As an e3ercise, inesti$ate %"at "appens if t"e found te3t is in a different te3t ob/ect t"an t"e te3t ob/ect t"at contains oR#ursor in Listin$ 3!@& )s t"e code in Listin$ 3!@ robust> earching for all occurrences )t is si$nificant*y faster to searc" for a** occurrences of t"e te3t at one time usin$ t"e findA**,. ob/ect met"od t"an to repeated*y ca** find4e3t,.& #are must be used, "o%eer, %"en usin$ a** occurrences of t"e specified te3t& T"e macro in Listin$ 3!B is an e3treme e3amp*e of code $one bad on purpose& Listing 349. +ind and replace all occurrences of the word >hello.yzzyA. Sub Si!pleSearc(Hello/.88. -i! o-e#criptor )3(e #earc( de#criptor -i! o"ound )3(e $ound rane -i! o"oundAll )3(e $ound rane -i! nG )Jeneral index :ariable o-e#criptor 6 3(i#Co!ponent&createSearc(-e#criptorBC o-e#criptor&Searc(Strin 6 "(ellox.88." o"oundAll 6 3(i#Co!ponent&$indAllBo-e#criptorC 392 "or nG 6 7 to o"oundAll&etCountBC9> o"ound 6 o"oundAll&etB.IndexBnGC )Print o"ound&etStrinBC o"ound&#etStrinB"(ello" 4 nGC Hext End Sub T"e macro in Listin$ 3!B obtains a *ist of te3t ran$es t"at encapsu*ate t"e te3t D"e**o3yCCyF& T"is te3t is t"en rep*aced %it" a s"orter piece of te3t& )n a perfect %or*d, t"e occurrences of D"e**o3yCCyF %ou*d be rep*aced %it" D"e**o0F, D"e**o1F, D"e**o2F, &&& ;"en eac" instance is rep*aced %it" t"e s"orter te3t, t"e tota* *en$t" of t"e document c"an$es& Remember t"at t"e te3t9ran$e ob/ects %ere a** obtained before t"e first instance of te3t is modified& A*t"ou$" t"e te3t9ran$e interface is c*ear*y defined, t"e interna* %or(in$s are not& ) purpose*y created t"is e3amp*e because ) e3pected it to fai*, and %it" no defined be"aior my on*y option %as to create a test& 23perimenta**y, ) obsered t"at if mu*tip*e occurrences of D"e**o3yCCyF are contained in t"e same %ord, poor be"aior resu*ts& ) a*so obsered t"at if a** occurrences of D"e**o3yCCyF are contained in separate %ords, eeryt"in$ %or(s $reat, and on*y occurrences of D"e**o3yCCyF are c"an$edL*eain$ t"e surroundin$ te3t intact& ) can but nod my "ead in approa* at t"e bri**iance of t"e pro$rammers t"at a**o% t"is be"aior, %"i*e remainin$ cautious*y paranoid, e3pectin$ t"at code re*yin$ on t"is be"aior %i** fai* in t"e future& )nesti$atin$ t"e be"aior of t"e macro in Listin$ 3!B is more t"an simp*e academics& ) use a simi*ar macro re$u*ar*y in my o%n %ritin$& 0or arious reasons, t"e numberin$ used durin$ t"e creation of t"is boo( %as done manua**y rat"er t"an usin$ t"e bui*t9in numberin$ capabi*ities of 11oLin ot"er %ords, ) s"ou*d "ae read #"apter A of aming OpenOffice.org 'riter (.( by Kean Eo**is ;eber& Manua**y insertin$ numberin$ is a prob*em %"en a tab*e, fi$ure, or code *istin$ is de*eted, inserted, or moed& )n ot"er %ords, if ) de*ete t"e first tab*e in my document, a** of my tab*es %i** be numbered incorrect*y& ) created a macro t"at erifies t"at t"e items are se8uentia**y numbered startin$ %it" 1& #onsider tab*es, for e3amp*e& T"e tab*e captions use t"e para$rap" sty*e D=tab*e caption&F Tab*es are numbered usin$ t"e form DTab*e 122&F T"e macro in !isting /4( erifies t"at t"e captions are se8uentia**y numbered, and it renumbers t"em if re8uired& ;"en t"e te3t DTab*e WF is found in a para$rap" usin$ t"e D=tab*e captionF para$rap" sty*e, it is assumed to be identifyin$ a tab*e& T"e macro in Listin$ 36B renumbers t"ese based on t"eir occurrence in t"e document& 2ac" occurrence of DTab*e WF t"at is not in t"e D=tab*e captionF para$rap" sty*e is assumed to be a reference to a tab*e& 1$...2. earching and replacing 6ou can perform simp*e searc"in$ and rep*acin$ by searc"in$ and manua**y rep*acin$ eac" found occurrence %it" t"e rep*acement te3t& 11o a*so defines t"e IRep*aceab*e interface, %"ic" adds t"e abi*ity to rep*ace a** occurrences usin$ one met"od& 6ou must use an IRep*aceDescriptor rat"er t"an an ISearc"Descriptor, "o%eer& Rep*acin$ a** occurrences of te3t is ery simp*e ,see Listin$ 3A0.& TIP T"e IRep*aceab*e interface is deried from t"e ISearc"ab*e interface, and t"e IRep*aceDescriptor is deried from t"e ISearc"Descriptor interface& Listing 350. Replace >hello youA with >hello meA. o-e#criptor 6 o-oc&createReplace-e#criptorBC Wit( o-e#criptor &Searc(Strin 6 "(ello .ou" &ReplaceStrin 6 "(ello !e" End Wit( o-oc&ReplaceAllBo-e#criptorC 393 1$...#. )d'anced search and replace ;"i*e usin$ t"e 11o J5) for searc"in$ and rep*acin$, it is possib*e to searc" for and rep*ace attributes as %e** as te3t& An inspection of t"e searc"9and9rep*ace descriptors reea*s t"e ob/ect met"ods setSearc"Attributes,. and setRep*aceAttributes,.& ) discoered "o% to use t"ese ob/ect met"ods %"en ) found some code %ritten by A*e3 Saits(y, %"om ) do not (no%, and Laurent Jodard, %"om ) do& T"e macro in Listin$ 3A1 finds a** te3t t"at is in bo*d type, conerts t"e te3t to re$u*ar type, and t"en surrounds t"e te3t %it" t%o sets of cur*y brac(ets& T"e conersion of attributes to te3t ta$s is fre8uent*y done %"i*e conertin$ formatted te3t to re$u*ar AS#)) te3t %it" no specia* formattin$ capabi*ities& ;"i*e readin$ Listin$ 3A1, *oo( for t"e fo**o%in$ interestin$ tec"ni8ues: To search for all text that is bold regardless of the content, you must use a regular expression. In OOo, the period matches any single character and the asterisk means find zero or more occurrences of the previous character. Placed together, the regular expression .* matches any text. Regular expressions are required to find any text that is bold. While searching regular expressions, the ampersand character is replaced by the found text. In Listing 351, the replacement text {{ & }} causes the found text hello to become {{ hello }}. Text that is set to bold using an applied style is found only while searching character attributes if SearchStyles is set to True. If the SearchStyles attribute is set to False, only text that has been directly set to bold will be found. To search for text with specific attributes, create an array of structures of type PropertyValue. There should be one entry in the array for each attribute you want to search. Set the property name to the name of the attribute to search, and the property value to the value for which to search. Although this is complicated to describe using words, it is clearly shown in Listing 351. You can set attribute values by specifying the replacement attributes in the same way that you set the search attributes. Listing 351. Replace bold te.t. Sub Replace"or!attin REM oriinal code : Alex Sa:it#1. REM !odi$ied b. : ,aurent Jodard REM !odi$ied b. : Andre* Piton.a1 REM 3(e purpo#e o$ t(i# !acro i# to #urround all BO,- ele!ent# *it( RR TT REM and c(ane t(e Bold attribute to HORMA, b. u#in a reular expre##ion& -i! oReplace -i! Src(Attribute#B7C a# ne* co!&#un&#tar&bean#&Propert.Oalue -i! ReplAttribute#B7C a# ne* co!&#un&#tar&bean#&Propert.Oalue oReplace 6 3(i#Co!ponent&createReplace-e#criptorBC oReplace&Searc(Strin 6 "&*" )Reular expre##ion& Matc( an. text oReplace&ReplaceStrin 6 "RR 4 TT" )Hote t(e 4 place# t(e $ound text bac1 oReplace&Searc(ReularExpre##ion63rue )0#e reular expre##ion# oReplace&#earc(St.le#63rue )We *ant to #earc( #t.le# oReplace&#earc(All63rue )-o t(e entire docu!ent 394 REM 3(i# i# t(e attribute to $ind Src(Attribute#B7C&Ha!e 6 "C(arWei(t" Src(Attribute#B7C&Oalue 6co!&#un&#tar&a*t&"ontWei(t&BO,- REM 3(i# i# t(e attribute to replace it *it( ReplAttribute#B7C&Ha!e 6 "C(arWei(t" ReplAttribute#B7C&Oalue 6co!&#un&#tar&a*t&"ontWei(t&HORMA, REM Set t(e attribute# in t(e replace de#criptor oReplace&SetSearc(Attribute#BSrc(Attribute#BCC oReplace&SetReplaceAttribute#BReplAttribute#BCC REM Ho* do t(e *or1K 3(i#Co!ponent&replaceAllBoReplaceC End Sub Ta'le )/4 *ists t"e supported re$u*ar e3pression c"aracters& Table 136. *upported regular e.pression characters. C6aracter Description & A period represents any sin$*e c"aracter& T"e searc" term Zs"&rtZ finds bot" Ds"irtF and Ds"ortF& \ An asteris( represents any number of c"aracters& T"e searc" term Ds"\rtF finds Ds"rtF, Ds"irtF, Fs"iirtF, Ds"ioiba*da%pc*asdfa asdf asdfrtF and Ds"ortFLto name a fe% t"in$s t"at it can find& ^ A caret represents t"e be$innin$ of a para$rap"& T"e searc" term D^+obF on*y finds t"e %ord D+obF if it is at t"e be$innin$ of a para$rap"& T"e searc" term D^&F finds t"e first c"aracter in a para$rap"& Y A do**ar si$n represents t"e end of a para$rap"& T"e searc" term D+obYF on*y finds t"e %ord D+obF if it is at t"e end of a para$rap"& ^Y Searc" for an empty para$rap"& T"is is *isted "ere on*y because it is used so fre8uent*y& N A p*us si$n indicates t"at t"e precedin$ c"aracter must appear at *east once& T"e p*us si$n a*so %or(s %it" t"e %i*dcard c"aracter D&F& 0or e3amp*e, Dt&NsF finds a section of te3t t"at starts %it" a DtF and ends %it" an DsF& T"e *on$est possib*e te3t %it"in t"e para$rap" is a*%ays found& )n ot"er %ords, mu*tip*e %ords may be found, but t"e found te3t %i** a*%ays reside in t"e same para$rap"& > A 8uestion mar( mar(s t"e preious c"aracter as optiona*& 0or e3amp*e, you cou*d find %ords t"at inc*ude t"e c"aracters t"at come before t"e c"aracter t"at is in front of t"e DSF& 0or e3amp*e, Dbirds>F finds bot" DbirdF and DbirdsF& Sn T"e te3t DSnF "as t%o uses& ;"en searc"in$, t"is finds a "ard ro% brea( inserted %it" S"iftN2nter& )n t"e rep*ace fie*d, t"is represents a para$rap" brea(& 6ou can, t"erefore, rep*ace a** "ard brea(s %it" a para$rap" brea(& St T"e te3t DStF is used to find a tab& )n t"e rep*ace fie*d, t"is adds a tab& SR 5sin$ t"e te3t DSRF indicates t"at t"e precedin$ te3t must end a %ord& 0or e3amp*e, Dboo(SRF finds Dc"ec(boo(F but not Dboo(mar(F& S[ 5sin$ t"e te3t DS[F indicates t"at t"e fo**o%in$ te3t must end a %ord& 0or e3amp*e, DS[boo(F finds Dboo(mar(F but not Dc"ec(boo(F& 395 C6aracter Description S3IIII A bac(s*as" fo**o%ed by a *o%ercase 3 fo**o%ed by a four9di$it "e3adecima* number ,IIII. finds t"e c"aracter %"ose 5nicode ,AS#)). a*ue is t"e same as t"e four9di$it "e3adecima* number& S T"e bac(s*as" c"aracter fo**o%ed by anyt"in$ ot"er t"an DnF, DtF, DRF, D[F, or D3F is used to specify t"e c"aracter t"at fo**o%s& 0or e3amp*e, DSMF finds DMF& T"e primary purpose is to a**o% specia* %i*d c"aracters to be found& 0or e3amp*e, assume t"at ) %anted to find any c"aracter preceded by a DNF& ;e**, t"e DNF is a specia* c"aracter so ) need to precede it %it" a DSF& 5se D&SNF to find any c"aracter precedin$ a DNF c"aracter& Q T"e ampersand is used in t"e rep*ace te3t to add t"e found c"aracters& )n Listin$ 3A1, t"e ampersand is used to surround a** bo*d te3t %it" D``D and DbbF& cabc123d Matc" any c"aracter t"at is bet%een s8uare brac(ets& 0or e3amp*e, Dtce3dNtF finds Dte3tF, DteetF, and Dt3eeetF7 to name a fe% e3amp*es of %"at it finds& ca9ed T"e minus si$n is used to define a ran$e %"en used inside of s8uare brac(ets& 0or e3amp*e, Dca9edF matc"es c"aracters bet%een DaF and DeF and Dca9e39CdF matc"es c"aracters bet%een DaF and DeF or D3F and DCF& c^a9ed '*acin$ a caret symbo* inside s8uare brac(ets %i** find anyt"in$ but t"e specified c"aracters& 0or e3amp*e, Dc^a9edF finds any c"aracter t"at is not bet%een DaF and DeF& a '*acin$ a ertica* bar bet%een t%o searc" strin$s %i** matc" %"at is before and a*so matc" %"at is after& 0or e3amp*e, Dboba/eanF matc"es t"e strin$ DbobF and a*so matc"es t"e strin$ D/eanF& `2b '*acin$ a number bet%een cur*y brac(ets finds t"at many occurrences of t"e preious c"aracter& 0or e3amp*e, Dme`2btF matc"es DmeetF, and Dc09Bd`3bF matc"es any t"ree9di$it number& 4ote t"at Dc09Bd`3bF %i** a*so find t"e first t"ree di$its of a number %it" more t"an t"ree di$its, un*ess Dfind %"o*e %ordsF is a*so specified& `1,2b '*acin$ t%o numbers separated by a comma bet%een cur*y brac(ets finds t"e precedin$ c"aracter a ariab*e number of times& 0or e3amp*e, Dc09Bd`1,!bF finds any number t"at contains bet%een one and four di$its& , . Te3t p*aced %it"in parent"eses is treated as a reference& T"e te3t DS1F finds t"e first reference, DS2F finds t"e second reference, and so on& 0or e3amp*e, D,c09Bd`3b.9c09Bd `2b9S1F finds D1239!A9123F but not D1239!A96M@F& 'arent"eses can a*so be used for $roupin$& 0or e3amp*e, D,"eas"eame.YF finds any para$rap" t"at ends %it" D"eF, Ds"eF, or DmeF& c:di$it:d 0inds a sin$*e9di$it number& 0or e3amp*e, Dc:di$it:d>F finds a sin$*e9di$it number and Dc:di$it:dNF finds any number %it" one or more di$its& c:space:d 0inds any %"ite space, suc" as spaces and tabs& c:print:d 0inds any printab*e c"aracters& c:cntr*:d 0inds any non9printin$ c"aracters& c:a*num:d 0inds any a*p"anumeric c"aracters ,numbers and te3t c"aracters.& c:a*p"a:d 0inds any a*p"abetic c"aracters, bot" uppercase and *o%ercase& c:*o%er:d 0inds any *o%ercase c"aracters if DMatc" caseF is se*ected in t"e 1ptions area& c:upper:d 0inds any uppercase c"aracters if DMatc" caseF is se*ected in t"e 1ptions area& 396 14.$. 0e:t content T"e primary purpose of a ;riter document is to contain simp*e te3t& T"e te3t is stored and enumerated by para$rap"s& ;"en a para$rap" enumerates content, eac" enumerated section uses t"e same set of properties& )n $enera*, te3t content must be created by t"e document t"at %i** contain t"e content& After creation, t"e te3t content is inserted into t"e document at a specified *ocation& 'ara$rap"s, "o%eer, are not specifica**y created and t"en inserted ,see Listin$ 316 near t"e be$innin$ of t"is c"apter.& 'ara$rap" te3t is inserted as a strin$ and ne% para$rap"s are inserted as contro* c"aracters ,see Tab*e 123.& More comp*icated te3t content is typica**y added usin$ t"e insertTe3t#ontent,. ob/ect met"od ,see Listin$ 31M.& T"ere are ot"er, *ess9used met"ods to insert te3t contentLfor e3amp*e, pastin$ content from t"e c*ipboard ,see Listin$ 363 *ater in t"is c"apter. and insertin$ an entire document ,see Listin$ 3A2.& Listing 352. "nsert a document at a te.t cursor. oCur#or&in#ert-ocu!ent"ro!0R,B#"ile0R,= Arra.BCC Most te3t content is named and accessib*e in a simi*ar %ay ,see Ta'le )/0.& T"e most popu*ar content type in Tab*e 13M is undoubted*y te3t tab*es& Table 137. /ontent contained in a te.t document. Content Type )ec6anism $ccess )et6od 0ootnotes )nde3 Access $et0ootnotes,. 2ndnotes )nde3 Access $et2ndnotes,. Reference mar(s 4amed Access $etReferenceMar(s,. Jrap"ic ob/ects 4amed Access $etJrap"ic1b/ects,. 2mbedded ob/ects 4amed Access $et2mbedded1b/ects,. Te3t tab*es 4amed Access $etTab*es,. +oo(mar(s 4amed Access $et+oo(mar(s,. Sty*e fami*ies 4amed Access $etSty*e0ami*ies,. Document inde3es )nde3 Access $etDocument)nde3es,. Te3t fie*ds 2numeration Access $etTe3t0ie*ds,. Te3t fie*d masters 4amed Access $etTe3t0ie*dMasters,. Te3t frames 4amed Access $etTe3t0rames,. Te3t sections 4amed Access $etTe3tSections,. TIP #ontent accessib*e usin$ named access a*so proides inde3ed access& 14.&. 0e:t tables ;riter documents act as a te3t9tab*es supp*ier, so you can direct*y retriee te3t tab*es from ;riter documents& A*t"ou$" te3t tab*es are enumerated as te3t content a*on$ %it" para$rap"s ,see Listin$ 31B., tab*es are more typica**y obtained by name or by inde3 ,see !isting /5/ and +igure (/.& Listing 353. #emonstrate enumerating te.t tables. Sub Enu!rateAll3ext3able# 397 -i! o3able# )All o$ t(e text table# -i! #F )Wor1 #trin -i! iG )Index :ariable
# 6 # 4 CHRFB>7C 4 CHRFB>7C 4 "3ext 3able# B. Ha!e" 4 CHRFB>7C # 6 # 4 MoinBo3able#&etEle!entHa!e#BC= CHRFB>7CC M#Box #= 7= "3able#" End Sub Figure 93. ables contained in a document) by inde. and named access. TIP Most named te3t content is retrieed, created, inserted, and disposed of in t"e same %ay& Learn to do t"is usin$ tab*es and youG** be ready to use ot"er named te3t contentLboo(mar(s, for e3amp*e& As %it" most te3t content, tab*es must be created by t"e document before t"ey are inserted into t"e document& T"e macro in Listin$ 3A! inserts a tab*e named DSamp*eTab*eF if it does not e3ist, and remoes it if it does& Listing 354. "nsert then delete a te.t table. Sub In#ert-elete3able -i! o3able )He*l. created table to in#ert -i! o3able# )All o$ t(e text table# -i! oIn#ertPoint )W(ere t(e table *ill be in#erted -i! #3ableHa!e a# Strin
REM Alt(ou( t(i# #ee!# li1e t(e correct *a. to re!o:e text content= REM *(at i$ t(e table i# not in#erted into t(e pri!ar. docu!ent)# REM text obNectU o3able&di#po#eBC !a. be #a$er to u#e& 398 3(i#Co!ponent&3ext&re!o:e3extContentBo3ableC El#e REM ,et t(e docu!ent create t(e text table& o3able 6 3(i#Co!ponent&createIn#tanceB "co!&#un&#tar&text&3ext3able" C o3able&initiali8eB'= %C )3*o ro*#= t(ree colu!n#
REM I$ t(ere i# a boo1!ar1 na!ed "In#ert3ableHere"= t(en in#ert REM t(e table at t(at point& I$ t(i# boo1!ar1 doe# not exi#t= REM t(en #i!pl. c(oo#e t(e :er. end o$ t(e docu!ent& 399 I$ 3(i#Co!ponent&etBoo1!ar1#BC&(a#B.Ha!eB"In#ert3ableHere"C 3(en oIn#ertPoint 65 3(i#Co!ponent&etBoo1!ar1#BC&etB.Ha!eB"In#ert3ableHere"C&etAnc(orBC El#e oIn#ertPoint 6 3(i#Co!ponent&3ext&etEndBC End I$
REM Ho* in#ert t(e text table at t(e end o$ t(e docu!ent& REM Hote t(at t(e text obNect $ro! t(e oIn#ertPoint text REM rane i# u#ed rat(er t(an t(e docu!ent text obNect& oIn#ertPoint&et3extBC&in#ert3extContentBoIn#ertPoint = o3able= "al#eC
REM 3(e #et-ataBC obNect !et(od *or1# OH,P *it( nu!erical data& REM 3(e #et-ataArra.BC obNect !et(od= (o*e:er= al#o allo*# #trin#& o3able&#et-ataArra.BArra.BArra.B7= "One"= 'C= Arra.B%= ""our"= <CCC o3able&#etHa!eB#3ableHa!eC End I$ End Sub TIP )n $enera*, it is better to set tab*e properties before insertin$ t"e tab*e into t"e document& T"is preents screen f*ic(er as t"e ob/ect is modified and t"en redra%n on t"e screen& Due to a bu$ in 11o 1&1&0, if Listin$ 3A! is modified to set t"e data before insertin$ t"e tab*e, t"e tab*e name is modified and it contains an e3tra $arba$e c"aracter at t"e end& +e %arned, "o%eer, t"at some te3t content, suc" as te3t fie*d masters, cannot c"an$e t"eir names after t"ey "ae been inserted into a document& T"e macro in Listin$ 3A! demonstrates many usefu* tec"ni8ues: A named text content is found and obtained. Notice that finding the table and the bookmark are very similar processes. A bookmark is used. A text table is created, initialized, and inserted at a location marked by a bookmark. Text content is deleted. A table is initialized with data. The table name is set. 1$.0.1. 9sing the correct text ob4ect )t is ery important t"at you use t"e correct te3t ob/ect& )t is possib*e t"at t"e te3t ob/ect in a te3t section or tab*e ce** is not t"e same as t"e te3t ob/ect returned by t"e document& 2ac" te3t ran$e is associated %it" a specific te3t ob/ect& Attemptin$ to use ob/ect met"ods from one te3t ob/ect to operate on a te3t ran$e associated %it" a different te3t ob/ect causes an error& )n Listin$ 3A!, a tab*e is remoed, %it" t"e sin$*e *ine s"o%n in !isting /55& Listing 355. 'hat if the table is not contained in the documentSs te.t ob%ectU 3(i#Co!ponent&3ext&re!o:e3extContentBo3ableC T"e code in Listin$ 3AA assumes t"at t"e tab*e is contained in t"e documentGs te3t ob/ect& )f t"e tab*e is not contained in t"e primary documentGs te3t ob/ect, t"e code in Listin$ 3AA %i** fai*& A*t"ou$" Listin$ 3AA %i** rare*y fai*, it %i** undoubted*y fai* at t"e %orst possib*e time& T"e macro %or(s because t"e samp*e 400 document %as desi$ned so t"at t"e tab*e is inserted into t"e primary documentGs te3t ob/ect& 2it"er so*ution s"o%n in Listin$ 3A6 may be a better so*ution for de*etin$ t"e tab*e& Listing 356. wo safe methods to delete the table. o3able&etAnc(orBC&et3extBC&re!o:e3extContentBo3ableC o3able&di#po#eBC T"e second time t"at a te3t ob/ect is used in Listin$ 3A!, it is obtained from t"e anc"or returned from a boo(mar(Lt"is is safe& Listing 357. - safe way to get a te.t ob%ect. oIn#ertPoint&et3extBC&in#ert3extContentBoIn#ertPoint = o3able= "al#eC )f t"e te3t ran$e o)nsert'oint is not contained in t"e documentGs te3t ob/ect, attemptin$ to insert t"e tab*e usin$ t"e documentGs te3t ob/ect %i** fai*& 1n*y you can decide "o% carefu* you need to be %"en accessin$ te3t ob/ects& #onsider t"e se*ected te3t frame%or(& ;"at te3t ob/ect is used to create te3t cursors and to compare te3t cursors> #an you ma(e t"e code more robust> 1$.0.2. Methods and properties T"e met"ods supported by te3t tab*es are ery simi*ar to t"e met"ods supported by spreads"eets contained in #a*c documents ,see #"apter 1!, D#a*c DocumentsF.& Tab*e 13@ summariCes t"e ob/ect met"ods supported by te3t tab*es& Table 138. Ob%ect methods supported by te.t tables. )et6od Description auto0ormat,name. App*y t"e specified auto9format name to t"e tab*e& create#ursor+y#e**4ame,name. ITe3tTab*e#ursor positioned at t"e specified ce**& createSortDescriptor,. Array of 'ropertyOa*ues t"at specify t"e sort criteria& dispose,. Destroy a te3t ob/ect, %"ic" a*so remoes it from t"e document& $etAnc"or,. Return a te3t ran$e identifyin$ %"ere t"e tab*e is anc"ored& T"is met"od a**o%s te3t content to be added easi*y before or after a te3t tab*e& $et#e**+y4ame,name. Return an I#e** based on t"e ce** name, suc" as D+3F& $et#e**+y'osition,co*, ro%. 4umberin$ starts at Cero& T"is "as difficu*ties %it" comp*e3 tab*es& $et#e**4ames,. Strin$ array of ce** names contained in t"e tab*e& $et#e**Ran$e+y4ame,name. I#e**Ran$e based on ce** name, suc" as A1:+!& 0ai*s if t"e name identifies a ce** t"at "as been sp*it& $et#e**Ran$e+y'osition,*eft, top, ri$"t, bottom. I#e**Ran$e based on numeric ran$e& $et#o*umnDescriptions,. Array of strin$s describin$ t"e co*umns& 0ai*s for comp*e3 tab*es& $et#o*umns,. ITab*e#o*umns ob/ect enumerates co*umns by inde3& A*so supports insert+y)nde3,id3, count. and remoe+y)nde3,id3, count.& $etData,. Jet numerica* data as a nested se8uence of a*ues ,arrays in an array.& 0ai*s for comp*e3 tab*es& $etDataArray,. Same as $etData,. but may contain Strin$ or Doub*e& $et4ame,. Jet t"e tab*e name as a strin$& 401 )et6od Description $etRo%Descriptions,. Array of strin$s describin$ t"e ro%s& 0ai*s for comp*e3 tab*es& $etRo%s,. ITab*eRo%s ob/ect enumerates ro%s by inde3& A*so supports insert+y)nde3,id3, count. and remoe+y)nde3,id3, count.& initia*iCe,ro%s, co*s. Set t"e numbers of ro%s and co*umns& Must be done before t"e tab*e is inserted ,see Listin$ 31M.& set#o*umnDescriptions,strin$,.. Set t"e co*umn descriptions from an array of strin$s& setData,Doub*e,.. Set numerica* data as a nested se8uence of a*ues& 0ai*s for comp*e3 tab*es& setDataArray,array,.. Same as setData,. but may contain Strin$ or Doub*e& set4ame,name. Set t"e tab*e name& setRo%Descriptions,strin$,.. Set t"e ro% descriptions from an array of strin$s& sort,array,.. Sort t"e tab*e based on a sort descriptor& Te3t tab*e ob/ects a*so support a ariety of properties ,see Tab*e 13B.& Te3t tab*es support many of t"e same properties t"at are supported by para$rap"s ,see Tab*e 126.& Table 139. 9roperties supported by the com.sun.star.te.t.e.table service. Property Description +rea(Type Specify t"e type of brea( t"at is app*ied at t"e start of t"e tab*e ,see t"e +rea(Type attribute in Tab*e 126.& LeftMar$in Specify t"e *eft tab*e mar$in in 0&01 mm as a Lon$ )nte$er& Set t"e Eori1rient property to somet"in$ ot"er t"an 05LL& Ri$"tMar$in Specify t"e ri$"t tab*e mar$in in 0&01 mm as a Lon$ )nte$er& Set t"e Eori1rient property to somet"in$ ot"er t"an 05LL& Eori1rient Specify t"e "oriConta* orientation usin$ t"e com&sun&star&te3t&Eori1rientation constants& T"e defau*t a*ue is com&sun&star&te3t&Eori1rientation&05LL& 4142 ? 0 H 4o a*i$nment is app*ied& R)JET ? 1 H T"e ob/ect is a*i$ned at t"e ri$"t side& #24T2R ? 2 H T"e ob/ect is a*i$ned at t"e midd*e& L20T ? 3 H T"e ob/ect is a*i$ned at t"e *eft side& )4S)D2 ? ! H ,4ot yet supported. 15TS)D2 ? A H ,4ot yet supported. 05LL ? 6 H T"e ob/ect uses t"e fu** space ,for te3t tab*es on*y.& L20T=A4D=;)DTE ? M H T"e *eft offset and t"e %idt" of t"e ob/ect are defined& <eepTo$et"er )f True, preents pa$e or co*umn brea(s bet%een t"is tab*e and t"e fo**o%in$ para$rap" or te3t tab*e& Sp*it )f 0a*se, t"e tab*e %i** not sp*it across t%o pa$es& 'a$eDesc4ame )f t"is strin$ is set, a pa$e brea( occurs before t"e para$rap", and t"e ne% pa$e uses t"e $ien pa$e sty*e name ,see 'a$eDesc4ame in Tab*e 126.& 'a$e4umber1ffset )f a pa$e brea( occurs, specify a ne% pa$e number ,see 'a$e4umber1ffset in Tab*e 126.& Re*atie;idt" Specify t"e %idt" of t"e tab*e re*atie to its enironment as a S"ort )nte$er& )s;idt"Re*atie )f True, t"e re*atie %idt" is a*id& 402 Property Description RepeatEead*ine )f True, t"e first ro% of t"e tab*e is repeated on eery ne% pa$e& S"ado%0ormat Specify t"e type, co*or, and siCe of t"e s"ado% ,see 'araS"ado%0ormat in Tab*e 126.& TopMar$in Specify t"e top tab*e mar$in in 0&01 mm as a Lon$ )nte$er& +ottomMar$in Specify t"e bottom tab*e mar$in in 0&01 mm as a Lon$ )nte$er& +ac(Transparent )f True, t"e bac($round co*or is transparent& ;idt" Specify t"e abso*ute tab*e %idt" as a Lon$ )nte$erLt"is is a read9on*y property& #"artRo%AsLabe* )f True, t"e first ro% is treated as a3is *abe*s if a c"art is created& #"art#o*umnAsLabe* )f True, t"e first co*umn is treated as a3is *abe*s if a c"art is created& Tab*e+order Specify t"e tab*e borders in a com&sun&star&tab*e&Tab*e+order structure& T"e structure contains numerous comp*icated properties: T"e properties TopLine, +ottomLine, LeftLine, Ri$"tLine, EoriConta*Line, and Oeritica*Line are a** structures of type +orderLine as described by t"e Left+order property in Tab*e 126& T"e Distance property contains t"e distance bet%een t"e *ines and ot"er contents& 6ou can turn eac" border property on or off by settin$ one of t"e fo**o%in$ properties to True or 0a*se: )sTopLineOa*id, )s+ottomLineOa*id, )sLeftLineOa*id, )sRi$"tLineOa*id, )sEoriConta*LineOa*id, )sOertica*LineOa*id, and )sDistanceOa*id& Tab*e#o*umnSeparators Specify t"e %idt" of eac" co*umn %it" an array of tab*e co*umn separators& 2ac" separator is a com&sun&star&te3t&Tab*e#o*umnSeparator structure& 'osition is a S"ort )nte$er t"at defines t"e position of a ce** separator& )sOisib*e determines if t"e separator is isib*e& T"e %idt" of a ce** is defined by t"e position of t"e separator bet%een ad/acent ce**s& ;"en t%o ce**s are mer$ed, t"e separator is "idden, not remoed& T"e 'osition a*ues are re*atie to t"e te3t tab*e Tab*e#o*umnRe*atieSum property& T"is property is a*id for a tab*e on*y if eery ro% "as t"e same structure& )f t"ey do not, obtain t"e separators from t"e indiidua* ro% ob/ects& Tab*e#o*umnRe*atieSum Specify t"e sum of t"e co*umn9%idt" a*ues used in Tab*e#o*umnSeparators as a S"ort )nte$er& +ac(#o*or Specify t"e para$rap" bac($round co*or as a Lon$ )nte$er& +ac(Jrap"ic5RL Specify t"e 5RL of t"e para$rap" bac($round $rap"ic& +ac(Jrap"ic0i*ter Specify t"e name of t"e $rap"ic fi*ter for t"e para$rap" bac($round $rap"ic& +ac(Jrap"icLocation Specify t"e position of a bac($round $rap"ic ,see 'ara+ac(Jrap"icLocation in Tab*e 126.& 1$.0.#. imple and complex tables Simp*y spea(in$, a te3t tab*e is a set of ro%s and co*umns of te3t& A** of t"e tab*es in t"is boo( are represented usin$ simp*e te3t tab*es& 11o supports bot" simp*e and comp*e3 tab*es& As t"eir name imp*ies, in simp*e tab*es t"e tab*e ce**s are *aid out in a simp*e $rid ,see Ta'le )6*.& 2ac" co*umn is *abe*ed a*p"abetica**y startin$ %it" t"e *etter A, and eac" ro% is *abe*ed numerica**y startin$ %it" t"e number 1& T"e ob/ect met"od $et#e**+y4ame,. uses t"is name to return t"e specified ce**& A simi*ar ob/ect met"od, 403 $et#e**+y'osition,., returns t"e ce** based on t"e co*umn and ro% number& T"e co*umn and ro% number are Cero9based numbers, so re8uestin$ ,1, 2. returns t"e ce** named D+3F& Table 140. Rows are labeled numericallyE columns are labeled alphabetically. A1 B1 C1 A2 B2 C2 A3 B3 C3 11o supports more t"an /ust simp*e te3t tab*es& A te3t tab*e contains ro%s, ro%s contain one or more ce**s ,co*umns., and ce**s contain eit"er te3t content or ro%s& )n ot"er %ords, ad/acent ce**s may be mer$ed, and indiidua* ce**s may be mer$ed eit"er "oriConta**y or ertica**y& T"e namin$ conention for comp*e3 tab*es is more comp*icated t"an for simp*e tab*es ,see Tab*e 1!1.& )n Tab*e 1!1, t"e ce** named +2 %as sp*it "oriConta**y& T"e ne% name is a concatenation of t"e former ce** name ,+2. and t"e number of t"e ne% co*umn and ro% inde3 inside t"e ori$ina* tab*e ce**, separated by dots& Table 141. 'hen a row or column is split or merged) cell names become more complicated. A1 B1 C1 D1 A2 B2.1.1 B2.1.2 C2 D2 A3 B3 C3 D3 E3 A4 B4 C4 TIP 4ot a** ob/ect met"ods %or( %it" comp*e3 tab*es& 0or e3amp*e, t"e ob/ect met"ods $etData,. and setData,. cause an e3ception for comp*e3 tab*es, %"ic" ma(es sense& A*t"ou$" t"e ob/ect met"od $et#e**+y4ame,. %or(s as e3pected for comp*e3 tab*es, $et#e**+y'osition,. is not ab*e to return a** of t"e ce**s because it a**o%s on*y a co*umn and a ro% number& 5se t"e $et#e**4ames,. ob/ect met"od to return t"e names of t"e ce**s in a tab*e ,see Listin$ 3A@.7 you can t"en use t"e ce** names to indiidua**y obtain eac" ce** in t"e tab*e& Listing 358. Hoin the array of strings to print the cell names in a table. M#Box MoinBo3able&etCellHa!e#BC= ""C 1$.0.$. Tables contain cells T"e ce**s in a te3t tab*e are ery ersati*e ob/ects capab*e of "o*din$ a** types of data& T"e ce** ob/ects imp*ement bot" t"e ITe3t interface ,see Tab*e 123 near t"e be$innin$ of t"is c"apter. as %e** as t"e I#e** interface ,see Tab*e 1!2.& TIP Tab*es are ab*e to create a te3t tab*e cursor %it" met"ods and properties specifica**y desi$ned to traerse and se*ect ce**s, and eac" indiidua* ce** is ab*e to produce a te3t cursor t"at is *oca* to t"e ce** te3t ob/ect& 404 Table 142. Methods defined by the com.sun.star.table.:/ell interface. )et6od Description $et0ormu*a,. T"e ori$ina* strin$ typed into t"e ce**, een if it is not a formu*a& set0ormu*a,Strin$. Set t"e ce**Gs formu*a& 5se setStrin$,. from t"e ITe3t interface to set te3t& $etOa*ue,. 0*oatin$9point ,Doub*e. a*ue of t"e ce**& setOa*ue,Doub*e. Set t"e f*oatin$9point a*ue of t"e ce**& $etType,. Return a com&sun&star&tab*e&#e**#ontentType enumeration %it" a*id a*ues of 2M'T6, OAL52, T2IT, and 01RM5LA& $et2rror,. Lon$ )nte$er error a*ue& )f t"e ce** is not a formu*a, t"e error a*ue is Cero& 2ac" ce** ob/ect posses numerous properties& T"ese properties are $enera**y fami*iar because t"ey are used in ot"er ob/ects& 0or e3amp*e, t"e +ac(#o*or, +ac(Jrap"ic0i*ter, +ac(Jrap"icLocation, +ac(Jrap"ic5RL, +ac(Transparent, +orderDistance, +ottom+order, +ottom+orderDistance, Left+order, Left+orderDistance, Ri$"t+order, Ri$"t+orderDistance, Top+order, and Top+orderDistance properties are defined for te3t tab*es in Tab*e 13B and-or para$rap" properties in Tab*e 126& 1ne of t"e more usefu* properties t"at is aai*ab*e on*y in t"e ce** ob/ect, "o%eer, is #e**4ame& T"is is usefu* to determine t"e *ocation of t"e current cursor& T"e macro in Listin$ 3AB demonstrates a fe% ne% manipu*ations for tab*es& The text tables, rows, columns, and cells all support the BackColor property. Listing 359 sets the background color of the first row to a light gray, which is commonly used to mark headings. The insertByIndex(index, num) object method is used to insert new rows at the end of a table. Rows can also be inserted into the middle or at the start of a table. Individual cells are retrieved by name; both numeric values and strings are set. Notice that strings are set using setString() rather than setFormula(). TIP A*t"ou$" t"e ;eb9based 11o documentation ma(es no distinction bet%een ce**s contained in te3t tab*es and ce**s contained in spreads"eets, t"e t%o ce** types do not support t"e same property set& 0or e3amp*e, t"e #e**Sty*e, #e**+ac(#o*or, and RotateAn$*e properties are not supported& Listing 359. *imple te.t table manipulations. Sub Si!ple3ableManipulation# -i! o3able )He*l. created table to in#ert -i! o3able# )All o$ t(e text table# -i! oIn#ertPoint )W(ere t(e table *ill be in#erted -i! #3ableHa!e a# Strin
#3ableHa!e 6 "Sa!ple3able" o3able# 6 3(i#Co!ponent&3ext3able# REM Re!o:e t(e table i$ it exi#t#K I$ o3able#&(a#B.Ha!eB#3ableHa!eC 3(en 3(i#Co!ponent&3ext&re!o:e3extContentBo3able#&etB.Ha!eB#3ableHa!eCC End I$ REM ,et t(e docu!ent create t(e text table& 405 o3able 6 3(i#Co!ponent&createIn#tanceB "co!&#un&#tar&text&3ext3able" C o3able&initiali8eB?= %C )3*o ro*#= t(ree colu!n# REM I$ t(ere i# a boo1!ar1 na!ed "In#ert3ableHere"= t(en in#ert REM t(e table at t(at point& I$ t(i# boo1!ar1 doe# not exi#t= REM t(en #i!pl. c(oo#e t(e :er. end o$ t(e docu!ent& I$ 3(i#Co!ponent&etBoo1!ar1#BC&(a#B.Ha!eB"In#ert3ableHere"C 3(en oIn#ertPoint 65 3(i#Co!ponent&etBoo1!ar1#BC&etB.Ha!eB"In#ert3ableHere"C&etAnc(orBC El#e oIn#ertPoint 6 3(i#Co!ponent&3ext&etEndBC End I$
o3able&#et-ataArra.BArra.BArra.B"Ha!e"= "Score"= "3e#t"C=5 Arra.B"Bob"= Q7= "CCW"C= Arra.B"And."= Q7= "CCW"C=5 Arra.B"Mean"= >77= "CCI"CCC o3able&#etHa!eB#3ableHa!eC REM Set t(e $ir#t ro* to (a:e a ra. bac1round& o3able&etRo*#BC&etB.IndexB7C&Bac1Color 6 RJBB'%<= '%<= '%<C REM re!o:eB.Index u#e# t(e #a!e aru!ent# a# in#ertB.Index= na!el. REM t(e index at *(ic( to in#ert or re!o:e $ollo*ed b. t(e nu!ber REM o$ ro*# to in#ert or re!o:e& 3(e $ollo*in line in#ert# REM one ro* at index ?& o3able&etRo*#BC&in#ertB.IndexB?= >C
REM Obtain t(e indi:idual cell# and #et t(e :alue#& o3able&etCellB.Ha!eB"A<"C&#etStrinB"W(il"C o3able&etCellB.Ha!eB"B<"C&#etOalueB>77C o3able&etCellB.Ha!eB"C<"C&#etStrinB"Ad:anced"C End Sub 1$.0.,. 9sing a table cursor A*t"ou$" te3t tab*e cursors imp*ement met"ods specific to traersin$ te3t tab*es, t"ey are not si$nificant*y different from t"eir te3t cursor counterparts in $enera* functiona*ity& 6ou can se*ect and manipu*ate ran$es of ce**s, and set ce** properties& TIP 6ou cannot obtain a te3t tab*e from t"e document and t"en simp*y insert it a$ain at anot"er *ocation& So, "o% do you copy a te3t tab*e> See Listin$ 363& Li(e te3t cursors, te3t tab*e cursor moement met"ods accept a +oo*ean ar$ument t"at indicates if t"e current se*ection s"ou*d be e3panded ,True. or if t"e cursor s"ou*d simp*y be moed ,0a*se.& T"e moement met"ods a*so return a +oo*ean a*ue indicatin$ if t"e moement %as successfu*& Tab*e 1!3 contains t"e met"ods defined by t"e ITe3tTab*e#ursor interface& 406 Table 143. Methods defined by the com.sun.star.te.t.:e.table/ursor interface. )et6od Description $etRan$e4ame,. Return t"e ce** ran$e se*ected by t"is cursor as a strin$& 0or e3amp*e, D+3:DAF& $oto#e**+y4ame,Strin$, boo*ean. Moe t"e cursor to t"e ce** %it" t"e specified name7 return +oo*ean& $oLeft,n, boo*ean. Moe t"e cursor *eft n ce**s7 return +oo*ean& $oRi$"t,n, boo*ean. Moe t"e cursor ri$"t n ce**s7 return +oo*ean& $o5p,n, boo*ean. Moe t"e cursor up n ce**s7 return +oo*ean& $oDo%n,n, boo*ean. Moe t"e cursor do%n n ce**s7 return +oo*ean& $otoStart,boo*ean. Moe t"e cursor to t"e top *eft ce**& $oto2nd,boo*ean. Moe t"e cursor to t"e bottom ri$"t ce**& mer$eRan$e,. Mer$e t"e se*ected ran$e of ce**s7 return True for success& sp*itRan$e,n, boo*ean. #reate n ,an inte$er. ne% ce**s in eac" ce** se*ected by t"e cursor& 0or t"e +oo*ean, specify True to sp*it "oriConta**y, 0a*se for ertica**y& Returns True on success& Te3t tab*e cursors are used to sp*it and mer$e tab*e ce**s& )n $enera*, ) consider t"is to be t"e primary use of a te3t tab*e cursor& 6ou can use te3t tab*e cursors to moe around t"e tab*e by usin$ t"e met"ods in Tab*e 1!3& T"e macro in Listin$ 360 obtains t"e tab*e ce** names, creates a ce** cursor t"at contains t"e first tab*e ce**, and t"en moes t"e cursor to t"e *ast ce** in t"e tab*e& A ce** ran$e is created based on t"e ran$e name, and t"en t"e entire tab*e is se*ected by t"e current contro**er& Listing 360. *elect an entire table using a cursor. his may fail for a comple. table. oCellHa!e# 6 o3able&etCellHa!e#BC oCur#or 6 o3able&createCur#orB.CellHa!eBoCellHa!e#B7CC oCur#or&otoCellB.Ha!eBoCellHa!e#B0BoundBoCellHa!e#BCCC= 3rueC oRane 6 o3able&etCellRaneB.Ha!eBoCur#or&etRaneHa!eBCC )3(i# !a. $ailK 3(i#co!ponent&etCurrentController&#electBoRaneC Listin$ 360 demonstrates "o% to se*ect a** ce**s in a tab*e by usin$ a tab*e ce** cursor& 6ou can t"en manipu*ate t"e entire tab*e usin$ t"e cursor& )t may fai*, "o%eer, in se*ectin$ t"e entire tab*e in t"e current ie%& Tab*e ce** cursors "ae no prob*ems %it" comp*e3 tab*es& T"e ob/ect met"ods supported by tab*es, "o%eer, do not a** support comp*e3 tab*es& A notab*e e3amp*e is t"e ob/ect met"od $et#e**Ran$e+y4ame,., as used in Listin$ 360& T"is is ery unfortunate because t"e ie% cursor is ab*e to se*ect te3t based on a ce** ran$e, but t"e tab*e cannot return a ce** ran$e t"at "as a sp*it ce** as one of t"e endpoints& 0or e3amp*e, t"e ce** ran$e A1&2&1:#! fai*s& T"ere is no easy met"od to dup*icate an entire te3t tab*e, eit"er %it"in a document or bet%een documents ,at *east not as of 11o ersion 1&1&0 >>.& T"e $enera* so*ution for suc" prob*ems is to use t"e c*ipboard& 0irst, use t"e ie% cursor or current contro**er to se*ect t"e ob/ect t"at you %ant to copy& T"en use a dispatc"er to copy t"e ob/ect to t"e c*ipboard, moe t"e ie% cursor %"ere t"e ob/ect s"ou*d be p*aced, and t"en use a dispatc"er to paste t"e ob/ect from t"e c*ipboard& As you may "ae $uessed, t"e difficu*t part in t"is process is se*ectin$ t"e tab*e %it" t"e ie% cursor& A*t"ou$" numerous peop*e "ae tried and fai*ed to so*e t"is prob*em, a bri**iant so*ution %as proided by 'ao*o Mantoani, a contributor on t"e 11o mai*in$ *ists& 'ao*o starts by notin$ t"at se*ectin$ an entire tab*e %it" t"e current contro**er p*aces t"e ie% cursor at t"e start of t"e first ce** ,see Listin$ 361.& 407 Listing 361. 9lace the cursor at the start of the first cell in the table. 3(i#Co!ponent&CurrentController&#electBo3ableC A*t"ou$" Listin$ 361 does not entire*y so*e t"e prob*em, it does proide a $ood start, because t"e ie% cursor is in t"e tab*e at a (no%n position& 'ao*o t"en proides a ery succinct met"od to se*ect t"e entire tab*e ,see Listin$ 362.& Listing 362. *elect the entire table in the current view. 3(i#Co!ponent&CurrentController&#electBo3ableC oOCur#or&otoEndB3rueC )Mo:e to t(e end o$ t(e current cell oOCur#or&otoEndB3rueC )Mo:e to t(e end o$ t(e table TIP Remember to carefu**y test a** code dea*in$ %it" tab*es& A different so*ution proposed by 'ao*oL%"ic" fai*edL%as to use $oRi$"t,. and t"en $oDo%n,. based on t"e number of ro%s and co*umns& T"e macro in Listin$ 363 se*ects a tab*e by name, copies t"e tab*e to t"e c*ipboard, and t"en pastes it at t"e end of t"e document& Listing 363. /opy a te.t table. Sub Cop.Ha!ed3able3oEndB#Ha!e A# StrinC -i! o3able )3able to cop. -i! o3ext )-ocu!ent)# text obNect -i! o"ra!e )Current $ra!e to u#e *it( t(e di#patc(er -i! oOCur#or )Current :ie* cur#or -i! o-i#patc(er )-i#patc(er $or clipboard co!!and#
REM Place t(e cur#or in t(e #tart o$ t(e $ir#t cell& REM 3(i# i# :er. ea#.K 3(i#Co!ponent&CurrentController&#electBo3ableC oOCur#or&otoEndB3rueC )Mo:e to t(e end o$ t(e current cell& oOCur#or&otoEndB3rueC )Mo:e to t(e end o$ t(e table& REM Cop. t(e table to t(e clipboard& o-i#patc(er&execute-i#patc(Bo"ra!e= "&uno:Cop."= ""= 7= Arra.BCC REM Mo:e t(e cur#or to t(e end o$ t(e docu!ent and t(en pa#te t(e table& oOCur#or&otoRaneBo3ext&etEndBC= "al#eC o-i#patc(er&execute-i#patc(Bo"ra!e= "&uno:Pa#te"= ""= 7= Arra.BCC End Sub 408 14.(. 0e:t fields A te3t fie*d is te3t content t"at is usua**y seam*ess*y inserted into t"e e3istin$ te3t, but t"e actua* content comes from e*se%"ereLfor e3amp*e, t"e tota* number of pa$es or a database fie*d& Tab*e 1!! *ists t"e standard fie*d types& Table 144. e.t field interfaces starting with com.sun.star.te.t.e.t+ield. !ield Type Description Annotation )nserted note %it" strin$ properties Aut"or and #ontent& T"e property Date, of type com&sun&star&uti*&Date, contains t"e date t"at t"e note %as created& Aut"or Disp*ays t"e documentGs aut"or& T"e fo**o%in$ optiona* fie*ds may be present: )s0i3ed H )f 0a*se, t"e aut"or is modified eery time t"e document is saed& #ontent H Strin$ content of t"e te3t fie*d& Aut"or0ormat H #onstants from t"e com&sun&star&te3t&Aut"orDisp*ay0ormat constant $roup7 t"ese "ae t"e a*ues: 05LL ,0., LAST=4AM2 ,1., 0)RST=4AM2 ,2., or )4)T)ALS ,3.& #urrent'resentation H Strin$ containin$ t"e current te3t of t"e fie*d& 0u**4ame H )f 0a*se, t"e initia*s are disp*ayed rat"er t"an t"e fu** name& +ib*io$rap"y #ontains a property named 0ie*ds, %"ic" is an array of type 'ropertyOa*ue& T"is fie*d is dependent on a +ib*io$rap"y te3t fie*d master& #"apter #"apter information& T"e Lee* property is a +yte inte$er& T"e #"apter0ormat property is a constant $roup of type com&sun&star&te3t&#"apter0ormat %it" t"e fo**o%in$ a*id a*ues: 4AM2 ,0., 45M+2R ,1., 4AM2=45M+2R ,2., 41='R20)I=S500)I ,3., or D)J)T ,!.& #"aracter#ount )ndicates t"e number of c"aracters in t"e document& T"is contains one property, 4umberin$Type, from t"e constant $roup com&sun&star&sty*e&4umberin$Type7 a*id a*ues are s"o%n in Tab*e 1!A& #ombined#"aracters Disp*ays one to si3 c"aracters and treats t"em as one c"aracter& #onditiona*Te3t Disp*ays te3t t"at c"an$es based on a condition in t"e te3t fie*d& True#ontent H Strin$ to use if t"e condition is True& 0a*se#ontent H Strin$ to use if t"e condition is 0a*se& #ondition H Strin$ condition to ea*uate& )s#onditionTrue H +oo*ean resu*t of t"e ea*uation ,read9on*y a*ue.& DD2 Disp*ays t"e resu*t from a DD2 connection& 5ses a DD2 te3t fie*d master& Database Database te3t fie*d used as a mai*9mer$e fie*d& T"is fie*d depends on a te3t fie*d master and contains t"e fo**o%in$ properties: #ontent H Mer$ed database content as a Strin$& #urrent'resentation H Disp*ays content as a Strin$& Data+ase0ormat H )f True, t"e database number disp*ay format is used& 4umber0ormat H com&sun&star&uti*&4umber0ormatter t"at formats t"e fie*d& Database4ame Disp*ay t"e database name %"en performin$ database operations ,depends on a te3t fie*d master. %it" t"ese properties: Data+ase4ame H Strin$ containin$ t"e database name& Data#ommandType H #onstant $roup com&sun&star&sdb&#ommandType specifies %"at DataTab*e 4ame supports: TA+L2 ,0., _52R6,1., or #1MMA4D ,2.& DataTab*e4ame H Strin$ containin$ t"e tab*e name, 8uery, or statement& 409 !ield Type Description Database4e3tSet )ncrement a se*ection ,depends on a te3t fie*d master. %it" t"ese properties: Data+ase4ame H Strin$ name of t"e database& Data#ommandType H #onstant $roup com&sun&star&sdb&#ommandType specifies %"at DataTab*e 4ame supports: TA+L2 ,0., _52R6,1., or #1MMA4D ,2.& DataTab*e4ame H Strin$ containin$ t"e tab*e name, 8uery, or statement& #ondition H Strin$ t"at determines if t"e se*ection is adanced to t"e ne3t position& Database4umber1fSet Set t"e database cursor se*ection ,depends on a te3t fie*d master. %it" t"ese properties: Data+ase4ame H Strin$ name of t"e database& Data#ommandType H #onstant $roup com&sun&star&sdb&#ommandType specifies %"at DataTab*e 4ame supports: TA+L2 ,0., _52R6,1., or #1MMA4D ,2.& DataTab*e4ame H Strin$ containin$ t"e tab*e name, 8uery, or statement& #ondition H Strin$ condition t"at determines if t"e Set4umber is app*ied& Set4umber H Lon$ )nte$er set number to be app*ied& DatabaseSet4umber Disp*ay t"e current database set number ,depends on a te3t fie*d master. %it" t"ese properties: Data+ase4ame H Strin$ name of t"e database& Data#ommandType H #onstant $roup com&sun&star&sdb&#ommandType specifies %"at DataTab*e4ame supports: TA+L2 ,0., _52R6,1., or #1MMA4D ,2.& DataTab*e4ame H Strin$ containin$ t"e tab*e name, 8uery, or statement& 4umberin$Type H See #"aracter#ount property for a*id a*ues& Set4umber H Lon$ )nte$er database set& DateTime Disp*ay a date or time %it" t"e fo**o%in$ optiona* properties: )s0i3ed H )f 0a*se, t"e current date or time is disp*ayed& )sDate H )f 0a*se, t"is is on*y a time& )f True, t"is is a date %it" an optiona* time& DateTimeOa*ue H com&sun&star&uti*&DateTime ob/ect %it" t"e actua* content& 4umber0ormat H com&sun&star&uti*&4umber0ormatter t"at formats t"e fie*d& Ad/ust H Lon$ )nte$er offset to t"e date or time in minutes& )s0i3edLan$ua$e H )f 0a*se, settin$ t"e ad/acent te3t *an$ua$e may c"an$e t"e fie*d disp*ay& DropDo%n Disp*ay a drop9do%n fie*d %it" t"e fo**o%in$ properties: 4ame H 0ie*d name& )tems H Array of strin$s %it" t"e drop9do%n a*ue& Se*ected)tem H T"e se*ected item or an empty strin$ if not"in$ is se*ected& 2mbedded1b/ect#ount Disp*ay t"e number of ob/ects embedded in t"e document& #ontains t"e 4umberin$Type property7 see #"aracter#ount property for a*id a*ues& 23tended5ser Disp*ay information for t"e user data ,under Too*s a 1ptions a 1pen1ffice&or$ a 5ser Data. suc" as name, address, or p"one number& #ontent H Strin$ content& #urrent'resentation H Strin$ containin$ t"e current te3t of t"e fie*d& )s0i3ed H )f 0a*se, t"e content is updated& 5serDataType H Specify %"at to disp*ay from t"e com&sun&star&te3t&5serData'art constant $roup: #1M'A46, 0)RST4AM2, 4AM2, SE1RT#5T, STR22T, #154TR6, P)', #)T6, T)TL2, '1S)T)14, 'E142='R)OAT2, 'E142=#1M'A46, 0AI, 2MA)L, STAT2& 410 !ield Type Description 0i*e4ame Disp*ay t"e document fi*e name ,5RL.& #ontains t"e fo**o%in$ properties: #urrent'resentation H Strin$ containin$ t"e current te3t of t"e fie*d& 0i*e0ormat H 0i*e name format com&sun&star&te3t&0i*enameDisp*ay0ormat constants %it" t"e fo**o%in$ a*ues: 05LL, 'ATE, 4AM2, and 4AM2=A4D=2IT& )s0i3ed H )f 0a*se, t"e content is updated& Jet23pression Disp*ay t"e resu*t from a D$et e3pressionF te3t fie*d& #ontent H Strin$ content& #urrent'resentation H Strin$ containin$ t"e current te3t of t"e fie*d& 4umber0ormat H com&sun&star&uti*&4umber0ormatter t"at formats t"e fie*d& 4umberin$Type H See #"aracter#ount property for a*id a*ues& )sS"o%0ormu*a H )f True, t"e formu*a is disp*ayed rat"er t"an t"e content& SubType H Oariab*e type from t"e com&sun&star&te3t&SetOariab*eType constants %it" t"e fo**o%in$ a*ues: OAR, S2_524#2, 01RM5LA, and STR)4J& Oa*ue H 4umerica* ,Doub*e. a*ue of t"e fie*d& )s0i3edLan$ua$e H )f 0a*se, settin$ t"e ad/acent te3t *an$ua$e may c"an$e t"e fie*d disp*ay& JetReference Reference fie*d %it" t"ese properties: #urrent'resentation H Strin$ containin$ t"e current te3t of t"e fie*d& Reference0ie*dSource H com&sun&star&te3t&Reference0ie*dSource constant %it" t"e fo**o%in$ a*ues: R202R24#2=MAR<, S2_524#2=0)2LD, +11<MAR<, 011T41T2, or 24D41T2& Source4ame H Strin$ reference name suc" as a boo(mar( name& Reference0ie*d'art H com&sun&star&te3t&Reference0ie*d'art constant %it" t"e fo**o%in$ a*ues: 'AJ2, #EA'T2R, T2IT, 5'=D1;4, 'AJ2=D2S#, #AT2J1R6=A4D=45M+2R, 14L6=#A'T)14, and 14L6=S2_524#2=45M+2R& Se8uence4umber H S"ort inte$er se8uence number used as se8uence fie*d or Reference)d property of a footnote or endnote& Jrap"ic1b/ect#ount Disp*ay t"e number of $rap"ic ob/ects embedded in t"e document& #ontains t"e 4umberin$Type property7 see #"aracter#ount property for a*id a*ues& Eidden'ara$rap" A**o% a para$rap" to be "idden& 5sed, for e3amp*e, to create a test %it" t"e 8uestions and ans%ers a** in one document& Settin$ t"e ans%ers to "idden a**o%s t"e test 8uestions to be printed for t"e students& #ondition H Strin$ condition to ea*uate& )sEidden H +oo*ean resu*t of t"e *ast ea*uation of t"e condition& EiddenTe3t A fie*d %it" "idden te3t& Differs from a "idden para$rap" in t"at on*y t"e te3t in t"e fie*d is "idden, rat"er t"an t"e entire containin$ para$rap"& #ontent H Strin$ te3t content of t"e "idden te3t fie*d& #ondition H Strin$ condition& )sEidden H +oo*ean resu*t of t"e *ast ea*uation of t"e condition& )nput Te3t input fie*d& #ontent H Strin$ te3t content of t"e fie*d& Eint H Strin$ "int te3t& 411 !ield Type Description )nput5ser 5ser9defined te3t fie*d t"at depends on a fie*d master& #ontent H Strin$ te3t content of t"e fie*d& Eint H Strin$ "int te3t& Kump2dit '*ace"o*der te3t fie*d& Eint H Strin$ "int te3t& '*aceEo*der H Strin$ te3t of t"e p*ace"o*der& '*aceEo*derType H com&sun&star&te3t&'*ace"o*derType constant %it" t"e fo**o%in$ a*id a*ues: T2IT, TA+L2, T2IT0RAM2, JRA'E)#, or 1+K2#T& Macro Macro te3t fie*d& Eint H Stin$ "int te3t& Macro4ame H Strin$ macro name to run& MacroLibrary H Strin$ *ibrary name t"at contains t"e macro& 'a$e#ount Disp*ay t"e number of pa$es in t"e document& #ontains t"e 4umberin$Type property7 see #"aracter#ount property for a*id a*ues& 'a$e4umber Disp*ay a pa$e number& 1ffset H S"ort )nte$er offset to s"o% a different pa$e number& SubType H ;"ic" pa$e is disp*ayed from t"e com&sun&star&te3t&'a$e4umberType enumeration& Oa*id a*ues: 'R2O, #5RR24T, or 42IT& 5serTe3t H Strin$ t"at is disp*ayed %"en t"e 4umberin$Type is #EAR=S'2#)AL& 4umberin$Type H See #"aracter#ount property for a*id a*ues& 'ara$rap"#ount Disp*ay t"e number of para$rap"s in t"e document& #ontains t"e 4umberin$Type property7 see #"aracter#ount property for a*id a*ues& Reference'a$eJet Disp*ay t"e pa$e number of a reference point& #ontains t"e 4umberin$Type property7 see #"aracter#ount property for a*id a*ues& Reference'a$eSet )nsert additiona* pa$e numbers& #ontains t"ese properties: 1ffset H S"ort )nte$er t"at c"an$es t"e disp*ayed a*ue of a Reference'a$eJet fie*d& 4ame1n H )f True, t"e Reference'a$eJet te3t fie*ds are disp*ayed& Script Disp*ay te3t obtained by runnin$ a script& #ontains t"ese properties: #ontent H Script te3t or 5RL of t"e script as a strin$& ScriptType H Strin$ script type, suc" as KaaScript& 5RL#ontent H )f True, #ontent is a 5RL& )f 0a*se, #ontent is t"e script te3t& 412 !ield Type Description Set23pression An e3pression te3t fie*d& #ontains t"ese properties: #ontent H Strin$ content& #urrent'resentation H Strin$ containin$ t"e current te3t of t"e fie*d& 4umber0ormat H com&sun&star&uti*&4umber0ormatter t"at formats t"e fie*d& 4umberin$Type H See #"aracter#ount property for a*id a*ues& )sS"o%0ormu*a H )f True, t"e formu*a is disp*ayed rat"er t"an t"e content& Eint H Strin$ "int used if t"is is an input fie*d& )s)nput H )f True, t"e fie*d is an input fie*d& )sOisib*e H )f True, t"e fie*d is isib*e& Se8uenceOa*ue H Se8uence a*ue %"en t"is fie*d is used as se8uence fie*d& SubType H Oariab*e type from t"e com&sun&star&te3t&SetOariab*eType constants %it" t"e fo**o%in$ a*ues: OAR, S2_524#2, 01RM5LA, and STR)4J& Oa*ue H 4umerica* ,Doub*e. a*ue of t"e fie*d& Oariab*e4ame H 4ame of t"e associated set e3pression fie*d master& )s0i3edLan$ua$e H )f 0a*se, settin$ t"e ad/acent te3t *an$ua$e may c"an$e t"e fie*d disp*ay& Tab*e#ount Disp*ay t"e number of tab*es in t"e document& #ontains t"e 4umberin$Type property7 see #"aracter#ount property for a*id a*ues& Temp*ate4ame Disp*ay t"e name of t"e temp*ate used to create t"e document& Supports t"e 0i*e0ormat property as supported by t"e 0i*ename property& 5RL Disp*ay a 5RL& #ontains t"ese properties: 0ormat H S"ort )nte$er specifyin$ t"e 5RL output format& 5RL H Strin$ containin$ t"e unparsed ori$ina* 5RL& Representation H Disp*ay strin$ s"o%n to t"e user& Tar$et0rame H Strin$ frame name %"ere t"e 5RL %i** be opened& 5ser Disp*ay a user9defined fie*d %it" a fie*d master& #ontains t"ese properties: )sS"o%0ormu*a H )f True, t"e formu*a is disp*ayed rat"er t"an t"e content& )sOisib*e H )f True, t"e fie*d is isib*e& 4umber0ormat H com&sun&star&uti*&4umber0ormatter t"at formats t"e fie*d& )s0i3edLan$ua$e H )f 0a*se, settin$ t"e ad/acent te3t *an$ua$e may c"an$e t"e fie*d disp*ay& ;ord#ount Disp*ay t"e number of %ords in t"e document& #ontains t"e 4umberin$Type property7 see #"aracter#ount property for a*id a*ues& docinfo&#"an$eAut"or Disp*ay t"e name of t"e *ast aut"or to modify t"e document& Aut"or H Strin$ containin$ t"e name of t"e aut"or& #urrent'resentation H #urrent content of t"e te3t fie*d as a Strin$& )s0i3ed H )f 0a*se, t"e content is updated %"en t"e document is saed& 413 !ield Type Description docinfo&#"an$eDateTime Disp*ay t"e date and time t"e document %as *ast c"an$ed& #ontains t"ese properties: #urrent'resentation H #urrent content of t"e te3t fie*d as a Strin$& )s0i3ed H )f 0a*se, t"e current date or time is disp*ayed& )sDate H )f 0a*se, t"is is on*y a time& )f True, t"is is a date %it" an optiona* time& DateTimeOa*ue H com&sun&star&uti*&DateTime ob/ect %it" t"e actua* content& 4umber0ormat H com&sun&star&uti*&4umber0ormatter t"at formats t"e fie*d& )s0i3edLan$ua$e H )f 0a*se, settin$ t"e ad/acent te3t *an$ua$e may c"an$e t"e fie*d disp*ay& docinfo&#reateAut"or Disp*ay t"e name of t"e aut"or %"o created t"e document ,see docinfo&#"an$eAut"or for supported properties.& docinfo&#reateDateTime Disp*ay t"e date and time t"e document %as created ,see docinfo&#"an$eDateTime for supported properties.& docinfo&Description Disp*ay t"e document description as contained in t"e document properties ,0i*e a 'roperties.& #ontent H Strin$ content& #urrent'resentation H Strin$ containin$ t"e current te3t of t"e fie*d& )s0i3ed H )f 0a*se, t"e content is updated %"en t"e document information is c"an$ed& docinfo&2ditTime Disp*ay t"e duration t"e document "as been edited& )n ot"er %ords, "o% *on$ did it ta(e to %rite> #urrent'resentation H Strin$ containin$ t"e current te3t of t"e fie*d& )s0i3ed H )f 0a*se, t"e date or time is a*%ays disp*ayed as t"e current date or time& DateTimeOa*ue H Date and time as a Doub*e& 4umber0ormat H com&sun&star&uti*&4umber0ormatter t"at formats t"e fie*d& )s0i3edLan$ua$e H )f 0a*se, settin$ t"e ad/acent te3t *an$ua$e may c"an$e t"e fie*d disp*ay& docinfo&)nfo0 Disp*ay t"e document info 0 ,see doc&Description.& docinfo&)nfo1 Disp*ay t"e document info 1 ,see doc&Description.& docinfo&)nfo2 Disp*ay t"e document info 2 ,see doc&Description.& docinfo&)nfo3 Disp*ay t"e document info 3 ,see doc&Description.& docinfo&<ey%ords Disp*ay t"e document info (ey%ords ,see doc&Description.& docinfo&'rintAut"or Disp*ay t"e name of t"e aut"or %"o printed t"e document ,see docinfo&#"an$eAut"or for supported properties.& docinfo&'rintDateTime Disp*ay t"e time t"e document %as *ast printed ,see docinfo&#"an$eDateTime for supported properties.& docinfo&Reision Disp*ay t"e current document reision ,see doc&Description.& docinfo&Sub/ect Disp*ay t"e document sub/ect specified in t"e document information ,see doc&Description.& docinfo&Tit*e Disp*ay t"e document tit*e specified in t"e document information ,see doc&Description.& TIP T"e Annotation fie*d is a serice of type com&sun&star&te3t&Te3t0ie*d&Annotation& Some sources of documentation s"o% t"e te3t Dte3tfie*dF in a** *o%ercase *etters7 t"is is incorrect& T"e code in Listin$ 36! s"o%s t"is correct*y& 414 Tab*e 1!A contains t"e a*id a*ues for t"e #"aracter#ount property from Tab*e 1!!& Table 145. /onstants defined by com.sun.star.style.Numberingype. Constant Description #EARS=5''2R=L2TT2R 4umberin$ is in uppercase *etters as DA, +, #, D, &&&F& #EARS=L1;2R=L2TT2R 4umberin$ is in *o%ercase *etters as Da, b, c, d,&&&F& R1MA4=5''2R 4umberin$ is in Roman numbers %it" uppercase *etters as D), )), ))), )O, &&&F& R1MA4=L1;2R 4umberin$ is in Roman numbers %it" *o%ercase *etters as Di, ii, iii, i, &&&F& ARA+)# 4umberin$ is in Arabic numbers as D1, 2, 3, !, &&&F& 45M+2R=4142 4umberin$ is inisib*e& #EAR=S'2#)AL 5se a c"aracter from a specified font& 'AJ2=D2S#R)'T1R 4umberin$ is specified in t"e pa$e sty*e& +)TMA' 4umberin$ is disp*ayed as a bitmap $rap"ic& #EARS=5''2R=L2TT2R=4 4umberin$ is in uppercase *etters as DA, +, &&&, 6, P, AA, ++, ##, &&& AAA, &&&F& #EARS=L1;2R=L2TT2R=4 4umberin$ is in *o%ercase *etters as Da, b, &&&, y, C, aa, bb, cc, &&& aaa, &&&F& TRA4SL)T2RAT)14 A trans*iteration modu*e is used to produce numbers in #"inese, Kapanese, etc& 4AT)O2=45M+2R)4J T"e natie9number9supp*ier serice is ca**ed to produce numbers in natie *an$ua$es& 05LL;)DTE=ARA+)# 4umberin$ for fu**9%idt" Arabic number& #)R#L2=45M+2R +u**et for #irc*e 4umber& 45M+2R=L1;2R=PE 4umberin$ for #"inese *o%ercase numbers& 45M+2R=5''2R=PE 4umberin$ for #"inese uppercase numbers& 45M+2R=5''2R=PE=T; 4umberin$ for Traditiona* #"inese uppercase numbers& T)A4=JA4=PE +u**et for #"inese Tian Jan& D)=P)=PE +u**et for #"inese Di Pi& 45M+2R=TRAD)T)14AL=KA 4umberin$ for Kapanese traditiona* numbers& A)5=05LL;)DTE=KA +u**et for Kapanese A)5 fu** %idt"& A)5=EAL0;)DTE=KA +u**et for Kapanese A)5 "a*f %idt"& )R1EA=05LL;)DTE=KA +u**et for Kapanese )R1EA fu** %idt"& )R1EA=EAL0;)DTE=KA +u**et for Kapanese )R1EA "a*f %idt"& 45M+2R=5''2R=<1 4umberin$ for <orean uppercase numbers& 45M+2R=EA4J5L=<1 4umberin$ for <orean "an$u* numbers& EA4J5L=KAM1=<1 +u**et for <orean Ean$u* Kamo& EA4J5L=S6LLA+L2=<1 +u**et for <orean Ean$u* Sy**ab*e& EA4J5L=#)R#L2D=KAM1=<1 +u**et for <orean Ean$u* #irc*ed Kamo& EA4J5L=#)R#L2D=S6LLA+L2=<1 +u**et for <orean Ean$u* #irc*ed Sy**ab*e& #EARS=ARA+)# 4umberin$ in Arabic a*p"abet *etters& #EARS=TEA) 4umberin$ in T"ai a*p"abet *etters& 415 T"e te3t fie*ds contained in t"e document are aai*ab*e usin$ t"e $etTe3t0ie*ds,. ob/ect met"od ,see Tab*e 13M.& 2ery te3t fie*d ob/ect supports t"e ob/ect met"od $et'resentation,boo*ean., %"ic" returns a strin$ representin$ eit"er t"e fie*d type ,True. or t"e disp*ayed te3t ,0a*se.& See !isting /46 and +igure (6& Listing 364. #isplay +ields. Sub -i#pla."ield# oEnu! 6 3(i#Co!ponent&et3ext"ield#BC&createEnu!erationBC -o W(ile oEnu!&(a#MoreEle!ent#BC o"ield 6 oEnu!&nextEle!entBC # 6 # 4 o"ield&etPre#entationB3rueC 4 " 6 " )"ield t.pe I$ o"ield&#upport#Ser:iceB"co!&#un&#tar&text&3ext"ield&Annotation"C 3(en REM More cr.ptic= I could u#e I$ o"ield&etPre#entationB3rueC 6 "Hote"&&& REM A "Hote" (a# no di#pla.ed content #o callin etPre#entationB"al#eC REM return# an e!pt. #trin& In#tead= obtain t(e aut(or and t(e content& # 6 # 4 o"ield&Aut(or 4 " #a.# " 4 o"ield&Content El#e # 6 # 4 o"ield&etPre#entationB"al#eC )Strin content End I$ # 6 # 4 CHRFB>%C ,oop M#Box #= 7= "3ext "ield#" End Sub Figure 94. e.t fields in the current document. T"e source document used to create 0i$ure B! contains a DateTime fie*d, 'a$e4umber fie*ds, Annotation fie*d, and a 5ser fie*d& T"e code in Listin$ 36! proides specia* treatment for note fie*ds to disp*ay bot" t"e aut"or and t"e note& T"e fie*d is c"ec(ed to see if it supports t"e Annotation serice by usin$ t"e supportsSerice1b/ect,. met"od& T"e primary met"od of findin$ a specific te3t fie*d is by enumeratin$ t"e te3t fie*ds as s"o%n in Listin$ 36!& )f t"e document is *ar$e and contains many te3t fie*ds, it may ta(e a *on$ time to find a specific te3t fie*d& )f you (no% %"ere t"e te3t fie*d is *ocated in t"e document, Listin$ 33M demonstrates "o% to find a te3t fie*d by enumeratin$ te3t content in a para$rap"& TIP Te3t fie*ds imp*ement t"e ob/ect met"od update,.& T"e update,. met"od causes a te3t fie*d to update itse*f %it" t"e most current information if it is app*icab*e& 0or e3amp*e, date-time, fi*e name, and t"e document information te3t fie*ds a** update to t"e most current information& 416 1$.2.1. Text master fields Some te3t fie*ds contain t"eir o%n content, and ot"ers re*y on an e3terna* source to obtain t"e disp*ayed information& T"e e3terna* source is ca**ed a master fie*d& Tab*e 1!6 *ists t"e te3t fie*d types t"at re8uire a master fie*d& +esides t"e properties s"o%n in Tab*e 1!6, eery te3t fie*d master a*so supports t"e properties s"o%n in Tab*e 1!M& TIP T"e ob/ect met"od $etTe3t0ie*dMaster,. returns a te3t fie*dGs master fie*d& 5nfortunate*y, eery fie*d, een fie*ds t"at do not "ae master fie*ds, imp*ements t"is met"od and returns a non9nu** master fie*d& 11o may cras" if you obtain and manipu*ate a master fie*d from a fie*d t"at does not contain one& A*t"ou$" te3t fie*ds are accessib*e on*y by enumeration, master fie*ds are accessib*e by name and enumeration ,see Tab*e 13M.& T"e name used for a master fie*d is obtained by appendin$ t"e fie*d name to t"e fie*d master type& 0or e3amp*e, t"e 5ser fie*d DAndy0ie*dF, as s"o%n in 0i$ure B!, "as a master fie*d named com&sun&star&te3t&0ie*d9Master&5ser&Andy0ie*d& Database master fie*ds are named different*y t"an a** of t"e ot"er master fie*ds7 t"ey append t"e Database4ame, Datatab*e4ame, and Data#o*umn4ame to t"e serice name& Listin$ 36A demonstrates "o% to obtain t"e te3t fie*d masters in a document& 0i$ure BA s"o%s t"e resu*ts& Table 146. e.t field interfaces starting with com.sun.star.te.t.+ieldMaster. !ield Type Description +ib*io$rap"y 0ie*d master to a +ib*io$rap"y te3t fie*d& #ontains t"ese properties: )s4umber2ntries H )f True, t"e fie*ds are numbered7 ot"er%ise, t"e s"ort entry name is used& )sSort+y'osition H )f True, t"e bib*io$rap"y inde3 is sorted by t"e document position ,see Sort<ey.& +rac(et+efore H T"e openin$ brac(et disp*ayed in t"e +ib*io$rap"y te3t fie*d& +rac(etAfter H T"e c*osin$ brac(et disp*ayed in t"e +ib*io$rap"y te3t fie*d& Sort<eys H T"is array of 'ropertyOa*ues is used if )sSort+y'osition is 0a*se& T"e properties are a se8uence of t"e property Sort<ey ,com&sun&star&te3t&+ib*io$rap"yData0ie*d constant identifyin$ t"e fie*d to sort. and )sSortAscendin$ ,+oo*ean.& Loca*e H com&sun&star&*an$&Loca*e of t"e fie*d master& SortA*$orit"m H Strin$ containin$ t"e name of t"e sort a*$orit"m used to sort t"e te3t fie*ds& DD2 0ie*d master to a DD2 te3t fie*d& #ontains t"ese properties: DD2#ommand2*ement H DD2 command as a strin$& DD2#ommand0i*e H 0i*e strin$ of t"e DD2 command& DD2#ommandType H DD2 command type as a strin$& )sAutomatic5pdate H )f True, t"e DD2 *in( is automatica**y updated& Database 0ie*d master to a Database te3t fie*d& #ontains t"ese properties: Data+ase4ame H Strin$ name of t"e data source& #ommandType H Lon$ )nte$er #ommandType ,0 ? tab*e, 1 ? 8uery, 2 ? statement.& DataTab*e4ame H #ommand strin$ type is determined by t"e #ommandType property& Data#o*umn4ame H Database tab*e name as a Strin$& 417 !ield Type Description Set23pression 0ie*d master to a Dset e3pressionF te3t fie*d& #ontains t"ese properties: #"apter4umberin$Lee* H #"apter number as a byte, if t"is is a number se8uence& 4umberin$Separator H 4umberin$ separator strin$, used if t"is is a number se8uence& SubType H Oariab*e type from t"e com&sun&star&te3t&SetOariab*eType constants %it" t"e fo**o%in$ a*ues: OAR, S2_524#2, 01RM5LA, and STR)4J& 5ser 0ie*d master to a user te3t fie*d& #ontains t"e properties: )s23pression H )f True, t"e fie*d contains an e3pression& Oa*ue H Doub*e a*ue& #ontent H 0ie*d content as a strin$& Table 147. 9roperties defined by the service com.sun.star.te.t.+ieldMaster. Property Description 4ame 1ptiona* strin$ %it" t"e fie*d name7 t"is must be set before t"e fie*d is added to t"e document& DependentTe3t0ie*ds Array of te3t fie*ds t"at use t"is master fie*d& )nstance4ame Strin$ instance name as it is used in t"e ITe3t0ie*dsSupp*ier& Listing 365. *how te.t field masters. Sub S(o*"ieldMa#ter# -i! oMa#ter# )All o$ t(e text $ield !a#ter# -i! oMa#terHa!e# )Arra. o$ t(e text $ield !a#ter na!e# -i! iG= NG )Index :ariable# -i! #Ma#terHa!eF )"ull na!e o$ t(e !a#ter $ield -i! #F )0tilit. #trin -i! oMa#ter )Ma#ter $ield REM Obtain t(e text $ield !a#ter# obNect& oMa#ter# 6 3(i#Co!ponent&et3ext"ieldMa#ter#BC REM Obtain A,, o$ t(e text !a#ter $ield na!e#& REM 3(i# i# an arra. o$ #trin#& oMa#terHa!e# 6 oMa#ter#&etEle!entHa!e#BC "or i 6 ,BoundBoMa#terHa!e#C to 0BoundBoMa#terHa!e#C
REM "or a i:en na!e= obtain t(e !a#ter $ield= REM t(en loo1 at t(e -ependent3ext"ield# propert.= REM *(ic( i# an arra. o$ text $ield# t(at depend REM on t(i# !a#ter $ield& #Ma#terHa!e 6 oMa#terHa!e#BiC oMa#ter 6 oMa#ter#&etB.Ha!eB#Ma#terHa!eC # 6 # 4 "***" 4 #Ma#terHa!e 4 "***" 4 CHRFB>7C # 6 # 4 oMa#ter&Ha!e 4 " Contain# " 45 CStrB0BoundBoMa#ter&-ependent3ext"ield#C W >C 45 " dependent $ield#" 4 CHRFB>7C # 6 # 4 CHRFB>%C 418 Hext I REM -irectl. obtain a !a#ter $ield ba#ed on t(e na!e& REM 3(i# i# a u#er $ield t(at I added to t(e #ource code $ile& I$ oMa#ter#&(a#B.Ha!eB"co!&#un&#tar&text&"ieldMa#ter&0#er&And."ield"C 3(en oMa#ter6oMa#ter#&etB.Ha!eB"co!&#un&#tar&text&"ieldMa#ter&0#er&And."ield"C # 6 # 4 "-irectl. obtained t(e $ield !a#ter " 4 oMa#ter&Ha!e 4 CHRFB>7C 45 "3(e $ield contain# t(e text " 4 oMa#ter&Content End I$ M#Box #= 7= "3ext "ield Ma#ter#" End Sub Figure 95. e.t fields in the current document. 1$.2.2. Creating and adding text fields Te3t fie*ds must be created by t"e document t"at %i** contain t"em& )t is a*so t"e document t"at %i** destroy t"em if you c"oose to remoe t"em from t"e document& Listin$ 366 demonstrates t"e creation, confi$uration, and insertion of bot" a DateTime te3t fie*d and an Annotation te3t fie*d& T"e te3t fie*ds are appended to t"e end of t"e document& T"e DateTime te3t fie*d is formatted in an unusua* manner, so a ne% number format sty*e is created if it does not yet e3ist& TIP T"e ery popu*ar routine 0ind#reate4umber0ormatSty*e ,see Listin$ 3M0. is used by Listin$ 366& Listing 366. "nsert te.t fields. Sub In#ert"ield# -i! o3ext )3ext obNect $or t(e current docu!ent -i! o"ield )"ield to in#ert -i! o-oc )o-oc i# $e*er c(aracter# t(an 3(i#Co!ponent
o-oc 6 3(i#Co!ponent o3ext 6 o-oc&3ext
REM Start b. in#ertin a date ti!e text $ield at t(e end o$ t(e REM docu!ent& "or!at t(e date ti!e a# "--& MMM PPPP" 419 REM In#ert #o!e explanator. text be$ore t(e ne*l. in#erted $ield& o3ext&in#ertStrinBo3ext&etEndBC= "3oda. i# "= "A,SEC
REM Create a date ti!e $ield& o"ield 6 o-oc&createIn#tanceB"co!&#un&#tar&text&3ext"ield&-ate3i!e"C o"ield&I#"ixed 6 3R0E o"ield&Hu!ber"or!at 6 "indCreateHu!ber"or!atSt.leB"--& MMMM PPPP"= o-ocC o3ext&in#ert3extContentBo3ext&etEndBC= o"ield= "al#eC REM Ho*= in#ert an Annotation a$ter t(e in#erted text $ield& -i! o-ate A# He* co!&#un&#tar&util&-ate REM ,ie about t(e date and #a. t(at I did it a little *(ile aoK Wit( o-ate &-a. 6 -a.BHo* 9 >7C &Mont( 6 Mont(BHo* 9 >7C &Pear 6 PearBHo* 9 >7C End Wit( REM ,i1e !o#t text content= t(e $ield !u#t be created b. t(e docu!ent REM t(at *ill contain it& o"ield 6 o-oc&createIn#tanceB"co!&#un&#tar&text&3ext"ield&Annotation"C Wit( o"ield &Aut(or 6 "AP" &Content 6 "3(i# note i# next to a date $ield t(at I Nu#t added" &-ate 6 o-ate )O!!it t(e date and it de$ault# to toda.K End Wit( o3ext&in#ert3extContentBo3ext&etEndBC= o"ield= "al#eC M#Box "3*o $ield# in#erted at t(e end o$ t(e docu!ent" End Sub )nsertin$ a fie*d t"at re8uires a te3t fie*d master is s*i$"t*y more difficu*t t"an insertin$ a re$u*ar te3t fie*d& +ot" t"e master fie*d and t"e dependent te3t fie*d must be created by t"e document usin$ t"e ob/ect met"od create)nstance,.& T"e master fie*d must be named before it is used7 after insertin$ a fie*d into a document, you cannot c"an$e t"e name& T"e dependent fie*d is attac"ed to t"e master fie*d, %"ic" proides t"e content to t"e dependent fie*d& T"e dependent fie*d, not t"e master fie*d, is inserted as te3t content into t"e document& T"e dependent fie*d can be remoed from t"e document by usin$ t"e remoeTe3t#ontent,. ob/ect met"od& To remoe t"e master fie*d, use t"e dispose,. met"od of t"e master fie*d& Listin$ 36M demonstrates t"e use of master fie*ds by performin$ arious operations on a master fie*d named DTest0ie*dF& T"ree specific states are c"ec(ed and appropriate be"aior is ta(en as fo**o%s: If the master field does not exist, the master field and a dependent field are created and inserted into the document. The field is now visible by opening the Field dialog using Insert | Fields | Other and choosing the Variables tab. If the master field exists with a corresponding dependent field, the dependent field is removed from the document. The master field still exists, but no dependent field is inserted in the document. You can view the master field by using the Field dialog. If the master field exists and has no corresponding dependent field, the master field is removed by using the dispose() object method. The Field dialog no longer shows the master field. 420 Listing 367. "nsert field master. Sub In#ert"ieldMa#ter -i! oMa#ter# )All o$ t(e text $ield !a#ter# -i! o3ext )3ext obNect $or t(e current docu!ent -i! o0"ield )0#er $ield to in#ert -i! oM"ield )3(e !a#ter $ield $or t(e u#er $ield -i! o-oc )o-oc i# $e*er c(aracter# t(an 3(i#Co!ponent -i! #,eadF ),eadin $ield na!e -i! #Ha!eF )Ha!e o$ t(e $ield to re!o:e or in#ert -i! #3otHa!eF )3(e entire na!e REM Set t(e na!e#& #Ha!e 6 "3e#t"ield" #,ead 6 "co!&#un&#tar&text&"ieldMa#ter&0#er" #3otHa!e 6 #,ead 4 "&" 4 #Ha!e REM Initiali8e #o!e :alue#& o-oc 6 3(i#Co!ponent o3ext 6 o-oc&3ext oMa#ter# 6 3(i#Co!ponent&et3ext"ieldMa#ter#BC REM I$ t(e !a#ter $ield alread. exi#t#= t(en per$or! #pecial (andlin& REM Special (andlin i# $or illu#trati:e purpo#e# onl.= not t(at it REM #ol:e# an. particularl. $un and excitin proble!& I$ oMa#ter#&(a#B.Ha!eB#3otHa!eC 3(en REM Obtain t(e !a#ter $ield and t(e $ield# dependent on t(i# $ield& oM"ield 6 oMa#ter#&etB.Ha!eB#3otHa!eC
REM I$ t(ere are $ield# dependent on t(i# $ield t(en REM t(e arra. o$ dependent $ield# (a# :alue#K I$ 0BoundBoM"ield&-ependent3ext"ield#C D6 7 3(en REM Re!o:e t(e text content and it di#appear# $ro! t(e REM docu!ent& 3(e !a#ter $ield #till exi#t#= (o*e:erK o0"ield 6 oM"ield&-ependent3ext"ield#B7C o3ext&re!o:e3extContentBo0"ieldC M#Box "Re!o:ed one in#tance $ro! t(e docu!ent" El#e REM I arbitraril. decided t(at I *ould de#tro. t(e !a#ter $ield REM but I could Nu#t a# ea#il. create a ne* u#er $ield and REM attac( it to t(e exi#tin !a#ter $ield and t(en in#ert REM t(e ne* $ield into t(e docu!ent& M#Box "Ho in#tance# in t(e docu!ent= di#po#in !a#ter $ield" oM"ield&content6"" oM"ield&di#po#eBC End I$ El#e REM Create a 0#er text $ield t(at re;uire# a !a#ter $ield& o0"ield 6 o-oc&createIn#tanceB"co!&#un&#tar&text&3ext"ield&0#er"C
REM Pou CAHHO3 c(ane t(e na!e o$ a !a#ter $ield A"3ER it i# in#erted REM into a docu!ent #o .ou !u#t #et it no*& oMa#ter"ield&Ha!e 6 #Ha!e
REM 3(i# i# t(e data t(at *ill be di#pla.ed& Re!e!ber t(at t(e REM u#er $ield di#pla.# *(at t(e !a#ter tell# it to di#pla.& oMa#ter"ield&Content 6 "Hello"
REM A u#er $ield !u#t be attac(ed to a !a#ter $ield& REM 3(e u#er $ield i# no* a "-ependent3ext"ield"& o0"ield&attac(3ext"ieldMa#terBoMa#ter"ieldC
REM In#ert t(e u#er $ield into t(e docu!ent& o3ext&in#ert3extContentBo3ext&etEndBC= o0"ield= "al#eC M#Box "One $ield in#erted at t(e end o$ t(e docu!ent" End I$ End Sub 14.1+. Boo*mar*s A boo(mar( is te3t content t"at is accessib*e based on its name& A boo(mar( may encompass a te3t ran$e or a sin$*e point& Listin$ 3A! inserts te3t content at t"e point %"ere a boo(mar( is anc"ored& 5se t"e $etStrin$,. ob/ect met"od to obtain t"e strin$ contained in t"e boo(mar(& 5se setStrin$,. to set t"e strin$ contained in t"e boo(mar(& )f t"e boo(mar( is mere*y a point, t"e te3t is mere*y inserted before t"e boo(mar(& ;"en a created boo(mar( is inserted into t"e te3t, t"e insertion point determines t"e boo(mar(Gs anc"or position& Listing 368. #emonstrate how to add a bookmark. Sub AddBoo1!ar1 -i! oBoo1!ar1 )Created boo1!ar1 to add -i! oCur# )3ext cur#or
REM Create a text cur#or t(at contain# t(e la#t $our c(aracter# REM in t(e docu!ent& oCur# 6 3(i#Co!ponent&3ext&create3extCur#orBC oCur#&otoEndB"al#eC oCur#&o,e$tB?= 3rueC REM Create t(e boo1!ar1& oBoo1!ar1 6 3(i#Co!ponent&createIn#tanceB"co!&#un&#tar&text&Boo1!ar1"C
REM I$ t(e boo1!ar1 i# not i:en a na!e= OOo *ill create a na!e& REM I$ t(e na!e alread. exi#t#= a nu!ber i# appended to t(e na!e& oBoo1!ar1&#etHa!eB"Bobert"C
REM Becau#e 3rue i# u#ed= t(e boo1!ar1 contain# t(e la#t $our c(aracter# REM in t(e docu!ent& I$ "al#e i# u#ed in#tead= t(en t(e boo1!ar1 REM contain# no c(aracter# and it i# po#itioned be$ore t(e $ourt( c(aracter REM $ro! t(e end o$ t(e docu!ent& 3(i#Co!ponent&3ext&in#ert3extContentBoCur#= oBoo1!ar1= "al#eC End Sub 422 14.11. /eDuence fields4 references4 and formatting #onsider t"e caption for Listin$ 36@& )$norin$ formattin$, enter t"e caption as fo**o%s: 1& 2nter t"e te3t DListin$ F& 2& 5se 7nsert > +iel&s > Other to open t"e 0ie*ds dia*o$& 3& Se*ect t"e Oariab*es tab& !& Se*ect t"e 4umber Ran$e type & A& 2nter Listing for name and Listin$ N 1 for t"e a*ue& 6& #*ic( )nsert& M& 2nter t"e rest of t"e caption& Se8uence fie*ds ,number ran$es. %or( %e** because t"ey automatica**y renumber as captions are added and remoed& A reference to a se8uence fie*d renumbers if t"e fie*d itse*f c"an$es a*ue because a fie*d is added or remoed& ) "ad a co**ection of documents containin$ "undreds of captions and references& 5nfortunate*y, a** captions and references %ere te3t as opposed to fie*ds& ) needed a macro to conert t"e te3t captions and references to use se8uence fie*ds and *in(ed cross references& 1$.11.1. +ormatting numbers and dates Se8uence fie*ds can be formatted in many %ays& 5*timate*y, t"e formattin$ is associated to a defined format strin$& 11o is confi$ured to (no% many common number and date formats, and you can create ne% formats as you desire& 2ac" number format is assi$ned a numeric )D& T"in$s t"at format numbers and dates H suc" as fie*ds and tab*e ce**s H contain t"e numeric (ey for t"e formattin$ strin$ used to disp*ay t"e contained a*ue& .ist formats *nown to the current document *now ;"en you create a ne% number format, t"e format is stored in t"e current document& T"e supported numeric formats and t"e )D for a specific format %i** differ from document to document& Listing 369. List the formats in the current document. Sub ,i#t"or!at#InCurrent-ocu!entBC -i! o-oc ) -ocu!ent created to (old t(e $or!at #trin#& -i! o"or!at# ) "or!at# in t(e current docu!ent& -i! o"or!at ) Current $or!at obNect& -i! o-ata ) ^e.# ;ueried $ro! t(e $or!at#& -i! iG ) Jeneral index :ariable& -i! #"or!atF ) Current $or!at #trin& -i! #Pre:"or!atF ) Pre:iou# $or!at #trin& -i! a,ocale a# ne* co!&#un&#tar&lan&,ocale o"or!at# 6 3(i#Co!ponent&etHu!ber"or!at#BC
) Create an output docu!ent& o-oc 6 Star-e#1top&loadCo!ponent"ro!0R,B "pri:ate:$actor.+#*riter"= "5blan1"= 7= Arra.BC C o-ata 6 o"or!at#&;uer.^e.#Bco!&#un&#tar&util&Hu!ber"or!at&A,,= a,ocale= "al#eC "or i 6 ,BoundBo-ataC 3o 0BoundBo-ataC o"or!at6o"or!at#&etb.1e.Bo-ataBiCC 423 #"or!at6o"or!at&"or!atStrin I$ #"or!atED#Pre:"or!at 3(en #Pre:"or!at6#"or!at o-oc&et3extBC&in#ertStrinBo-oc&et3extBC&End= 5 CStrBo-ataBiCC 4 CHRFB@C 4 #"or!at 4 CHRFB>7C= "al#eC End I$ Hext End Sub Cind or create a numeric format. ;"en a number format is added, it may be modified and stored in a s*i$"t*y different format& _uery<ey searc"es t"e interna* modified 8uery strin$s %it"out first modifyin$ t"e input strin$& T"e end resu*t is t"at after storin$ a (ey 8uery<ey %i** c*aim t"at t"e format strin$ is not present& )f you t"en dutifu**y, add t"e format strin$, an e3ception %i** be t"ro%n because it a*ready e3ists& Eere are t"ree e3amp*es: 1& Addin$ ZW,WW0&00=.7cRedd,W,WW0&000.Z stores ZW,WW0&00=.7cR2Dd,W,WW0&000.Z7 red is conerted to upper case ,see "ttp:--openoffice&or$-bu$Ci**a-s"o%=bu$&c$i>id?M23@0.& 2& Anot"er e3amp*e can be seen %it" bu$ 3@B1& 3& ;"i*e storin$, ZWW0,0WS"Z is c"an$ed to ZWW,00WS"Z& T"e usua* adice is to use a number format t"at does not c"an$e& Listin$ 3M0 returns t"e )D t"at identifies t"e specified format& T"e returned )D can be used to format a a*ue& )f you add a format and t"en t"e format is not aai*ab*e, ma(e note of t"e format )Dand use Listin$ 36B to disp*ay t"e formats in t"e modified form& Listing 370. +ind or create a numeric format. )#"or!at a "or!at to $ind + create& )o-oc 9 -ocu!ent to u#e& I$ o!itted= t(e current docu!ent i# u#ed& )locale 9 ,ocale to u#e& I$ o!itted= t(e de$ault locale i# u#ed& "unction "indCreateHu!ber"or!atSt.le B#"or!atF= Optional o-oc= Optional localeC -i! o-ocu!ent A# ObNect -i! a,ocale a# ne* co!&#un&#tar&lan&,ocale -i! o"or!at# A# ObNect -i! $or!atHu! A# ,on o-ocu!ent 6 II$BI#Mi##inBo-ocC= 3(i#Co!ponent= o-ocC o"or!at# 6 o-ocu!ent&etHu!ber"or!at#BC )I$ .ou c(oo#e to ;uer. on t.pe#= .ou need to u#e t(e t.pe )co!&#un&#tar&util&Hu!ber"or!at&-A3E )I could #et t(e locale $ro! :alue# #tored at )(ttp:++***&ic#&uci&edu+pub+iet$+(ttp+related+i#oA%@&txt )(ttp:++***&c(e!ie&$u9berlin&de+di:er#e+doc+ISO5%>AA&(t!l )I u#e a H0,, locale and let it u#e *(at e:er it li1e#& )"ir#t= #ee i$ t(e nu!ber $or!at exi#t# I$ B Hot I#Mi##inBlocaleCC 3(en a,ocale 6 locale End I$ $or!atHu! 6 o"or!at#&;uer.^e. B#"or!at= a,ocale= 3R0EC )M#Box "Current "or!at nu!ber i#" 4 $or!atHu! )I$ t(e nu!ber $or!at doe# not exi#t t(en add it I$ B$or!atHu! 6 9>C 3(en 424 $or!atHu! 6 o"or!at#&addHe*B#"or!at= a,ocaleC I$ B$or!atHu! 6 9>C 3(en $or!atHu! 6 7 )M#Box "ne* "or!at nu!ber i# " 4 $or!atHu! End I$ "indCreateHu!ber"or!atSt.le 6 $or!atHu! End "unction "efault formats )t is possib*e to $et formats of a specific type %it"out manua**y specifyin$ t"e format usin$ t"e $etStandard0ormat met"od on t"e 0ormats ob/ect& Specify t"e desired format usin$ t"e 4umber0ormat constant $roup& #onsider t"is snippet to set ce**s in #a*c to t"e *oca* currency format: o"or!at# 6 o-oc&Hu!ber"or!at# -i! a,ocale A# He* co!&#un&#tar&lan&,ocale oRane 6 oS(eet&etCellRaneB.Ha!eB"-':">@"C oRane&Hu!ber"or!at 6 o"or!at#&etStandard"or!atB5 co!&#un&#tar&util&Hu!ber"or!at&C0RREHCP= a,ocaleC Table 148. /onstants for the com.sun.star.util.Number+ormat constant group. Vale %ame Description 0 ALL se*ects a** number formats& 1 D20)42D se*ects on*y user9defined number formats& 2 DAT2 se*ects date formats& ! T)M2 se*ects time formats& @ #5RR24#6 se*ects currency formats& 16 45M+2R se*ects decima* number formats& 32 S#)24T)0)# se*ects scientific number formats& 6! 0RA#T)14 se*ects number formats for fractions& 12@ '2R#24T se*ects percenta$e number formats& 2A6 T2IT se*ects te3t number formats& 6 DAT2T)M2 se*ects number formats %"ic" contain date and time& 102! L1J)#AL se*ects boo*ean number formats& 20!@ 54D20)42D is used as a return a*ue if no format e3ists& 1$.11.2. Create a field master A Listing se8uence fie*d is associated to t"e com&sun&star&te3t&0ie*dMaster&Set23pression&Listin$ master fie*d, %"ic" must e3ist before t"e se8uence fie*d can be used& Listin$ 3M1 Demonstrates "o% to create a master fie*d if it does not e3ist, and "o% to $et t"e master fie*d if it does& Listing 371. /reating a master field. oMa#ter# 6 o-oc&et3ext"ieldMa#ter# I$ HO3 oMa#ter#&(a#B.Ha!eB"co!&#un&#tar&text&"ieldMa#ter&SetExpre##ion&,i#tin"C 3(en oMa#ter"ield 6 o-oc&createIn#tanceB"co!&#un&#tar&text&"ieldMa#ter&SetExpre##ion"C oMa#ter"ield&Ha!e 6 ",i#tin" 425 oMa#ter"ield&Sub3.pe 6 co!&#un&#tar&text&SetOariable3.pe&SE[0EHCE El#e oMa#ter"ield 6 oMa#ter#&etB.Ha!eB"co!&#un&#tar&text&"ieldMa#ter&SetExpre##ion&,i#tin"C End I$ T"e master fie*d sub9type determines t"e fie*d type ,see Tab*e 1!B.& Table 149. /onstants for com.sun.star.te.t.*et3ariableype. Vale Constant Description 0 com&sun&star&te3t&SetOariab*eType&OAR Simp*e ariab*e& 1 com&sun&star&te3t&SetOariab*eType&S2_524#2 4umber se8uence fie*d& 2 com&sun&star&te3t&SetOariab*eType&01RM5LA 0ormu*a fie*d& 3 com&sun&star&te3t&SetOariab*eType&STR)4J Strin$ fie*d& 1$.11.#. Insert a seCuence field T"e se8uence fie*d is created by t"e document, t"en t"e numberin$ type is set to arabic& T"e number format is set, t"e master fie*d is associated to t"e fie*d ,t"e master fie*d is a se8uence fie*d., and t"en t"e fie*d content is set to increment t"e a*ue ,Listin$ N 1.& 4ote t"at %"en t"e fie*d is inserted, t"e fie*d may not be immediate*y updated& 2it"er %ait for t"e fie*d to update, or force an update usin$ Tools > 8p&ate > +iel&s& Listing 372. /reating a set e.pression se8uence field. o"ield 6 o-oc&createIn#tanceB"co!&#un&#tar&text&3ext"ield&SetExpre##ion"C o"ield&Hu!berin3.pe 6 co!&#un&#tar&#t.le&Hu!berin3.pe&ARABIC o"ield&Hu!ber"or!at 6 "indCreateHu!ber"or!atSt.leB"LLL7"= o-ocC o"ield&attac(3ext"ieldMa#terBoMa#ter"ieldC o"ield&Content 6 na!e 4 " W >" #onstants used to set t"e numberin$ type are set as s"o%n in t"e fo**o%in$ tab*e& 426 Table 150. /onstants for com.sun.star.style.Numberingype. Vale Constant Description 0 #EARS=5''2R=L2TT2R 5pper case *etters as ZA, +, #, D, &&&Z& 1 #EARS=L1;2R=L2TT2R Lo%er case *etters as Za, b, c, e,&&&Z& 2 R1MA4=5''2R Roman numbers %it" upper case *etters as Z), )), ))), )O, &&&Z& 3 R1MA4=L1;2R Roman numbers %it" *o%er case *etters as Zi, ii, iii, i, &&&Z& ! ARA+)# Arabic numbers as Z1, 2, 3, !, &&&Z& A 45M+2R=4142 )nisib*e or no numberin$& 6 #EAR=S'2#)AL 5se a c"aracter from a specified font& M 'AJ2=D2S#R)'T1R Specified in t"e pa$e sty*e& @ +)TMA' Disp*ayed as a bitmap $rap"ic& B #EARS=5''2R=L2TT2R=4 5pper case *etters as ZA, +, &&&, 6, P, AA, ++, ##, &&& AAA, &&&Z& 10 #EARS=L1;2R=L2TT2R=4 Lo%er case *etters as Za, b, &&&, y, C, aa, bb, cc, &&& aaa, &&&Z& 11 TRA4SL)T2RAT)14 A trans*iteration modu*e %i** be used to produce numbers in c"inese, /apanese, etc& 12 4AT)O2=45M+2R)4J T"e natienumbersupp*ier serice %i** be ca**ed to produce numbers in natie *an$ua$es& 13 05LL;)DTE=ARA+)# 4umberin$ for fu**%idt" Arabic number 1! #)R#L2=45M+2R +u**et for #irc*e 4umber 1$.11.$. 6eplace text 1ith a seCuence field 0ina**y, t"e main %or(in$ macro to find t"e te3t and rep*ace it %it" a se8uence fie*d& T"e *ocation to insert t"e se8uence fie*d is found by searc"in$ for a re$u*ar e3pression& T"e re$u*ar e3pression Z^Listin$ c:di$it:d NS&c:space:dNZ searc"es for a *ine t"at be$ins %it" t"e te3t DListin$F, fo**o%ed by a space, one or more numeric di$its, a period, and one or more spaces7 for e3amp*e, DListin$ 12& F& Listing 373. Replace te.t with se8uence fields. "unction "indReplace3ext"ield#Bo-oc= na!eFC A# Inteer -i! o-e#criptor ) Searc( de#criptor u#ed to $ind t(e caption#& -i! o"ound ) 3ext !atc(in t(e #earc( de#criptor& -i! oMa#ter# ) Ma#ter $ield# in t(i# docu!ent& -i! oMa#ter"ield ) 3(e a##ociated !a#ter $ield& -i! o"ra!e ) -ocu!ent# !ain $ra!e= u#ed $or di#patc(e#& -i! o-i#patc(er ) -i#patc(er obNect& -i! oCur# ) 3ext cur#or u#ed to in#ert text content& -i! o"ield ) Se;uence $ield to in#ert& -i! $or!atHu!4 ) I- B^e.C $or t(e $or!at $or t(e $ield& -i! i A# Inteer ) Jeneral index :ariable& )A##u!e t(at no text $ield# are in#erted& "indReplace3ext"ield# 6 7 )W(at nu!ber $or!at to u#e $or t(e $ield& $or!atHu! 6 "indCreateHu!ber"or!atSt.leB"LLL7"= o-ocC 427 ) Create t(e !a#ter $ield i$ needed& oMa#ter# 6 o-oc&et3ext"ieldMa#ter# I$ HO3 oMa#ter#&(a#B.Ha!eB"co!&#un&#tar&text&"ieldMa#ter&SetExpre##ion&" 4 na!eC 3(en oMa#ter"ield 6 o-oc&createIn#tanceB"co!&#un&#tar&text&"ieldMa#ter&SetExpre##ion"C oMa#ter"ield&Ha!e 6 na!e oMa#ter"ield&Sub3.pe 6 co!&#un&#tar&text&SetOariable3.pe&SE[0EHCE El#e oMa#ter"ield 6 oMa#ter#&etB.Ha!eB"co!&#un&#tar&text&"ieldMa#ter&SetExpre##ion&" 4 na!eC End I$ )Searc( $or a line beinnin *it( t(e na!e= a #pace= a nu!ber= a period= and a #pace& o-e#criptor 6 o-oc&createSearc(-e#criptorBC Wit( o-e#criptor &Searc(Strin 6 "Z" 4 na!e 4 " X:diit:YW\&X:#pace:YW" &Searc(ReularExpre##ion 6 3rue End Wit( )Prepare to i##ue a di#patc( to clear $or!attin& o"ra!e 6 o-oc&CurrentController&"ra!e o-i#patc(er 6 create0noSer:iceB"co!&#un&#tar&$ra!e&-i#patc(Helper"C )Bein t(e $ind proce##& o"ound 6 o-oc&$ind"ir#tBo-e#criptorC -o W(ile Hot I#HullBo"oundC ) 0#e t(e #tron e!p(a#i# c(aracter #t.le $or ",i#tin 2&" o"ound&C(arSt.leHa!e 6 "OOoStronE!p(a#i#" ) Create and con$iure t(e #e;uence $ield& o"ield 6 o-oc&createIn#tanceB"co!&#un&#tar&text&3ext"ield&SetExpre##ion"C o"ield&Hu!berin3.pe 6 co!&#un&#tar&#t.le&Hu!berin3.pe&ARABIC o"ield&Hu!ber"or!at 6 $or!atHu! o"ield&attac(3ext"ieldMa#terBoMa#ter"ieldC o"ield&Content 6 na!e 4 " W >"
) Create a text cur#or *it( t(e $ound text& oCur# 6 o"ound&et3extBC&create3extCur#orB.RaneBo"oundC
) 3(e in#erted text u#e# #tron e!p(a#i#& ) Mo:e t(e cur#or bac1 one #o t(at it i# be$ore t(e #pace& ) Mu!p to t(e end o$ t(e pararap( and re#et t(e attribute#& oCur#&o,e$tB>= "al#eC 428 oCur#&otoEndo$Pararap(B3rueC o-oc&CurrentController&SelectBoCur#C o-i#patc(er&execute-i#patc(Bo"ra!e= "&uno:Re#etAttribute#"= ""= 7= Arra.BCC
) "ind t(e next occurrence& o"ound 6 o-oc&$indHextBo"ound&End= o-e#criptorC i 6 i W > ,oop "indReplace3ext"ield# 6 i End "unction T"e aboe met"od contains e3tra code t"at c*ears formattin$ after t"e main se8uence ariab*es& 1$.11.,. Create a Get6eference field An inserted se8uence fie*d is direct*y associated to a fie*d master, %"ic" may be referenced by many different fie*ds7 eery *istin$ in t"is boo( references a sin$*e fie*d master& A JetReference fie*d, "o%eer, does not reference a fie*d as easi*y& ;"en a fie*d is inserted, 11o automatica**y assi$ns a se8uence a*ue& T"e JetReference fie*d "as a Se8uence4umber attribute t"at ta(es t"e numeric Se8uenceOa*ue from t"e referenced fie*d ,see Listin$ 3M!.& T"e reference fie*d source indicates t"e type of fie*d t"at is referenced& T"e supported types are s"o%n in Tab*e 1A2& Muc" of t"is is poor*y documented, and ) specu*ate t"at t"e se8uence a*ue may be uni8ue re*atie to fie*d source& T"e Reference0ie*d'art indicates "o% t"e reference is disp*ayed& Oa*id a*ues are s"o%n in Tab*e 1A1& T"e e3amp*e in Listin$ 3M! uses t"e cate$ory and t"e number& )n a caption, a** te3t before t"e number is t"e cate$ory& Listing 374. "nserting a <etReference field. o"ield 6 o-oc&createIn#tanceB"co!&#un&#tar&text&text$ield&JetRe$erence"C o"ield&Re$erence"ieldPart 6 co!&#un&#tar&text&Re$erence"ieldPart&CA3EJORP5AH-5H0MBER o"ield&Re$erence"ieldSource 6 co!&#un&#tar&text&Re$erence"ieldSource&SE[0EHCE5"IE,- o"ield&Se;uenceHu!ber 6 oRe$erenced"ield&Se;uenceOalue o"ield&SourceHa!e 6 #Se;Ha!e o3ext&in#ert3extContentBoCur#= o"ield= 3rueC 429 Table 151. /onstants for com.sun.star.te.t.Reference+ield9art. Vale Constant Description 0 'AJ2 T"e pa$e number is disp*ayed usin$ Arabic numbers& 1 #EA'T2R T"e c"apter number is disp*ayed& 2 T2IT T"e reference te3t is disp*ayed& 3 5'=D1;4 5se *oca*iCed %ords for ZaboeZ or Zbe*o%Z& ! 'AJ2=D2S# T"e pa$e number is disp*ayed usin$ t"e numberin$ type defined in t"e pa$e sty*e of t"e reference position& A #AT2J1R6=A4D=45M+2R T"e cate$ory and t"e number of a caption is disp*ayed7 for e3amp*e, Listin$ M& 6 14L6=#A'T)14 T"e caption te3t of a caption is disp*ayed& M 14L6=S2_524#2=45M+2R T"e number of a se8uence fie*d is disp*ayed& @ 45M+2R T"e numberin$ *abe* and dependin$ of t"e reference fie*d conte3t numberin$ *abe*s of superior *ist *ee*s of t"e reference are disp*ayed& B 45M+2R=41=#14T2IT T"e numberin$ *abe* of t"e reference is disp*ayed& 10 45M+2R=05LL=#14T2IT T"e numberin$ *abe* and numberin$ *abe*s of superior *ist *ee*s of t"e reference are disp*ayed& Table 152. /onstants for com.sun.star.te.t.Reference+ield*ource. Vale Constant Description 0 R202R24#2=MAR< T"e source is a reference mar(& 1 S2_524#2=0)2LD T"e source is a number se8uence fie*d& 2 +11<MAR< T"e source is a boo(mar(& 3 011T41T2 T"e source is a footnote& ! 24D41T2 T"e source is an endnote& 1$.11... 6eplace text 1ith a Get6eference field Listin$ 3MA accepts an array of strin$s and a strin$ to find in t"e array& T"e function returns t"e inde3 of t"e strin$ in t"e array& T"e need for t"is macro is e3p*ained be*o%& Listing 375. +ind a string in an array. "unction "indStrinInArra.Bo-ata= #C A# Inteer -i! i A# Inteer "indStrinInArra. 6 9> "or i 6 ,BoundBo-ataC 3o 0BoundBo-ataC I$ o-ataBiC 6 # 3(en "indStrinInArra. 6 i Exit "unction End I$ Hext End "unction T"e inner %or(in$s of t"e main macro are described in t"e comments of t"e macro itse*f ,see Listin$ 3M6.& 430 Listing 376. Replace te.t with a <etReference field. "unction re$erenceSe;uenceOariable#Bo-oc= #Se;Ha!eC A# Inteer -i! oEnu! ) Enu!eration o$ text #ection#& -i! o"ield ) Enu!erated text $ield& -i! #F ) Jeneric #trin :ariable& -i! o"ra!e ) -ocu!ent# !ain $ra!e= u#ed $or di#patc(e#& -i! o-i#patc(er ) -i#patc(er obNect& -i! o"ield#BC ) Set expre##ion# t(at !a. be re$erenced& -i! #Pre#entation#BC ) 3ext o$ *(at i# di#pla.ed\ $or exa!ple= ",i#tin 2" -i! i A# Inteer ) ,ocation o$ a re$erence B#uc( a# ",i#tin 2"C in #Pre#entation#& -i! n A# Inteer ) Count t(e $ield#& -i! oCur# ) Cur#or u#ed to clear $or!attin& -i! o-e#criptor ) 3(e #earc( de#criptor& -i! o"ound ) 3(e $ound rane& ) -e$ault to no re$erence# created& re$erenceSe;uenceOariable# 6 7 ) Setup to per$or! a di#patc(& o"ra!e 6 o-oc&CurrentController&"ra!e o-i#patc(er 6 create0noSer:iceB"co!&#un&#tar&$ra!e&-i#patc(Helper"C ) Enu!erate t(e text $ield# and identi$. t(e appropriate #et $ield expre##ion#& ) 3(e $ield pre#entation i# t(e nu!ber a# it i# di#pla.ed& ) W(en t(i# #ection i# $ini#(ed: ) o"ield#BC 9 All t(e #et expre##ion $ield# $or t(e #peci$ied na!e& ) #Pre#entation#BC 9 Contain# t(e $ull re$erence #uc( a# ",i#tin 2" $or t(e li#tin ) #e;uence *it( t(e :alue 2& oEnu! 6 o-oc&et3ext"ield#BC&createEnu!erationBC I$ Hot I#HullBoEnu!C 3(en -o W(ile oEnu!&(a#MoreEle!ent#BC o"ield 6 oEnu!&nextEle!entBC I$ o"ield&#upport#Ser:iceB"co!&#un&#tar&text&3ext"ield&SetExpre##ion"C 3(en I$ o"ield&OariableHa!e 6 #Se;Ha!e 3(en Re-i! Pre#er:e o"ield#B7 3o nC Re-i! Pre#er:e #Pre#entation#B7 3o nC o"ield#BnC 6 o"ield #Pre#entation#BnC 6 #Se;Ha!e 4 " " 4 o"ield&CurrentPre#entation n 6 n W > End I$ End I$ ,oop End I$ ) Create t(e #earc( de#criptor to $ind all in#tance# o$ t(in# #uc( a# ",i#tin '%"& ) Oalue# in $ield# are not $ound= becau#e #earc( doe# HO3 #earc( $ield#& o-e#criptor 6 o-oc&createSearc(-e#criptorBC Wit( o-e#criptor &Searc(Strin 6 #Se;Ha!e 4 " X:diit:YW" &Searc(ReularExpre##ion 6 3rue End Wit( 431 n 6 7 o"ound 6 o-oc&$ind"ir#tBo-e#criptorC -o W(ile Hot I#HullBo"oundC ) ,oo1 $or a $ield *it( t(e text #uc( a# ",i#tin 2" i 6 "indStrinInArra.B#Pre#entation#= o"ound&etStrinBCC I$ i D6 7 3(en ) Create and con$iure t(e JetRe$erence $ield o"ield 6 o-oc&createIn#tanceB"co!&#un&#tar&text&text$ield&JetRe$erence"C o"ield&Re$erence"ieldPart 6 co!&#un&#tar&text&Re$erence"ieldPart&CA3EJORP5AH-5H0MBER o"ield&Re$erence"ieldSource 6 co!&#un&#tar&text&Re$erence"ieldSource&SE[0EHCE5"IE,- o"ield&Se;uenceHu!ber 6 o"ield#BiC&Se;uenceOalue o"ield&SourceHa!e 6 #Se;Ha!e ) Create a text cur#or *(ere t(e text *a# $ound& ) Clear t(e text= t(en in#ert t(e JetRe$erence $ield at t(at location& oCur# 6 o"ound&et3extBC&create3extCur#orB.RaneBo"oundC oCur#&#etStrinB""C o"ound&et3extBC&in#ert3extContentBoCur#= o"ield= 3rueC ) So!eti!e#= #pecial $or!attin *a# u#ed $or t(e re$erence text& ) A cur#or cannot !o:e into a $ield= #o collap#in t(e cur#or t(en #electin ) one c(aracter to t(e le$t *ill #elect t(e JetRe$erence $ield& oCur#&collap#e3oEndBC oCur#&o,e$tB>= 3rueC ) Select t(e JetRe$erence $ield on t(e di#pla.= t(en u#e a ) di#patc( to clear all attribute#& o-oc&CurrentController&#electBoCur#C o-i#patc(er&execute-i#patc(Bo"ra!e= "&uno:Re#etAttribute#"= ""= 7= Arra.BCC n 6 n W > El#e # 6 # 4 ""ailed to $ind B" 4 o"ound&etStrinBC 4 "C" 4 CHRFB>7C End I$ o"ound 6 o-oc&$indHextBo"ound&End= o-e#criptorC ,oop re$erenceSe;uenceOariable# 6 n I$ # ED "" 3(en M#box # End I$ End "unction 1$.11./. The 1orker that ties it all together T"e main %or(er macro starts by rep*acin$ captions for 0i$ure, Listin$, and Tab*e %it" se8uence ariab*es& )t is assumed, but neer erified, t"at t"e first caption is 1 and t"at t"e captions a se8uentia**y numbered as t"ey appear in t"e document %it" no $aps in numberin$& )n ot"er %ords, t"e routines are a bit fra$i*e, but t"ey %or(ed $reat for t"e documents t"at ) desired to use& My first test set about 100 captions& A** cross9references fai*ed because t"e fie*ds "ad not yet updated& After creatin$ a** se8uence fie*ds, a dispatc" causes t"e fie*ds to update so t"at t"e ne3t p"ase can be$in& 4ote t"at if t"is is not done, t"en t"e #urrent'resentation attribute on t"e se8uence fie*ds %i** be incorrect& 432 Listing 377. *et captions and references for a document. #ub replaceCaption#BC -i! o-oc ) -ocu!ent on *(ic( to operate& -i! o"ra!e ) -ocu!ent# !ain $ra!e= u#ed $or di#patc(e#& -i! o-i#patc(er ) -i#patc(er obNect& -i! i A# Inteer ) Jeneral index :ariable& -i! n A# Inteer ) Hu!ber o$ $ield# created& -i! #F ) Su!!ar. o$ *or1 per$or!ed& -i! $ield#BC ) "ield na!e# on *(ic( to operate& $ield# 6 Arra.B",i#tin"= "3able"= ""iure"C o-oc 6 3(i#Co!ponent o"ra!e 6 o-oc&CurrentController&"ra!e o-i#patc(er 6 create0noSer:iceB"co!&#un&#tar&$ra!e&-i#patc(Helper"C
"or i 6 ,BoundB$ield#BCC 3o 0BoundB$ield#BCC n 6 "indReplace3ext"ield#B3(i#Co!ponent= $ield#BiCC # 6 # 4 ""ixed " 4 n 4 " caption# $or " 4 $ield#BiC 4 CHRFB>7C Hext ) 3(i# next part *ill HO3 *or1 until a$ter all o$ t(e $ield# (a:e updated& ) So= $orce an update& o-i#patc(er&execute-i#patc(Bo"ra!e= "&uno:0pdate"ield#"= ""= 7= Arra.BCC "or i 6 ,BoundB$ield#BCC 3o 0BoundB$ield#BCC n 6 re$erenceSe;uenceOariable#B3(i#Co!ponent= $ield#BiCC # 6 # 4 "#et " 4 n 4 " re$erence# to " 4 $ield#BiC 4 CHRFB>7C Hext M#Box # End Sub 14.12. 0able of contents 0indin$ and insertin$ a tab*e of contents ,T1#. is easy un*ess you %ant to c"an$e t"e defau*ts& T"e fo**o%in$ macro c"ec(s T"is#omponent to see if t"e document contains a content inde3& REM "ind 3OC i$ it exi#t#& oIndexe# 6 3(i#Co!ponent&et-ocu!entIndexe#BC bIndex"ound 6 "al#e "or i 6 7 3o oIndexe#&etCountBC 9 > oIndex 6 oIndexe#&etB.IndexBiC I$ oIndex&#upport#Ser:iceB"co!&#un&#tar&text&ContentIndex"C 3(en bIndex"ound 6 3rue Exit "or End I$ Hext 5se dispose to remoe an e3istin$ inde3 from t"e document& ;"en ) create a T1#, ) usua**y set #reate0rom1ut*ine to true to create t"e inde3 based on t"e document out*ine sty*es ,see Listin$ 3M@.& 433 Listing 378. "nsert a standard O/ into a document. Sub In#ertA3OC REM Aut(or: Andre* Piton.a1 -i! oCur# )0#ed to in#ert t(e text content& -i! oIndexe# )All o$ t(e exi#tin indexe# -i! oIndex )3OC i$ it exi#t# and a ne* one i$ not -i! iG )"ind an exi#tin 3OC -i! bIndex"ound A# Boolean )"la to trac1 i$ t(e 3OC *a# $ound REM "ind 3OC i$ it exi#t#& oIndexe# 6 3(i#Co!ponent&et-ocu!entIndexe#BC bIndex"ound 6 "al#e "or i 6 7 3o oIndexe#&etCountBC 9 > oIndex 6 oIndexe#&etB.IndexBiC I$ oIndex&#upport#Ser:iceB"co!&#un&#tar&text&ContentIndex"C 3(en bIndex"ound 6 3rue Exit "or End I$ Hext I$ Hot bIndex"ound 3(en Print "I did not $ind an exi#tin content index" REM Create and in#ert a ne* 3OC& REM 3(e ne* 3OC !u#t be created b. t(e docu!ent t(at *ill contain t(e 3OC& oIndex 6 3(i#Co!ponent&createIn#tanceB"co!&#un&#tar&text&ContentIndex"C oIndex&Create"ro!Outline 6 3rue oCur# 6 3(i#Co!ponent&et3extBC&create3extCur#orBC oCur#&otoStartB"al#eC 3(i#Co!ponent&et3extBC&in#ert3extContentBoCur#= oIndex= "al#eC End I$ REM E:en t(e ne*l. in#erted index i# not updated until ri(t HEREK oIndex&updateBC End Sub T"e same code can be used to create a Document)nde3, #ontent)nde3, 5serDefined)nde3, )**ustration)nde3, Tab*e)nde3, or 1b/ect)nde3& 'roperties common to a** inde3 types are s"o%n in Tab*e 1A3& 434 Table 153. /ommon inde. properties. Property Description +ac(#o*or +ac($round co*or& Set to 91 for none& +ac(Jrap"ic0i*ter 0i*ter for t"e $rap"ic disp*ayed as bac($round $rap"ic& +ac(Jrap"icLocation Location of t"e bac( $rap"ic& Set usin$ t"e com&sun&star&sty*e&Jrap"icLocation constants& T"is inc*udes 4142, L20T=T1', M)DDL2=T1', R)JET=T1', L20T=M)DDL2, M)DDL2=M)DDL2, R)JET=M)DDL2, L20T=+1TT1M, M)DDL2=+1TT1M, R)JET=+1TT1M, AR2A, and T)L2D +ac(Jrap"ic5RL 5RL to t"e $rap"ic disp*ayed as a bac($round $rap"ic& ) did not e3periment %it" t"is, it may re8uire an interna* 5RL>> #reate0rom#"apter Set to True to create an inde3 based on t"e current c"apter rat"er t"an t"e entire document& )s'rotected )f true, t"e inde3 is protected and cannot be edited as part of t"e te3t& 'araSty*eEeadin$ 'ara$rap" sty*e name used for t"e "eadin$& 'araSty*eLee*1 'ara$rap" sty*e named used for *ee* 1& 4ote t"at t"ere is an attribute for *ee*s 1 t"rou$" 10& Tit*e )nde3 tit*e t"at is inserted as part of t"e T1#& ) usua**y *eae t"is b*an( and p*ace t"e tit*e before t"e T1# usin$ t"e DEeadin$ 1F para$rap" sty*e so t"at it is inc*uded as part of t"e T1#7 si**y, ) (no%& A T1# contains co*umns of data7 for e3amp*e, section numberin$, section tit*e, and pa$e number& 2ac" co*umn is represented by an array of named properties& T"e supported properties are s"o%n Tab*e 1A!& Table 154. *upported column tokens. To0en Description To(enType )dentifies t"e contents of t"e co*umn& 2ery co*umn "as a to(en type as t"e first property& To(enType property a*ues are strin$s s"o%n in Tab*e 1AA& #"aracterSty*e4ame 4ame of t"e c"aracter sty*e app*ied to t"e e*ement& Do not inc*ude for tab stops& An empty a*ue causes t"e Defau*t sty*e to be used& TabStopRi$"tA*i$ned Tab stop is ri$"t a*i$ned& 1n*y a*id for tab stops& TabStop'osition 'osition of t"e tab stop& 1n*y a*id for tab stops& TabStop0i**#"aracter 0i** c"aracter in tab stops& 1n*y a*id for tab stops& ;it"Tab )f true insert tab c"aracter& Te3t 1n*y a*id in user defined te3t& #"apter0ormat Oa*id in c"apter info and entry number on*y& T"e c"apter format is a*so mentioned in Tab*e 1!!& 0or c"apter info 45M+2R and 4AM2=45M+2R are a**o%ed and for an entry 45M+2R and D)J)T are a**o%ed& #"apterLee* Oa*id in c"apter info and entry number on*y& Denotes t"e *ee* up to %"ic" t"e c"apter information is $ien& Oa*ues permitted 1 to 10 inc*usie& Some to(en types are not supported by a** inde3 types& T"e Oa*ue is t"e strin$ name used to identify t"e to(en type& T"e 2ntry co*umn contains t"e te3t used in t"e J5) %"i*e specifyin$ t"e co*umns& )f an entry is empty, it is because ) did not erify eery type to see %"at a*ues are used and ) do not (no% t"e a*ue& 435 Table 155. *upported okenype values. Vale Entry Comment Spported Index Types To(en2ntry4umber 2W #"apter number #ontent To(en2ntryTe3t 2 2ntry te3t A** To(enTabStop T Tab stop A** To(enTe3t 5ser defined te3t To(en'a$e4umber W pa$e number A** To(en#"apter)nfo #"apter information )**ustration, Tab*e, 5ser, Tab*e of 1b/ects, and A*p"abetica* To(enEyper*in(Start LS +e$in a "yper*in( To(enEyper*in(2nd L2 2nd a "yper*in( To(en+ib*io$rap"yData0ie*d +ib*io$rap"ic data fie*d T"e macro in Listin$ 3MB inspects t"e *ee* formattin$ for t"e T1# in t"e current document and t"en inserts te3t at t"e end of t"e current document& Listing 379. "nspect the O/ in the current document. Sub In#pectCurrent3OCColu!n# )In#pect 3(i#Co!ponent -i! oCur# )0#ed to in#ert t(e text content& -i! oIndexe# )All o$ t(e exi#tin indexe# -i! oIndex )3OC i$ it exi#t# and a ne* one i$ not -i! iG )"ind an exi#tin 3OC -i! bIndex"ound A# Boolean )"la to trac1 i$ t(e 3OC *a# $ound -i! i,e:elG ) Iterate o:er t(e le:el# in t(e ,e:el"or!at propert.& -i! iColG ) Iterate o:er t(e colu!n# in eac( le:el& -i! iPropG ) Iterate o:er t(e propertie# $or a #inle colu!n& -i! o,e:el ) ,e:el obNect& -i! oCol ) Colu!n obNect& -i! #F REM "ind 3OC i$ it exi#t#& oIndexe# 6 3(i#Co!ponent&et-ocu!entIndexe#BC bIndex"ound 6 "al#e "or i 6 7 3o oIndexe#&etCountBC 9 > oIndex 6 oIndexe#&etB.IndexBiC I$ oIndex&#upport#Ser:iceB"co!&#un&#tar&text&ContentIndex"C 3(en bIndex"ound 6 3rue Exit "or End I$ Hext I$ Hot bIndex"ound 3(en Exit Sub End I$
# 6 ",e:el" 4 CHRFB@C 4 "Colu!n" 4 CHRFB@C 4 "Propert." 4 CHRFB@C 4 "Ha!e" 4 5 CHRFB@C 4 "Oalue" 4 CHRFB>%C "or i,e:el 6 7 3o oIndex&,e:el"or!at&etCountBC 9 > 436 o,e:el 6 oIndex&,e:el"or!at&etB.IndexBi,e:elC "or iCol 6 ,BoundBo,e:elC 3o 0BoundBo,e:elC oCol 6 o,e:elBiColC "or iProp 6 ,BoundBoColC 3o 0BoundBoColC # 6 # 4 i,e:el 4 CHRFB@C 4 iCol 4 CHRFB@C 4 iProp 4 CHRFB@C 4 5 oColBiPropC&Ha!e 4 CHRFB@C 4 oColBiPropC&Oalue 4 CHRFB>%C Hext Hext Hext 3(i#Co!ponent&et3extBC&in#ertStrinB3(i#Co!ponent&et3extBC&End= #= "al#eC End Sub ) ran t"e macro in Listin$ 3MB %it" 11o ersion 3&3&0 and noticed t"at *ee* 0 contains no entries, and *ee*s 1 H 10 are identica*& T"e output for *ee* 1 is s"o%n in Tab*e 1A6& #o*umn 0 is t"e To(en2ntry4umber formatted %it" t"e Defau*t c"aracter sty*e& )n t"e T1#, t"is is t"e c"apter numberin$& A "yper*in( be$ins in co*umn 1, and it is formatted usin$ t"e D)nternet Lin(F c"aracter sty*e& #o*umn 2 contains t"e "eadin$ te3t& 4o c"aracter sty*e is proided, but it is formatted usin$ t"e D)nternet Lin(F sty*e because it is inc*uded in t"e "yper*in(& #o*umn 3 specifies t"e end of t"e "yper*in(, so t"e "yper*in( inc*udes on*y t"e "eadin$ te3t& #o*umn ! specifies a ri$"t a*i$ned tab stop t"at fi**s t"e empty space bet%een t"e "eadin$ te3t and t"e pa$e number %it" periods& #o*umn A contains t"e pa$e number& Table 156. Level format for level (. Level Colmn Property %ame Vale 1 0 0 To(enType To(en2ntry4umber 1 0 1 #"aracterSty*e4ame 1 1 0 To(enType To(enEyper*in(Start 1 1 1 #"aracterSty*e4ame )nternet *in( 1 2 0 To(enType To(en2ntryTe3t 1 2 1 #"aracterSty*e4ame 1 3 0 To(enType To(enEyper*in(2nd 1 ! 0 To(enType To(enTabStop 1 ! 1 TabStopRi$"tA*i$ned TR52 1 ! 2 TabStop0i**#"aracter & 1 ! 3 #"aracterSty*e4ame 1 ! ! ;it"Tab TR52 1 A 0 To(enType To(en'a$e4umber 1 A 1 #"aracterSty*e4ame 437 ;"i*e creatin$ a T1# manua**y, t"e co*umns are edited to inc*ude t"in$s suc" as c"apter numbers, c"apter te3t, "yper*in( start, "yper*in( end, pa$e number, and ot"er t"in$s& T"ese a*ues are stored in t"e Lee*0ormat property& Listing 380. "nsert a O/ with hyperlinks. Sub In#ertA3OCWit(H.perlin1# REM Aut(or: Andre* Piton.a1 -i! oCur# )0#ed to in#ert t(e text content& -i! oIndexe# )All o$ t(e exi#tin indexe#& -i! oIndex )3OC i$ it exi#t# and a ne* one i$ not& -i! iG )"ind an exi#tin 3OC& -i! bIndex"ound A# Boolean )"la to trac1 i$ t(e 3OC *a# $ound& -i! i,e:el REM "ind 3OC i$ it exi#t#& oIndexe# 6 3(i#Co!ponent&et-ocu!entIndexe#BC bIndex"ound 6 "al#e "or i 6 7 3o oIndexe#&etCountBC 9 > oIndex 6 oIndexe#&etB.IndexBiC I$ oIndex&#upport#Ser:iceB"co!&#un&#tar&text&ContentIndex"C 3(en bIndex"ound 6 3rue Exit "or End I$ Hext I$ Hot bIndex"ound 3(en REM Create and in#ert a ne* 3OC& REM 3(e ne* 3OC !u#t be created b. t(e docu!ent t(at *ill contain t(e 3OC& oIndex 6 3(i#Co!ponent&createIn#tanceB"co!&#un&#tar&text&ContentIndex"C oIndex&Create"ro!Outline 6 3rue
oCur# 6 3(i#Co!ponent&et3extBC&create3extCur#orBC oCur#&otoRaneB3(i#Co!ponent&CurrentController&Oie*Cur#or= "al#eC 3(i#Co!ponent&et3extBC&in#ert3extContentBoCur#= oIndex= "al#eC End I$ REM E:en t(e ne*l. in#erted index i# not updated until ri(t HEREK oIndex&updateBC End Sub "unction Create3OCColu!nEntrie#BC -i! o o 6 Arra.B Arra.BMa1ePropert.B"3o1en3.pe"= "3o1enEntr.Hu!ber"C= 5 Ma1ePropert.B"C(aracterSt.leHa!e"= ""CC= 5 Arra.BMa1ePropert.B"3o1en3.pe"= "3o1enH.perlin1Start"C= 5 Ma1ePropert.B"C(aracterSt.leHa!e"= "Internet lin1"CC= 5 Arra.BMa1ePropert.B"3o1en3.pe"= "3o1enEntr.3ext"C= 5 Ma1ePropert.B"C(aracterSt.leHa!e"= ""CC= 5 438 Arra.BMa1ePropert.B"3o1en3.pe"= "3o1enH.perlin1End"CC= 5 Arra.BMa1ePropert.B"3o1en3.pe"= "3o1en3abStop"C= 5 Ma1ePropert.B"3abStopRi(tAlined"= 3R0EC= 5 Ma1ePropert.B"3abStop"illC(aracter"= "&"C= 5 Ma1ePropert.B"C(aracterSt.leHa!e"= ""C= 5 Ma1ePropert.B"Wit(3ab"= 3R0ECC= 5 Arra.BMa1ePropert.B"3o1en3.pe"= "3o1enPaeHu!ber"C= 5 Ma1ePropert.B"C(aracterSt.leHa!e"= ""CCC Create3OCColu!nEntrie#BC 6 o End "unction "unction Ma1ePropert.B#Ha!eF= :alueC -i! oProp oProp 6 CreateObNectB"co!&#un&#tar&bean#&Propert.Oalue"C oProp&Ha!e 6 #Ha!e oProp&Oalue 6 :alue Ma1ePropert. 6 oProp End "unction 14.13. Conclusion A*t"ou$" t"is c"apter didnGt coer eery ob/ect and capabi*ity supported by ;riter, it did discuss t"e capabi*ities most fre8uent*y 8uestioned on t"e mai*in$ *ists& Many of t"e tec"ni8ues demonstrated in t"is c"apter are representatie of t"e tec"ni8ues t"at are re8uired for ob/ects not discussed& 0or e3amp*e, a** ob/ects supportin$ named access are retrieed in t"e same manner& 5se t"e materia* coered "ere as a startin$ point in your e3p*oration of ;riter documents in 1pen1ffice&or$& 439 1,. Calc (ocuments T"e primary purpose of a #a*c document is to contain mu*tip*e spreads"eets, %"ic" in turn contain ro%s and co*umns of data L in ot"er %ords, tab*es& T"is c"apter introduces appropriate met"ods to manipu*ate, traerse, format, and modify t"e content contained in a #a*c document& 1pen1ffice&or$ supports t"ree primary tab*e types: te3t tab*es in ;riter documents, database tab*es, and spreads"eets in #a*c documents& 2ac" of t"e different tab*e types is tai*ored for a specific purpose& Te3t tab*es in ;riter documents support comp*e3 te3t formattin$ but on*y simp*e tab*e ca*cu*ations& Spreads"eet documents, on t"e ot"er "and, support comp*e3 ca*cu*ations and on*y simp*e te3t formattin$& #onceptua**y, a** document types "ae t%o components: t"e data t"ey contain and t"e contro**er t"at determines "o% t"e data is disp*ayed& )n 1pen1ffice&or$, t"e co**ection of data contained in a document is ca**ed t"e model& 2ac" mode* "as a contro**er t"at is responsib*e for t"e isua* presentation of t"e data& T"e contro**er (no%s t"e *ocation of t"e isib*e te3t cursor and t"e current pa$e, and (no%s %"at is current*y se*ected& 2ery #a*c document supports t"e com&sun&star&s"eet&Spreads"eetDocument serice& ;"en ) %rite a macro t"at must be user9friend*y and re8uires a spreads"eet document, ) erify t"at t"e document is t"e correct type by usin$ t"e ob/ect met"od supportsSerice,.& See Listin$ 3@1& Listing 381. /alc documents support the com.sun.star.sheet.*preadsheet#ocument service. REM A tric1 i# u#ed to a:oid a bu in OOo& REM 3(i# $unction te#t# t(e aru!ent to #ee i$ it #upport# a #er:ice& REM I$ t(e obNect doe# not #upport a #er:ice= a runti!e error REM occur# t(at co!plain# t(at t(e :ariable i# not #et& REM A##inin t(e aru!ent to a te!porar. :ariable and REM u#in t(at to call Support#Ser:ice a:oid# t(e error& "unction i#Calc-ocu!entBo-ocC A# Boolean On Error Joto ErrorMu!pPoint -i! #F : #F 6 "co!&#un&#tar&#(eet&Spread#(eet-ocu!ent" -i! o-oc3e!p : o-oc3e!p 6 o-oc i#Calc-ocu!ent 6 "al#e I$ o-oc&Support#Ser:iceB#FC 3(en i#Calc-ocu!ent 6 3rue End I$ ErrorMu!pPoint: End "unction An interface defines a series of met"ods& )f an ob/ect imp*ements an interface, it imp*ements eery met"od defined by t"at interface& A serice defines an ob/ect by specifyin$ t"e interfaces t"at it imp*ements, t"e properties t"at it contains, and t"e ot"er serices t"at it e3ports& A serice indirect*y specifies t"e imp*emented met"ods by specifyin$ interfaces& T"e interfaces supported by t"e #a*cDocument serice proide a $ood oerie% of t"e proided functiona*ity ,see Tab*e 1AM.& 440 Table 157. *ome interfaces supported by /alc documents. Service Description com&sun&star&document&IActionLoc(ab*e Temporari*y *oc( t"e document from user interaction and automatic ce** updates& Loc(in$ an ob/ect ma(es it possib*e to preent interna* ob/ect updates %"i*e you 8uic(*y c"an$e mu*tip*e parts of t"e ob/ects t"at mi$"t temporari*y ina*idate eac" ot"er& com&sun&star&dra%in$&IDra%'a$esSupp*ier Access a** dra% pa$es in t"is document7 t"ere is one dra% pa$e for eac" contained s"eet& com&sun&star&s"eet&I#a*cu*atab*e #ontro* automatic ca*cu*ation of ce**s& com&sun&star&s"eet&I#onso*idatab*e 'erform data conso*idation& com&sun&star&s"eet&IJoa*See( 'erform a DJoa* See(F for a ce**& com&sun&star&s"eet&ISpreads"eetDocument Access t"e contained spreads"eets& com&sun&star&sty*e&ISty*e0ami*iesSupp*ier Access t"e contained sty*es by type& com&sun&star&uti*&I4umber0ormatsSupp*ier Access t"e number formats& com&sun&star&uti*&I'rotectab*e 'rotect and unprotect t"e document& T"e create4e%#a*cDoc function is used to create a ne% empty #a*c document& T"is met"od is used by ot"er met"ods in t"is c"apter& Listing 382. /reate a new /alc document. "unction createHe*Calc-oc -i! noAr#BC )An e!pt. arra. $or t(e aru!ent# -i! #0R, A# Strin )0R, o$ t(e docu!ent to load -i! o-oc #0R, 6 "pri:ate:$actor.+#calc" o-oc 6 Star-e#1top&,oadCo!ponent"ro!0rlB#0R,= "5blan1"= 7= noAr#BCC createHe*Calc-oc 6 o-oc End "unction 1.1. 2ccessing sheets T"e primary purpose of a spreads"eet document is to act as a container for indiidua* s"eets t"rou$" t"e ISpread"seetDocument interface& T"e ISpreads"eetDocument interface defines t"e sin$*e met"od $etS"eets,. t"at returns a Spreads"eets ob/ect used to manipu*ate t"e indiidua* s"eets ,see Listin$ 3@3.& Listing 383. Obtain a com.sun.star.sheet.*preadsheets service using a method or a property. 3(i#Co!ponent&etS(eet#BC )Met(od de$ined b. /Spread#(eet-ocu!ent inter$ace& 3(i#Co!ponent&S(eet# )Propert. o$ t(e #pread#(eet docu!ent& T"e Spreads"eet serice a**o%s t"e indiidua* s"eets to be returned by inde3, by enumeration, and by name ,see Tab*e 1A@.& T"e Spreads"eets serice a*so a**o%s s"eets to be created, moed, and de*eted& Many of t"e met"ods s"o%n in Tab*e 1A@ are demonstrated in Listin$ 3@!& Table 158. Methods implemented by the com.sun.star.sheet.*preadsheets service. )et6od Description copy+y4ame, src4ame, dest4ame, inde3 . #opy t"e s"eet named src4am to t"e specified inde3 and name it dest4ame& 441 )et6od Description create2numeration,. #reate an ob/ect t"at enumerates t"e spreads"eets& $et+y)nde3,inde3. 1btain a spreads"eet based on t"e s"eetGs inde3& $et+y4ame,name. 1btain a spreads"eet based on t"e s"eetGs name& $et#ount,. Return t"e number of s"eets as a Lon$ )nte$er& "as+y4ame,name. Return True if t"e named spreads"eet e3its& "as2*ements,. Return True if t"e document contains at *east one spreads"eet& insert4e%+y4ame,name, inde3. #reate a ne% spreads"eet and insert it at t"e specified *ocation %it" t"e supp*ied name& moe+y4ame,name, inde3. Moe t"e named spreads"eet to t"e specified inde3& remoe+y4ame,name. Remoe t"e named spreads"eet& Listing 384. Manipulate sheets in a /alc document. Sub Acce##S(eet# -i! oS(eet# )3(e #(eet# obNect t(at contain# all o$ t(e #(eet# -i! oS(eet )Indi:idual #(eet -i! oS(eetEnu! )"or acce##in b. enu!eration -i! # A# Strin )Strin :ariable to (old te!porar. data -i! i A# Inteer )Index :ariable -i! o-oc
o-oc 6 createHe*Calc-ocBC oS(eet# 6 o-oc&S(eet#
REM In#ert ne* #(eet a# t(e #econd #(eet& oS(eet#&in#ertHe*B.Ha!eB"CreatedS(eet"= >C
REM Create a ne* #(eet na!ed ""ir#t" at t(e #tart& oS(eet#&in#ertHe*B.Ha!eB""ir#t"= 7C REM Oeri$. t(at t(e #(eet na!ed "S(eet'" exi#t# I$ oS(eet#&(a#b.Ha!eB"S(eet%"C 3(en oS(eet 6 oS(eet#&etB.Ha!eB"S(eet%"C oS(eet&etCellB.Po#itionB7= 7C&#etStrinB"3e#t"C
REM Cop. "S(eet%" to t(e end& 3(at i# cop.= not !o:eK oS(eet#&cop.B.Ha!eB"S(eet%"= "Cop.>"= oS(eet#&etCountBCC End I$
I$ oS(eet#&(a#b.Ha!eB"S(eet>"C 3(en oS(eet#&re!o:eB.Ha!eB"S(eet>"C End I$
REM 3(e #(eet# are indexed #tartin at 8ero= but etCountBC indicate# REM exactl. (o* !an. #(eet# t(ere are& "or i 6 7 3o oS(eet#&etCountBC9> 442 # 6 # 4 "S(eet " 4 i 4 " 6 " 4 oS(eet#&etB.IndexBiC&Ha!e 4 CHRFB>7C Hext M#box #= 7= "A$ter In#ertin He* S(eet#"
REM Ho* re!o:e t(e ne* #(eet# t(at I in#erted oS(eet#&re!o:eB.Ha!eB""ir#t"C oS(eet#&re!o:eB.Ha!eB"Cop.>"C # 6 "" : i 6 7 oS(eetEnu! 6 oS(eet#&createEnu!erationBC -o W(ile oS(eetEnu!&(a#MoreEle!ent#BC oS(eet 6 oS(eetEnu!&nextEle!entBC # 6 # 4 "S(eet " 4 i 4 " 6 " 4 oS(eet&Ha!e 4 CHRFB>7C i 6 i W > ,oop M#box #= 7= "A$ter -eletin S(eet#" End Sub 1.2. /heet cells contain the data A spreads"eet document contains indiidua* s"eets t"at are composed of ro%s and co*umns of ce**s& 2ac" co*umn is *abe*ed a*p"abetica**y startin$ %it" t"e *etter A, and eac" ro% is *abe*ed numerica**y startin$ %it" t"e number 1& A ce** can be identified by its name, %"ic" uses t"e co*umn *etter and t"e ro% number, or by its position& T"e upper9*eft ce** is DA1F at position ,0, 0. and ce** D+3F is at *ocation ,1, 2.& T"e #a*c user interface identifies ce**s %it" names suc" as DS"eet2:DAF& A ce**, on t"e ot"er "and, identifies itse*f by t"e ro% and co*umn offset, %"ic" re8uires a bit of %or( to turn into "uman9readab*e form& T"e #e**Address#onersion serice conerts a ce** address into "uman readab*e form& T"e #e**Address#onersion serice is not yet documented, so ) performed some tests& ;"en a ce** address is assi$ned to t"e Address property ,See Listin$ 3@A., t"e 'ersistentRepresentation property is set to t"e fu** ce** name inc*udin$ t"e s"eet name& T"e 5ser)nterfaceRepresentation property, "o%eer, contains t"e s"eet name on*y if t"e ce** is not contained in t"e actie s"eet& Listing 385. Obtain the cell name using the /ell-ddress/onversion service. -i! oCon: -i! oCell oCon: 6 o-oc&createIn#tanceB"co!&#un&#tar&table&CellAddre##Con:er#ion"C oCell 6 3(i#Co!ponent&S(eet#B'C&etCellB.Po#itionB7= 7C )Cell A> oCon:&Addre## 6 oCell&etCellAddre##BC Print oCon:&0#erInter$aceRepre#entation )A> print oCon:&Per#i#tentRepre#entation )S(eet>&A> ) "ad difficu*ty %it" t"e #e**Address#onersion serice, so ) opted to %rite my o%n& T"e fo**o%in$ met"od accepts t"e s"eet number, co*umn, and ro%, and returns an address& T"e Dc"eatF t"at ) used, is to assume t"at t"e s"eet name is formatted as S"eet1, S"eet2, etc& T"is is triia* to c"an$e, but ) opted to not do it& T"e on*y tric(y part is to understand t"at co*umns are *abe*ed usin$ +ase 26 %"ere t"e di$its are A9P and not 09B7 and bein$ enou$" of a tec"nica* person to understand %"at t"at means& Listing 386. +ormat a single cell address assuming all sheets are named *heet. "unction Addre##StrinBiS(eet A# ,on= iCol A# ,on= iRo* A# ,on= bW*it(S(eet A# BooleanC -i! i -i! #F -o 443 # 6 CHRFBBiCol MO- 'AC W A<C 4 # iCol 6 iCol \ 'A ,oop 0ntil iCol 6 7 I$ bW*it(S(eet 3(en Addre##Strin 6 "S(eet" 4 CStrBiS(eet W >C 4 "&" 4 # 4 CStrBiRo* W >C El#e Addre##Strin 6 # 4 CStrBiRo* W >C End I$ End "unction T"is ne3t function accepts a ran$e address& Listing 387. +ormat a single range address assuming all sheets are named *heet. "unction prett.RaneAddre##Ha!eBoRaneAddrC -i! #>F= #'F -i! oCon: -i! oCellAddr A# He* co!&#un&#tar&table&CellAddre##
#> 6 Addre##StrinBoRaneAddr&S(eet= oRaneAddr&StartColu!n= oRaneAddr&StartRo*= 3rueC #' 6 Addre##StrinBoRaneAddr&S(eet= oRaneAddr&EndColu!n= oRaneAddr&EndRo*= "al#eC prett.RaneAddre##Ha!e 6 #> 4 ":" 4 #' End "unction 1,.2.1. Cell address )n 11o, a ce**Gs address is specified by t"e s"eet t"at contains t"e ce**, and t"e ro% and co*umn in %"ic" t"e ce** is *ocated& 11o encapsu*ates a ce**Gs address in a #e**Address structure ,see Tab*e 1AB.& T"e #e**Address structure is aai*ab*e direct*y from a ce** and it is a*so used as an ar$ument to numerous ob/ect met"ods& Table 159. 9roperties of the com.sun.star.table./ell-ddress structure. Property Description S"eet S"ort )nte$er inde3 of t"e s"eet t"at contains t"e ce**& #o*umn Lon$ )nte$er inde3 of t"e co*umn %"ere t"e ce** is *ocated& Ro% Lon$ )nte$er inde3 of t"e ro% %"ere t"e ce** is *ocated& 1,.2.2. Cell data A ce** can contain four types of data& 5se t"e met"od $etType,. to find out t"e type of data t"at it contains& A ce** t"at contains no data is considered empty& A ce** can contain a f*oatin$9point Doub*e a*ue& 5se t"e ob/ect met"ods $etOa*ue,. and setOa*ue,Doub*e. to $et and set a ce**Gs a*ue& Tip )f t"e ce** contains a formu*a, you can sti** determine t"e type of data t"at is stored in t"e ce** from t"e 0ormu*aResu*tType property s"o%n in Tab*e 163& A ce** can contain te3tua* data& T"e standard met"od of $ettin$ and settin$ te3tua* data is to use t"e met"ods $etStrin$,. and setStrin$,Strin$.& T"e rea* story, "o%eer, is t"at t"e com&sun&star&tab*e&#e** serice imp*ements t"e com&sun&star&te3t&ITe3t interface& T"e ITe3t interface is t"e primary te3t interface used in ;riter documents, and it a**o%s indiidua* ce**s to contain ery comp*e3 data& 444 Tip S"eet ce**s support t"e com&sun&star&te3t&ITe3t interface& )t s"ou*d come as no surprise, t"erefore, t"at s"eets a*so support t"e com&sun&star&te3t&ITe3t0ie*dsSupp*ier interface L in case you %ant to insert specia* te3t fie*ds into a ce**& A ce** can contain a formu*a& T"e met"ods $et0ormu*a,. and set0ormu*a,Strin$. $et and set a ce**Gs formu*a& To determine if a formu*a contains an error, use t"e $et2rror,. met"od L t"e Lon$ )nte$er return a*ue is Cero if t"ere is no error& T"e macro in Listin$ 3@@ demonstrates "o% to inspect a ce**Gs type& Tip ;"en settin$ a ce**Gs formu*a, you must inc*ude t"e *eadin$ e8ua*s si$n ,?. and t"e formu*a must be in 2n$*is"& To set a formu*a usin$ your o%n *oca* *an$ua$e, use t"e 0ormu*aLoca* property s"o%n in Tab*e 163& Listing 388. <et a string representation of the cell type. "unction JetCell3.peBoCellC A# Strin Select Ca#e oCell&et3.peBC Ca#e co!&#un&#tar&table&CellContent3.pe&EMP3P JetCell3.pe 6 "E!pt." Ca#e co!&#un&#tar&table&CellContent3.pe&OA,0E JetCell3.pe 6 "Oalue" Ca#e co!&#un&#tar&table&CellContent3.pe&3E/3 JetCell3.pe 6 "3ext" Ca#e co!&#un&#tar&table&CellContent3.pe&"ORM0,A JetCell3.pe 6 ""or!ula" Ca#e El#e JetCell3.pe 6 "0n1no*n" End Select End "unction Listin$ 3@B demonstrates "o% to $et and set information in a ce**& A numeric a*ue, a strin$, and a formu*a are set in a ce**& After settin$ eac" type, information is printed about t"e ce** ,see 0i$ure B6.& T"e macro in Listin$ 3@B is ery simp*e but it demonstrates some ery important be"aior& )nspect t"e output in 0i$ure B6 to see %"at is returned by $etStrin$,., $etOa*ue,., and $et0ormu*a,. for eac" different ce** content type& Listing 389. <et cell information. "unction Si!pleCellIn$oBoCellC A# Strin -i! # A# Strin Si!pleCellIn$o 6 oCell&Ab#oluteHa!e 4 " (a# t.pe " 45 JetCell3.peBoCellC 4 " StrinB" 4 oCell&etStrinBC 4 "C OalueB" 45 oCell&etOalueBC 4 "C "or!ulaB" 4 oCell&et"or!ulaBC 4 "C" End "unction Sub JetSetCell# -i! oCell -i! # A# Strin -i! o-oc
o-oc 6 createHe*Calc-ocBC oCell 6 o-oc&S(eet#B7C&etCellB.Po#itionB7= 7C )Cell A> oCell&#etStrinB"And."C 445 oCell 6 o-oc&S(eet#B7C&etCellB.Po#itionB>7?= 7C )Cell -A> # 6 Si!pleCellIn$oBoCellC 4 CHRFB>7C oCell&#etOalueB'%&'C # 6 # 4 Si!pleCellIn$oBoCellC 4 CHRFB>7C oCell&#etStrinB"?"C # 6 # 4 Si!pleCellIn$oBoCellC 4 CHRFB>7C oCell&#et"or!ulaB"6A>"C # 6 # 4 Si!pleCellIn$oBoCellC 4 CHRFB>7C oCell&#et"or!ulaB""C # 6 # 4 Si!pleCellIn$oBoCellC 4 CHRFB>7C End Sub +igure 1G. 3alues returned by getype67) get*tring67) get3alue67) and get+ormula67 for different types of content. Tip T"e met"ods $etStrin$,. and $et0ormu*a,. return re*eant a*ues een %"en t"e ce** type is not Strin$ or 0ormu*a ,see 0i$ure B6.& 4otice a*so t"at settin$ a strin$ a*ue of ! does not set a numeric a*ue, and t"e formu*a een s"o%s a sin$*e 8uotation mar( in front of t"e D!F& T"is proides a pretty $ood c*ue t"at you can a*so do t"in$s suc" as set0ormu*a,ZV) am te3tZ. to set te3t& 1,.2.#. Cell properties #e**s contained in a s"eet are defined by t"e com&sun&star&s"eet&S"eet#e** serice, %"ic" supports numerous properties for formattin$ t"e ce** contents& Jien t"at a ce** a*so supports t"e Te3t serice, it is of no surprise t"at it a*so supports properties re*ated to te3t content: #"aracter'roperties, #"aracter'ropertiesAsian, #"aracter'roperties#omp*e3, and 'ara$rap"'roperties& T"ere are a*so ce**9specific properties suc" as settin$ border *ines& 6ou specify t"e border *ines for ce**s by usin$ a +orderLine structure as s"o%n in Tab*e 160& T"e +orderLine structure defines "o% a sin$*e border *ine is disp*ayed, and t"e Tab*e+order structure defines "o% t"e *ines in an entire tab*e are disp*ayed ,see Tab*e 161.& Table 160. 9roperties of the com.sun.star.table.!orderLine structure. Property Description #o*or Line co*or as a Lon$ )nte$er& )nnerLine;idt" ;idt" of t"e inner part of a doub*e *ine ,in 0&01 mm. as a S"ort )nte$er L Cero for a sin$*e *ine& 1uterLine;idt" ;idt" of a sin$*e *ine, or %idt" of t"e outer part of a doub*e *ine ,in 0&01 mm. as a S"ort )nte$er& LineDistance Distance bet%een t"e inner and outer parts of a doub*e *ine ,in 0&01 mm. as a S"ort )nte$er& Table 161. 9roperties of the com.sun.star.table.able!order structure. Property Description TopLine Line sty*e at t"e top ed$e ,see Tab*e 160.& )sTopLineOa*id )f True, t"e TopLine is used %"en settin$ a*ues& 446 Property Description +ottomLine Line sty*e at t"e bottom ed$e ,see Tab*e 160.& )s+ottomLineOa*id )f True, t"e +ottomLine is used %"en settin$ a*ues& LeftLine Line sty*e at t"e *eft ed$e ,see Tab*e 160.& )sLeftLineOa*id )f True, t"e LeftLine is used %"en settin$ a*ues& Ri$"tLine Line sty*e at t"e ri$"t ed$e ,see Tab*e 160.& )sRi$"tLineOa*id )f True, t"e Ri$"tLine is used %"en settin$ a*ues& EoriConta*Line Line sty*e for "oriConta* *ines bet%een ce**s ,see Tab*e 160.& )sEoriConta*LineOa*id )f True, t"e EoriConta*Line is used %"en settin$ a*ues& Oertica*Line Line sty*e for ertica* *ines bet%een ce**s ,see Tab*e 160.& )sOertica*LineOa*id )f True, t"e Oertica*Line is used %"en settin$ a*ues& Distance Distance bet%een t"e *ines and ot"er contents as a S"ort )nte$er& )sDistanceOa*id )f True, t"e Distance is used %"en settin$ a*ues& ;"en settin$ a*ues in a Tab*e+order structure, not a** a*ues are a*%ays re8uired& 0or e3amp*e, %"en usin$ a Tab*e+order structure to confi$ure a ce**Gs border, t"e indiidua* a*ues are used on*y if t"e correspondin$ D)s&&&Oa*idF property is set& T"is proides t"e abi*ity to set a sin$*e a*ue and *eae t"e ot"er a*ues unc"an$ed& )f, on t"e ot"er "and, a Tab*e+order structure is obtained by usin$ a 8uery ,meanin$ you $et t"e a*ue., t"e f*a$s indicate t"at not a** *ines use t"e same a*ue& Tab*e 162 contains ce**9specific properties& #e** properties use t"e Tab*e+order structure to set t"e border types& Table 162. 9roperties supported by the com.sun.star.table./ell9roperties service. Property Description #e**Sty*e 1ptiona* property7 t"e name of t"e sty*e of t"e ce** as a Strin$& #e**+ac(#o*or T"e ce** bac($round co*or as a Lon$ )nte$er ,see )s#e**+ac($roundTransparent.& )s#e**+ac($roundTransparent )f True, t"e ce** bac($round is transparent and t"e #e**+ac(#o*or is i$nored& EoriKustify T"e ce**Gs "oriConta* a*i$nment as a com&sun&star&tab*e&#e**EoriKustify enum: STA4DARD H Defau*t a*i$nment is *eft for numbers and ri$"t for te3t& L20T H #ontent is a*i$ned to t"e ce**Gs *eft ed$e& #24T2R H #ontent is "oriConta**y centered& R)JET H #ontent is a*i$ned to t"e ce**Gs ri$"t ed$e& +L1#< H #ontent is /ustified to t"e ce**Gs %idt"& R2'2AT H #ontent is repeated to fi** t"e ce** ,but t"is doesnGt seem to %or(.& OertKustify T"e ce**Gs ertica* a*i$nment as a com&sun&star&tab*e&#e**OertKustify enum: STA4DARD H 5se t"e defau*t& T1' H A*i$n to t"e upper ed$e of t"e ce**& #24T2R H A*i$n to t"e ertica* midd*e of t"e ce**& +1TT1M H A*i$n to t"e *o%er ed$e of t"e ce**& )sTe3t;rapped )f True, t"e ce**Gs content is automatica**y %rapped at t"e ri$"t border& 'ara)ndent T"e indentation of t"e ce**Gs content ,in 0&01 mm. as a S"ort )nte$er& 447 Property Description 1rientation )f t"e RotateAn$*e is Cero, t"is specifies t"e orientation of t"e ce**Gs content as an enum of type com&sun&star&tab*e&#e**1rientation: STA4DARD H T"e ce**Gs content is disp*ayed from *eft to ri$"t& T1'+1TT1M H T"e ce**Gs content is disp*ayed from top to bottom& +1TT1MT1' H T"e ce**Gs content is disp*ayed from bottom to top& STA#<2D H Same as T1'+1TT1M but eac" c"aracter is "oriConta*& RotateAn$*e Defines "o% muc" to rotate t"e ce**Gs content ,in 0&01 de$rees. as a Lon$ )nte$er& T"e entire strin$ is rotated as one unit rat"er t"an as indiidua* c"aracters& RotateReference Defines t"e ed$e %"ere rotated ce**s are a*i$ned usin$ t"e same enum as OertKustify& AsianOertica*Mode )f True, on*y Asian c"aracters use a ertica* orientation& )n ot"er %ords, in Asian mode on*y Asian c"aracters are printed in "oriConta* orientation if t"e 1rientation property is STA#<2D7 for ot"er orientations, t"is a*ue is not used& Tab*e+order Description of the cell or cell range border (see Tab*e 161). When used with a single cell, the values set the borders for the single cell. When used with a range of cells, the borders are for the outer edges of the range rather than the individual cells. Top+order Description of the cell's top border line (see Tab*e 160). +ottom+order Description of the cell's bottom border line (see Tab*e 160). Left+order Description of the cell's left border line (see Tab*e 160). Ri$"t+order Description of the cell's right border line (see Tab*e 160). 4umber0ormat )nde3 of t"e ce**Gs number format& T"e proper a*ue can be determined by usin$ t"e com&sun&star&uti*&I4umber0ormatter interface supported by t"e document& S"ado%0ormat Defines t"e s"ado% format usin$ a com&sun&star&tab*e&S"ado%0ormat structure: Location H T"e s"ado%Gs *ocation as a com&sun&star&tab*e&S"ado%Location enum %it" a*id a*ues of 4142, T1'=L20T, T1'=R)JET, +1TT1M=L20T, and +1TT1M=R)JET& S"ado%;idt" H T"e s"ado%Gs siCe as a S"ort )nte$er& )sTransparent H )f True, t"e s"ado% is transparent& #o*or H T"e s"ado%Gs co*or as a Lon$ )nte$er& #e**'rotection Defines t"e ce**Gs protection as a com&sun&star&uti*&#e**'rotection structure: )sLoc(ed f True, t"e ce** is *oc(ed from modifications by t"e user& )s0ormu*aEidden f True, t"e formu*a is "idden from t"e user& )sEidden f True, t"e ce** is "idden from t"e user& )s'rintEidden f True, t"e ce** is "idden on printouts& 5serDefinedAttributes T"is property is used to store additiona* attributes in a com&sun&star&container&I4ame#ontainer interface& )n $enera*, t"e process of settin$ ce** attributes is ery simp*e& T"e macro in Listin$ 3B0 demonstrates some of t"e properties in Tab*e 162 by settin$ t"e te3t of ce** +1 to DEe**oF, centerin$ t"e te3t, and t"en rotatin$ t"e te3t 30 de$rees counterc*oc(%ise& Listing 390. /enter >&elloA and rotate it FC degrees. Sub RotateCell3ext -i! oCell -i! o-oc
448 o-oc 6 createHe*Calc-ocBC oCell 6 o-oc&S(eet#B7C&etCellB.Po#itionB>= 7C )Cell B> oCell&#etStrinB"Hello"C oCell&HoriMu#ti$. 6 co!&#un&#tar&table&CellHoriMu#ti$.&CEH3ER oCell&RotateAnle 6 %777 )%7 deree# End Sub +igure 1T. /ell value rotated FC degrees. #e** properties ,see Tab*e 162. are $eneric to most types of ce**s inc*udin$ te3t tab*e ce**s& #e**s in a spreads"eet contain ot"er properties as %e** ,see Tab*e 163.& Table 163. 9roperties supported by the com.sun.star.sheet.*heet/ell service. Property Description 'osition T"e position of t"e ce** in t"e s"eet ,in 0&01 mm. as a com&sun&star&a%t&'oint structure& T"is is t"e abso*ute position in t"e entire s"eet, not t"e position in t"e isib*e area& I H T"e 39coordinate as a Lon$ )nte$er& 6 H T"e y9coordinate as a Lon$ )nte$er& SiCe T"e siCe of t"e ce** ,in 0&01 mm. as a com&sun&star&a%t&SiCe structure: ;idt" H T"e %idt" as a Lon$ )nte$er& Eei$"t H T"e "ei$"t as a Lon$ )nte$er& 0ormu*aLoca* 1ptiona* strin$ containin$ t"e formu*a usin$ *oca*iCed function names& 0ormu*aResu*tType 0ormu*a resu*t type %it" a*ues from t"e com&sun&star&s"eet&0ormu*aResu*t constant $roup: OAL52 ? 1 H T"e formu*a returns a Doub*e precision f*oatin$9point number& STR)4J ? 2 H T"e formu*a returns a Strin$ a*ue& 2RR1R ? ! H T"e formu*a "as an error of some sort& #onditiona*0ormat T"e conditiona* formattin$ settin$s for t"is ce**& ;"en a conditiona* format is c"an$ed, it must be reinserted into t"e property set& #onditiona*0ormatLoca* 1ptiona* property dup*icatin$ #onditiona*0ormat e3cept t"at formu*a names use *oca* names& Oa*idation T"e data a*idation settin$s for t"is ce** as a com&sun&star&beans&I'ropertySet& Oa*idationLoca* 1ptiona* property dup*icatin$ Oa*idation e3cept t"at formu*a names use *oca* names& T"e macro in Listin$ 3B1 demonstrates "o% to obtain a ce**Gs position and siCe in a s"eet& Listing 391. 9rint cell dimensions. Sub Cell-i!en#ion# -i! oCell -i! # A# Strin oCell 6 3(i#Co!ponent&S(eet#B7C&etCellB.Po#itionB>= 7C )Cell B> # 6 # 4 CStrBoCell&Po#ition&/ \ >77C 4 " !! $ro! t(e le$t" 4 CHRFB>7C # 6 # 4 CStrBoCell&Po#ition&P \ >77C 4 " !! $ro! t(e top" 4 CHRFB>7C 449 # 6 # 4 CStrBoCell&Si8e&Widt( \ >77C 4 " !! *ide" 4 CHRFB>7C # 6 # 4 CStrBoCell&Si8e&Hei(t \ >77C 4 " !! tall" 4 CHRFB>7C M#Box #= 7= "Si8e And Po#tion O$ Cell " 4 oCell&Ab#oluteHa!e End Sub 1,.2.$. Cell annotations 2ac" ce** can contain one annotation t"at consists of simp*e unformatted te3t& T"e ce**Gs $etAnnotation,. met"od returns an ob/ect t"at supports t"e com&sun&star&s"eet&#e**Annotation serice& #e** annotations support t"e ISimp*eTe3t interface used in ;riter documents as %e** as t"e more specific met"ods s"o%n in Tab*e 16!& Table 164. Methods implemented by the com.sun.star.sheet./ell-nnotation service. )et6od Description $et'arent,. Jet t"e ob/ect ,ce**. containin$ t"is annotation& set'arent,o#e**. Set t"e ce** t"at contains t"is annotation& $et'osition,. Jet t"e com&sun&star&tab*e&#e**Address of t"e ce** containin$ t"is annotation ,see Tab*e 1AB.& $etAut"or,. Jet t"e user %"o *ast c"an$ed t"e annotation as a Strin$& $etDate,. Jet t"e date t"e annotation %as *ast c"an$ed as a formatted Strin$& $et)sOisib*e,. Returns True if t"e annotation is isib*e& set)sOisib*e,boo*ean. Set %"et"er t"e annotation is isib*e& T"e spreads"eet ob/ect supports t"e met"od $etAnnotations,., %"ic" returns a** of t"e annotations in t"e spreads"eet& 6ou can obtain indiidua* annotations by usin$ inde3ed access or enumeration& T"e ob/ect returned by $etAnnotations,. a*so supports t"e met"ods remoe+y)nde3,n. and insert4e%,#e**Address, Strin$.& Sub !anipulateAnnotation# -i! doc A# ObNect -i! aS(eet A# ObNect -i! aCell A# ObNect -i! annotation# A# ObNect -i! !.Annotation A# ObNect
annotation# 6 aCell&#preadS(eet&annotation# W(ile BBannotationIndex E annotation#&countC and Bnot i#"oundCC anAnnotation 6 annotation#&etB.IndexBannotationIndexC i#"ound 6 BBanAnnotation&po#ition&ro* 6 aCell&cellAddre##&ro*C and BanAnnotation&po#ition&colu!n 6 aCell&cellAddre##&colu!nCC I$ Bi#"oundC 3(en re#ult 6 anAnnotation End I$ annotationIndex 6 annotationIndex W > Wend etAnnotationB.Cell 6 re#ult End "unction 1.3. )ninterpreted AM. 2ttributes 1pen1ffice&or$ stores documents as IML& ;"en an 11o document is read, it is parsed by an IML parser& 5ser9defined attributes are not interpreted by t"e parser, but t"ey are simp*y read, stored, and t"en %ritten& T"e intent is t"at a parser can store attributes t"at it cannot "and*e by itse*f on readin$ an IML fi*e& ;"en t"e fi*e is stored a$ain, t"e un(no%n attributes can be %ritten bac( %it"out *oss& 5ninterpreted attributes a*so a**o% you to add your o%n properties t"at are saed %it" t"e document& Table 165. Methods to manipulate user defined attributes. Method Description $et+y4ame Jet t"e named attribute& $et2*ement4ames Jet an array of strin$s containin$ t"e e3istin$ attribute names& "as+y4ame,name. Determine if t"e named attribute e3ists& "as2*ements Determine if any attributes e3ist& insert+y4ame,name, attr. )nsert a ne% attribute& remoe+y4ame,name. Remoe an e3istin$ attribute& rep*ace+y4ame,name, attr. Rep*ace an e3istin$ attribute& Listing 392. o manipulate User#efined-ttributes) use a copy and then assign it back. Sub 0#er-e$inedAttribute3oCell -i! oCell )3(e cell t(at *ill contain t(e attribute -i! o0#er-ata )A cop. o$ t(e 0#er-e$inedAttribute# -i! oM.Attribute A# He* co!&#un&#tar&x!l&Attribute-ata -i! oAttribute -i! o-oc 451
o-oc 6 createHe*Calc-ocBC REM "ir#t= et t(e cell t(at *ill contain t(e ne* attribute oCell 6 o-oc&S(eet#B7C&etCellB.Po#itionB>= 7C )Cell B> REM Ho* add data to t(e attribute& REM 3(e Ha!e#pace i# u#uall. le$t blan1= but #et it i$ .ou *ant to& REM o!.Attribute&Ha!e#pace 6 "(ttp:++*(at+e:er+.ou+*ant" REM Hotice t(at t(e t.pe i# C-A3A and not #o!et(in li1e "Strin" oM.Attribute&3.pe 6 "C-A3A" oM.Attribute&Oalue 6 "Andre* Piton.a1" REM Here i# *(ere t(in# u#uall. o *ron *it( a #tate!ent li1e REM oCell&0#er-e$inedAttribute#&in#ertB.Ha!eB"And."= oM.AttributeC REM 3(i# $ail# e:er. ti!e& In#tead= $ir#t !a1e a cop. and t(en REM operate on t(e cop.& o0#er-ata 6 oCell&0#er-e$inedAttribute# I$ HO3 o0#er-ata&(a#B.Ha!eB"And."C 3(en o0#er-ata&in#ertB.Ha!eB"And."= oM.AttributeC oCell&0#er-e$inedAttribute# 6 o0#er-ata End I$ oAttribute 6 oCell&0#er-e$inedAttribute#&etB.Ha!eB"And."C Print oAttribute&Oalue End Sub Tip A** serices t"at support 5serDefinedAttributes %or( t"e same %ay& 1.4. /heet cell ranges )n ;riter documents, continuous te3t can be $rouped in a te3t ran$e& )n a spreads"eet, ce**s can be $rouped in rectan$u*ar re$ions %it" a S"eet#e**Ran$e& Jroupin$ ce**s to$et"er a**o%s mu*tip*e ce**s to be operated on at one time& T"e S"eet#e**Ran$e serice supports many of t"e same interfaces and properties as a S"eet#e**& Tip 2ac" s"eet in a spreads"eet document is a*so a S"eetRan$e& 2ac" ce** "as a ce** address ,see Tab*e 1AB. t"at identifies its *ocation in t"e spreads"eet document& 2ac" ce** ran$e "as an ana*o$ous structure t"at identifies its *ocation in t"e spreads"eet ,see Tab*e 166.& Table 166. 9roperties of the com.sun.star.table./ellRange-ddress structure. Property Description S"eet S"ort )nte$er inde3 of t"e s"eet t"at contains t"e ce**& Start#o*umn Lon$ )nte$er inde3 of t"e co*umn %"ere t"e *eft ed$e is *ocated& StartRo% Lon$ )nte$er inde3 of t"e ro% %"ere t"e top ed$e is *ocated& 2nd#o*umn Lon$ )nte$er inde3 of t"e co*umn of t"e ri$"t ed$e of t"e ran$e& 2ndRo% Lon$ )nte$er inde3 of t"e ro% of t"e bottom ed$e of t"e ran$e& 452 A sin$*e s"eet ce** ran$e e3ists in a sin$*e s"eet and contains one rectan$u*ar re$ion& Mu*tip*e ran$es are encapsu*ated by t"e S"eet#e**Ran$es serice, %"ic" supports most of t"e same properties and serices as a S"eet#e**Ran$e& T"e simi*arity in functiona*ity simp*ifies t"e *earnin$ cure and offers a *ot of ot"er%ise comp*icated functiona*ity& T"e S"eet#e**Ran$es serice proides access to eac" ran$e t"rou$" t"e use of t"e I2*ementAccess interface and t"e I)nde3Access interface& T"e met"ods in Tab*e 16M a*so proide access to t"e contained ce** ran$es& Table 167. Methods defined by the com.sun.star.table.:*heet/ellRanges interface. )et6od Description $et#e**s,. Return t"e co**ection of contained ce**s as an I2numerationAccess& $etRan$eAddressesAsStrin$,. Return a strin$ %it" t"e addresses of a** contained ran$es& T"e output format is simi*ar to DS"eet1&+2:D67S"eet3&#!:DAF& $etRan$eAddresses,. Return an array of serices of type #e**Ran$eAddress ,see Tab*e 166.& 1,.$.1. heet cell range properties S"eet ce** ran$es and s"eet ce**s bot" support t"e properties 'osition, SiCe, #onditiona*0ormat, #onditiona*0ormatLoca*, Oa*idation, and Oa*idationLoca* ,see Tab*e 163.& T"e 'osition property for a s"eet ce** ran$e proides t"e *ocation of t"e upper9*eft ce** L t"is is e8uia*ent to obtainin$ t"e position property from t"e upper9*eft ce** in t"e ran$e& T"e SiCe property for a ce** returns t"e siCe of a sin$*e ce**, and t"e SiCe property for a s"eet ce** ran$e proides t"e siCe for a** of t"e ce**s contained in t"e ran$e& -alidation settings S"eet ce**s and s"eet ce** ran$es are ab*e to a*idate t"e data t"at t"ey contain, to preent ina*id data from popu*atin$ t"e ce**s& 6ou can disp*ay a dia*o$ %"en ina*id data is entered ,see Tab*e 16B.& T"e serice com&sun&star&s"eet&Tab*eOa*idation contro*s t"e a*idation process& +efore demonstratin$ "o% a a*idation is performed, ) must introduce a fe% enumerated a*ues, properties, and met"ods& Specify t"e a*idation t"at is performed by usin$ t"e enumerated a*ues s"o%n in Tab*e 16@& Table 168. 3alidation types defined by the com.sun.star.sheet.3alidationype enum. Vale Description com&sun&star&s"eet&Oa*idationType&A46 A** content is a*id7 no conditions are used& com&sun&star&s"eet&Oa*idationType&;E1L2 #ompare a %"o*e ,inte$er. number a$ainst t"e specified condition& com&sun&star&s"eet&Oa*idationType&D2#)MAL #ompare any number a$ainst t"e specified condition& com&sun&star&s"eet&Oa*idationType&DAT2 #ompare a date a*ue a$ainst t"e specified condition& com&sun&star&s"eet&Oa*idationType&T)M2 #ompare a time a*ue a$ainst t"e specified condition& com&sun&star&s"eet&Oa*idationType&T2IT=L24 #ompare a strin$ *en$t" a$ainst t"e specified condition& com&sun&star&s"eet&Oa*idationType&L)ST 1n*y a**o% strin$s in t"e specified *ist& com&sun&star&s"eet&Oa*idationTypeST1M Specify a formu*a t"at determines if t"e contents are a*id& ;"en a ce** containin$ ina*id data is found, t"e Oa*idationA*ertSty*e enum specifies "o% t"e ina*id data s"ou*d be "and*ed ,see Tab*e 16B.& Tab*e 1M0 *ists t"e supported conditiona* operators& 453 Table 169. 3alidation alerts defined by the com.sun.star.sheet.3alidation-lert*tyle enum. Vale Description com&sun&star&s"eet&Oa*idationA*ertSty*e&ST1' Disp*ay an error messa$e and re/ect t"e c"an$e& com&sun&star&s"eet&Oa*idationA*ertSty*e&;AR4)4J Disp*ay a %arnin$ messa$e and as( t"e user if t"e c"an$e %i** be accepted& T"e defau*t ans%er is 4o& com&sun&star&s"eet&Oa*idationA*ertSty*e&)401 Disp*ay an information messa$e and as( t"e user if t"e c"an$e %i** be accepted& T"e defau*t ans%er is 6es& com&sun&star&s"eet&Oa*idationA*ertSty*e&MA#R1 23ecute a specified macro& Table 170. /onditions defined by the com.sun.star.sheet./onditionOperator enum. Vale Description com&sun&star&s"eet&#ondition1perator&4142 4o condition is specified& com&sun&star&s"eet&#ondition1perator&2_5AL T"e a*ue must be e8ua* to t"e specified a*ue& com&sun&star&s"eet&#ondition1perator&41T=2_5AL T"e a*ue must not be e8ua* to t"e specified a*ue& com&sun&star&s"eet&#ondition1perator&JR2AT2R T"e a*ue must be $reater t"an t"e specified a*ue& com&sun&star&s"eet&#ondition1perator&JR2AT2R=2_5AL T"e a*ue must be $reater t"an or e8ua* to t"e specified a*ue& com&sun&star&s"eet&#ondition1perator&L2SS T"e a*ue must be *ess t"an t"e specified a*ue& com&sun&star&s"eet&#ondition1perator&L2SS=2_5AL T"e a*ue must be *ess t"an or e8ua* to t"e specified a*ue& com&sun&star&s"eet&#ondition1perator&+2T;224 T"e a*ue must be bet%een t"e t%o specified a*ues& com&sun&star&s"eet&#ondition1perator&41T=+2T;224 T"e a*ue must be outside of t"e t%o specified a*ues& com&sun&star&s"eet&#ondition1perator&01RM5LA T"e specified formu*a must "ae a non9Cero resu*t& T"e a*idation ob/ect defines t"e type of a*idation and "o% to react to t"e a*idation usin$ properties of t"e ob/ect ,see Tab*e 1M1.& Table 171. 9roperties supported by the com.sun.star.sheet.able3alidation service. Property Description Type T"e type of a*idation to perform, as s"o%n in Tab*e 16@& S"o%)nputMessa$e )f True, an input messa$e appears %"en t"e cursor is in an ina*id ce**& )nputTit*e Tit*e ,Strin$. of t"e dia*o$ %it" t"e input messa$e& )nputMessa$e Te3t ,Strin$. of t"e input messa$e& S"o%2rrorMessa$e )f True, an error messa$e appears %"en ina*id data is entered& 2rrorTit*e Tit*e ,Strin$. of t"e dia*o$ s"o%in$ t"e error messa$e& 2rrorMessa$e Te3t ,Strin$. of t"e error messa$e& )$nore+*an(#e**s )f True, b*an( ce**s are a**o%ed& 2rrorA*ertSty*e T"e action t"at is ta(en %"en an error occurs, as s"o%n in Tab*e 16B& 0ina**y, t"e comparison t"at is performed is specified usin$ met"ods imp*emented by t"e Tab*eOa*idation serice ,see Tab*e 1M2.& 454 Table 172. Methods supported by the com.sun.star.sheet.able3alidation service. )et6od Description $et1perator,. Jet t"e operator used in t"e condition, as s"o%n in Tab*e 1M0& set1perator,condition. Set t"e operator used in t"e condition, as s"o%n in Tab*e 1M0& $et0ormu*a1,. Jet t"e comparison a*ue ,Strin$. used in t"e condition, or t"e first a*ue if t%o are needed& set0ormu*a1,Strin$. Set t"e comparison a*ue used in t"e condition, or t"e first a*ue if t%o are re8uired& $et0ormu*a2,. Jet t"e second a*ue ,Strin$. if t%o are re8uired& set0ormu*a2,Strin$. Set t"e second a*ue ,Strin$. if t%o are re8uired& $etSource'osition,. Jet t"e #e**Address t"at is used as a base for re*atie references in t"e formu*as ,see Tab*e 1AB.& setSource'osition,#e**Address. Set t"e #e**Address t"at is used as a base for re*atie references in t"e formu*as ,see Tab*e 1AB.& T"e macro in Listin$ 3B3 sets a a*idation ran$e in t"e fourt" s"eet L t"at is, t"e s"eet %it" a numerica* inde3 of 3& T"e ce**s from +2 to D6 are set to disa**o% any a*ues t"at are not bet%een 1 and 10& T"e macro itse*f is une3pected*y simp*e& Listing 393. *et validation range in /alc. Sub SetOalidationRane -i! oRane )Rane t(at *ill accept t(e :alidation -i! oOalidation )3(e :alidation obNect -i! o-oc
o-oc 6 createHe*Calc-ocBC REM S(eet# #upport returnin a cell rane ba#ed on 0I t.pe na!e#& oRane 6 o-oc&S(eet#B7C&etCellRaneB.Ha!eB"B':-A"C
REM Obtain t(e Oalidation obNect oOalidation 6 oRane&Oalidation
REM Con$iure t(e :alidation to per$or! oOalidation&3.pe 6 co!&#un&#tar&#(eet&Oalidation3.pe&-ECIMA, oOalidation&ErrorMe##ae 6 "Plea#e enter a nu!ber bet*een one and ten" oOalidation&S(o*ErrorMe##ae 6 3rue oOalidation&ErrorAlertSt.le 6 co!&#un&#tar&#(eet&OalidationAlertSt.le&S3OP oOalidation&#etOperatorBco!&#un&#tar&#(eet&ConditionOperator&BE3WEEHC
oOalidation&#et"or!ula>B>&7C oOalidation&#et"or!ula>B>7&7C REM Ho* #et t(e :alidation oRane&Oalidation 6 oOalidation Print "3r. to enter an inteer in cell# B':-A t(at i# not bet*een > and >7&" End Sub 455 T"e e3amp*e in Listin$ 3B3 sets a Decima* a*idation bet%een 1 and 10& T"is a*idation e3amp*e does not $enerate an error for a a*ue of 0 or 0&A& Try a fe% e3amp*es to see %"at e*se mi$"t fai*& Conditional formatting #onditiona* formattin$ a**o%s t"e ce** sty*e to c"an$e based on t"e ce**Gs content& S"eet ce**s and s"eet ce** ran$es bot" support t"e #onditiona*0ormat property, %"ic" in turn supports t"e IS"eet#onditiona*2ntries interface& 6ou can access conditiona* formattin$ entries by usin$ e*ement access, inde3ed access, or t"e met"ods add4e%,properties,.., c*ear,., and remoe+y)nde3,inde3.& 6ou can a*so app*y mu*tip*e conditiona* formattin$ entries to t"e same ce**& T"e first one t"at matc"es is app*ied& 2ac" formattin$ entry is represented by an array of 'ropertyOa*ue structures& #onditiona* formattin$ is ery simi*ar to a*idation in t"at t"ey bot" use a*ues and types from Tab*e 16@ t"rou$" Tab*e 1M2& Oa*idation is a re*atie*y simp*e condition on a data e*ement, enforcin$ type and format constraints& #onditiona* a*idation supports a*idation and a more e3tended set of c"ec(s, inc*udin$ attributes or metadata defined on e*ements or co**ections of e*ements L t"e names are simi*ar, but t"e actua* operations, app*ications, and imp*ications are muc" more e*aborate& )t is more difficu*t to e3p*ain t"an it is to demonstrate& T"e macro in Listin$ 3B! sets a ran$e of ce**s to use t"e DEeadin$1F sty*e if t"e ce** contains a ne$atie number& Listing 394. *et conditional style in /alc. Sub SetConditionalSt.le -i! oRane )Cell rane to u#e -i! oCon"or!at )Conditional $or!at obNect -i! oConditionB'C A# He* co!&#un&#tar&bean#&Propert.Oalue REM S(eet# #upport returnin a cell rane ba#ed on 0I t.pe na!e#& oRane 6 3(i#Co!ponent&S(eet#B7C&etCellRaneB.Ha!eB"B':-A"C
REM Obtain t(e Oalidation obNect oCon"or!at 6 oRane&Conditional"or!at
oConditionB7C&Ha!e 6 "Operator" oConditionB7C&Oalue 6 co!&#un&#tar&#(eet&ConditionOperator&,ESS oConditionB>C&Ha!e 6 ""or!ula>" oConditionB>C&Oalue 6 7 oConditionB'C&Ha!e 6 "St.leHa!e" oConditionB'C&Oalue 6 "Headin>" oCon"or!at&addHe*BoConditionBCC oRane&Conditional"or!at 6 oCon"or!at End Sub 1,.$.2. heet cell range ser'ices S"eet ce**s and s"eet ce** ran$es "ae numerous serices in common L for e3amp*e, #e**'roperties ,see Tab*e 162., #"aracter'roperties, #"aracter'ropertiesAsian, #"aracter'roperties#omp*e3, 'ara$rap"'roperties, and S"eetRan$es_uery& %etrieving cells and ranges S"eet#e**Ran$es support t"e #e**Ran$e serice, %"ic" in turn supports #e**'roperties ,see Tab*e 162.& T"e #e**Ran$e serice offers e3tra functiona*ity t"at is appropriate for ce** ran$es, but not for indiidua* ce**s L 456 for e3amp*e, retriein$ ce**s and ce** ran$es& ;"en a ce** ran$e is retrieed usin$ t"e met"ods in Tab*e 1M3, t"e ce**s are inde3ed re*atie to t"e top9*eft corner of t"e ran$e& ;"en t"e ran$e is an entire s"eet, t"e *ocation ,0, 0. refers to t"e ce** DA1&F )f t"e ran$e inc*udes t"e ce**s D+2:D6F, "o%eer, t"e *ocation ,0,0. refers to ce** D+2&F T"e macros in Listin$ 3@B t"rou$" Listin$ 3B1 a** use t"e met"od $et#e**+y'osition,.& Table 173. Methods supported by the com.sun.star.table.:/ellRange interface. )et6od Description $et#e**+y'osition,*eft, top. Jet a ce** %it"in t"e ran$e& $et#e**Ran$e+y'osition,*eft, top, ri$"t, bottom. Jet a ce** ran$e %it"in t"e ran$e& $et#e**Ran$e+y4ame,name. Jet a ce** ran$e %it"in t"e ran$e based on its name& T"e strin$ direct*y references ce**s usin$ t"e standard formats L suc" as D+2:DAF or DY+Y2F L or defined ce** ran$e names& Tip T"e met"ods $et#e**+y'osition,., $et#e**Ran$e+y'osition,., and $et#e**Ran$e+y4ame,. cannot return a a*ue t"at is not in t"e ran$e ,see Listin$ !22.& Buer'ing cells S"eet ce** ran$es and s"eet ce**s bot" support t"e abi*ity to find ce**s %it" specific properties& T"is abi*ity proides a mec"anism for findin$ a** ce**s t"at are referenced by t"e current ce**Gs formu*a and t"e abi*ity to see %"ic" ce**s reference t"e current ce**& ;"i*e performin$ a 8uery based on t"e ce**Gs content, t"e #e**0*a$s in Tab*e 1M! specify t"e content type to searc"& Table 174. 3alues in the com.sun.star.sheet./ell+lags constant group. Vale !la+ Description 1 com&sun&star&s"eet&#e**0*a$s&OAL52 Se*ect numbers not formatted as dates or times& 2 com&sun&star&s"eet&#e**0*a$s&DAT2T)M2 Se*ect numbers formatted as dates or times& ! com&sun&star&s"eet&#e**0*a$s&STR)4J Se*ect strin$s& @ com&sun&star&s"eet&#e**0*a$s&A441TAT)14 Se*ect ce** annotations& 16 com&sun&star&s"eet&#e**0*a$s&01RM5LA Se*ect formu*as& 32 com&sun&star&s"eet&#e**0*a$s&EARDATTR Se*ect e3p*icit formattin$ L not sty*es& 6! com&sun&star&s"eet&#e**0*a$s&ST6L2S Se*ect ce** sty*es& 12@ com&sun&star&s"eet&#e**0*a$s&1+K2#TS Se*ect dra%in$ ob/ects suc" as buttons and $rap"ics& 2A6 com&sun&star&s"eet&#e**0*a$s&2D)TATTR Se*ect formattin$ %it"in t"e ce**Gs content& 2ac" of t"e met"ods used to 8uery a ce** ran$e ,see Tab*e 1MA. a*so returns a ce** ran$e ,see Tab*e 16M.& Table 175. Methods to 8uery a cell range. )et6od Description 8ueryDependents,boo*ean. Return a** ce**s t"at reference ce**s in t"is ran$e& )f True, searc" is recursie& 8uery'recedents,boo*ean. Return a** ce**s referenced by ce**s in t"is ran$e& )f True, searc" is recursie& 8ueryOisib*e#e**s,. Return a** isib*e ce**s& 8uery2mpty#e**s,. Return a** empty ce**s& 457 )et6od Description 8uery#ontent#e**s,#e**0*a$s. Return a** ce**s %it" t"e specified content types ,see Tab*e 1M!.& 8uery0ormu*a#e**s,0ormu*aResu*t. Return a** ce**s containin$ a formu*a %it" t"e specified resu*t type ,see 0ormu*aResu*tType in Tab*e 163.& 8uery#o*umnDifferences,#e**Address. Return a** ce**s t"at differ from t"e comparison ce** in t"e specified ce**Gs ro% ,see Tab*e 1AB.& 8ueryRo%Differences,#e**Address. Return a** ce**s t"at differ from t"e comparison ce** in t"e specified ce**Gs co*umn ,see Tab*e 1AB.& 8uery)ntersection,#e**Ran$eAddress. Return t"e ran$e of ce**s t"at intersect t"e specified ran$e ,see Tab*e 166.& Cinding non9empt' cells in a range 5se t"e met"od 8uery#ontent#e**s,#e**0*a$s. to obtain a *ist of a** ce**s in a ran$e t"at are not empty& T"e #e**0*a$s ar$ument is set to return a** ce**s t"at contain a a*ue, strin$, formu*a, or date-time& T"e interestin$ t"in$ about Listin$ 3BA is not t"at it uses a 8uery to find t"e nonempty ce**s, but rat"er t"at it demonstrates "o% to e3tract t"e ce**s from t"e 8uery and enumerate a** of t"e returned ce**s& )n ot"er %ords, t"e macro in Listin$ 3BA demonstrates "o% to isit a** of t"e nonempty ce**s in a specific ran$e& Listing 395. +ind cells that are not empty in a range. "unction HonE!pt.Cell#InRaneBoRane= #epFC A# Strin -i! oCell )3(e cell to u#eK -i! oRane# )Rane# returned a$ter ;uer.in $or t(e cell# -i! oAddr#BC )Arra. o$ CellRaneAddre## -i! oAddr )One CellRaneAddre## -i! oS(eet )S(eet t(at contain# t(e cell rane -i! i A# ,on )Jeneral index :ariable -i! nRo* A# ,on )Ro* nu!ber -i! nCol A# ,on )Colu!n nu!ber -i! # A# Strin
REM "ir#t= $ind t(e cell# t(at are HO3 e!pt. in t(i# raneK REM I con#ider a cell to be not e!pt. i$ it (a# a :alue= REM date+ti!e= #trin= or $or!ula& oRane# 6 oRane&;uer.ContentCell#B5 co!&#un&#tar&#(eet&Cell"la#&OA,0E OR 5 co!&#un&#tar&#(eet&Cell"la#&-A3E3IME OR 5 co!&#un&#tar&#(eet&Cell"la#&S3RIHJ OR 5 co!&#un&#tar&#(eet&Cell"la#&"ORM0,AC
oAddr#BC 6 oRane#&etRaneAddre##e#BC "or i 6 7 3o 0BoundBoAddr#BCC
Hext HonE!pt.Cell#InRane 6 # End "unction )sing comple: Dueries A*t"ou$" t"e 8uery met"ods are easy to use, some of t"em are conceptua**y 8uite comp*icated& A** of t"e 8uery met"ods return a S"eet#e**Ran$es ob/ect& T"e macro in Listin$ 3B6 demonstrates "o% to find t"e ce**s referenced by a formu*a usin$ t"e 8uery'recedents,. met"od, "o% to find t"e ce**s referencin$ a particu*ar ce** usin$ t"e 8ueryDependents,. met"od, as %e** as "o% to find ro% and co*umn differences usin$ t"e 8ueryRo%Differences,. and 8uery#o*umnDifferences,. met"ods& T"e macro in Listin$ 3B6 confi$ures t"e fourt" s"eet %it" a*ues and formu*as, and t"en t"e macro performs some 8ueries& T"e code t"at performs t"e demonstrated 8ueries is simp*e and s"ort& T"e code t"at creates t"e data t"at is 8ueried, "o%eer, is more comp*icated and instructie& More specifica**y, t"e macro in Listin$ 3B6 demonstrates "o% to c*ear a ran$e of ce**s by usin$ t"e c*ear#ontents,. met"od& T"e dia*o$ produced by Listin$ 3B6 is s"o%n in 0i$ure B@& Listing 396. ;uery a range of cells to find references) dependencies) and similarities. Sub [uer.CellRane -i! oCell )Hold# a cell te!poraril. -i! oCellAddre## )Hold# a cell)# addre## -i! oRane )3(e pri!ar. rane -i! oS(eet )3(e $ourt( #(eet -i! i A# Inteer )3e!porar. index :ariable -i! # A# Strin )3e!porar. Strin -i! o-oc : o-oc 6 createHe*Calc-ocBC REM S(eet# #upport returnin a cell rane ba#ed on 0I t.pe na!e#& oS(eet 6 o-oc&S(eet#B7C REM Jet t(e rane I *ant to u#eK oRane 6 oS(eet&etCellRaneB.Ha!eB"A>:"Q"C
REM Ho* clear t(e rane o$ all attribute# and :alue# u#in t(e Cell"la# REM Hotice t(at I OR all o$ t(e $la# toet(er& oRane&clearContent#B5 co!&#un&#tar&#(eet&Cell"la#&OA,0E OR 5 co!&#un&#tar&#(eet&Cell"la#&-A3E3IME OR 5 co!&#un&#tar&#(eet&Cell"la#&S3RIHJ OR 5 co!&#un&#tar&#(eet&Cell"la#&AHHO3A3IOH OR 5 co!&#un&#tar&#(eet&Cell"la#&"ORM0,A OR 5 co!&#un&#tar&#(eet&Cell"la#&HAR-A33R OR 5 co!&#un&#tar&#(eet&Cell"la#&S3P,ES OR 5 co!&#un&#tar&#(eet&Cell"la#&OBMEC3S OR 5 co!&#un&#tar&#(eet&Cell"la#&E-I3A33RC "or i 6 > 3o < oCell 6 oS(eet&etCellB.Po#itionB>= iC )Cell B' t(rou( BA oCell&#etOalueBiC oCell 6 oS(eet&etCellB.Po#itionB'= iC )Cell C' t(rou( CA 459 oCell&#et"or!ulaB"6B" 4 CStrBiW>C 4 " W >"C )6B'W>= 6B%W>= &&& oCell 6 oS(eet&etCellB.Po#itionB%= iC )Cell -' t(rou( -A oCell&#et"or!ulaB"6C" 4 CStrBiW>C 4 " 9 >"C )6C'9>= 6C%9>= &&& Hext oCell 6 oS(eet&etCellB.Po#itionB>= AC )B2 oCell&#et"or!ulaB"6S0MBB':B<C"C )3(i# inore# BA oCell 6 oS(eet&etCellB.Po#itionB'= AC )C2 oCell&#et"or!ulaB"6S0MBC':CAC"C )3(i# include# CA oCell 6 oS(eet&etCellB.Po#itionB'= 7C )C> oCell&#et"or!ulaB"6B> 9 >"C oCell 6 oS(eet&etCellB.Po#itionB>= 7C )B> oCell&#etOalueB'C oCell 6 oS(eet&etCellB.Po#itionB>= 2C )BQ oCell&#etOalueB'C oCell 6 oS(eet&etCellB.Po#itionB?= 'C )E% oCell&#etOalueB'C oCell 6 oS(eet&etCellB.Po#itionB?= 2C )EQ oCell&#etOalueB'C
REM 3(i# include# cell# "C':C2"& Hotice t(at it include# t(e cell it#el$ oCell 6 oS(eet&etCellB.Po#itionB'= AC # 6 # 4 "6S0MBC':CAC directl. re$erence# " 45 oCell&;uer.Precedent#B"al#eC&etRaneAddre##e#A#StrinBC 4 CHRFB>7C
M#Box #= 7= "Manipulatin A Rane" End Sub 460 Figure 98. ;uery a range of cells to find references) dependencies) and similarities. Tab*e 1M6 s"o%s t"e formu*as and a*ues created by t"e macro in Listin$ 3B6, assists in understandin$ t"e output s"o%n in 0i$ure B@& Table 176. he formulas and values set by Listing F1G. * C ( E 1 2 B1-1 2 1 B2+1 C2-1 # 2 B3+1 C3-1 2 $ 3 B4+1 C4-1 , 4 B5+1 C5-1 . 5 B6+1 C6-1 / SUM(B2:B5) SUM(C2:C6) 0 2 2 Duer" <recedents T"e first *ine in 0i$ure B@ s"o%s t"e resu*t of 8uery'recedents,0a*se. on a ran$e t"at contains on*y ce** #M& As s"o%n in Tab*e 1M6, ce** #M direct*y references t"e ce**s #2:#6 and itse*f& +y ca**in$ 8uery'recedents,True. L t"e second *ine in 0i$ure B@ L t"e ce**s +2:+6 are added because t"e ce**s in co*umn # reference t"e ce**s in co*umn +& T"e met"od 8ueryDependents,True. proides t"e t"ird *ine in 0i$ure B@, %"ic" disp*ays a** of t"e ce**s t"at reference +3, direct*y or indirect*y& Tab*e 1M6 s"o%s t"at +3, +M, and #3 direct*y reference ce** +3, and t"at ce**s #M and D3 indirect*y reference ce** +3& T"e fourt" *ine in 0i$ure B@ *ists t"e Dco*umn differencesF based on ce** +3& ;"i*e ca*cu*atin$ co*umn differences, on*y t"e ro% matters& )n ot"er %ords, t"e same resu*t is returned if ce** A3, #3, D3, or 23 is used instead of ce** +3& 0i$ure BB s"o%s t"e s"eet7 t"e ce**s t"at are considered different are mar(ed %it" a b*ac( bac($round& 0i$ure BB "e*ps to i**ustrate %"at is, and is not, considered a difference& +y c"oosin$ ce** +3, a** of t"e ce**s in eac" co*umn ,of t"e ran$e. are compared to t"e ce** in ro% 3 ,in t"e same co*umn.& T"e first co*umn, A, "as no ce**s se*ected because t"ey are a** empty7 t"erefore, a** t"e ce**s in t"e co*umn "ae t"e same a*ue& )n co*umn +, ce** +3 contains t"e constant a*ue of 2& #e**s +1 and +@ a*so contain t"e constant a*ue 2, so t"ese ce**s are not considered different& #o*umn # is ery interestin$ in t"at it does not contain constants, but rat"er it contains formu*as t"at are simi*ar& T"e ce**s #2, #!, #A, and #6 are simi*ar to ce** #3& T"e formu*as are effectie*y t"e same ,see Tab*e 1M6. in t"at t"ey a** add 1 to t"e ce** to t"e *eft& T"e 461 formu*a in #1 is not simi*ar to #3 so it is inc*uded in t"e difference *ist& #o*umn D is simi*ar to co*umn # and co*umn 2 is simi*ar to co*umn +& ) *eae it as an e3ercise for t"e reader to e3p*ain t"e ro% differences as s"o%n in 0i$ure BB& +igure 11. Output from Listing F1G with >column differencesA highlighted. 1,.$.#. earching and replacing T"e t"in$ t"at ) find most interestin$ about searc"in$ in a spreads"eet document is t"at searc"in$ is not supported by t"e document ob/ect& #e** ob/ect and ce** ran$e ob/ects support searc"in$, "o%eer& 2ac" s"eet is a*so a s"eet ran$e, so itGs possib*e to searc" an entire s"eet& )t is not possib*e, t"erefore, to searc" an entire document at one time7 you must searc" eac" s"eet separate*y& Listin$ 3BM demonstrates searc"in$ and rep*acin$ te3t in a sin$*e s"eet& Listing 397. *imple /alc search. Sub Searc(S(eet -i! oS(eet )S(eet in *(ic( to replace -i! oReplace )Replace de#criptor -i! nCount )Hu!ber o$ ti!e# replaced
oS(eet 6 3(i#Co!ponent&S(eet#B%C oReplace 6 oS(eet&createReplace-e#criptorBC oReplace&#etSearc(StrinB"/.88."C oReplace&#etReplaceStrinB"So!et(in El#e"C oReplace&Searc(Word# 6 "al#e nCount 6 oS(eet&replaceAllBoReplaceC M#Box "Replaced " 4 nCount End Sub Searc"in$ a s"eet in a #a*c document is a*most identica* to searc"in$ for te3t in a ;riter document& )n a #a*c document, settin$ Searc";ords to True forces t"e entire ce** to contain t"e searc" te3t& )n a ;riter document, settin$ Searc";ords to True forces t"e te3t to not be part of anot"er %ord& Tip )n a #a*c document, settin$ Searc";ords to True forces t"e entire ce** to contain t"e searc" te3t& 1,.$.$. Merging cells 5se t"e mer$e met"od to mer$e and unmer$e a ran$e of ce**s& After mer$in$ t"e ran$e +2:DM, ce** +2 appears in t"e area former*y used by t"e entire ran$e& ;"at is not s"o%n in 0i$ure 100 is t"at t"e ce**s t"at arenGt isib*e sti** e3ist and are accessib*e7 t"ey are simp*y not disp*ayed& 5se t"e $et)sMer$ed,. met"od to determine if a** of t"e ce**s in a ran$e are mer$ed& 462 Listing 398. Merge a range of cells. Sub MereExperi!ent -i! oCell )Hold# a cell te!poraril. -i! oRane )3(e pri!ar. rane -i! oS(eet )3(e $ourt( #(eet REM Mere a rane o$ cell# oS(eet 6 3(i#Co!ponent&S(eet#B%C oRane 6 oS(eet&etCellRaneB.Ha!eB"B':-2"C oRane&!ereB3rueC
REM Ho* obtain a cell t(at *a# !ered REM and I can do itK oCell 6 oS(eet&etCellB.Po#itionB'= %C )C? Print oCell&etOalueBC End Sub +igure (CC. Merging cells causes the top4left cell to use the entire merged area. After mer$in$ t"e ran$e +2:DM, ce** +2 appears in t"e area former*y used by t"e entire ran$e& ;"at is not s"o%n in 0i$ure 100 is t"at t"e ce**s t"at arenGt isib*e sti** e3ist and are accessib*e7 t"ey are simp*y not disp*ayed& 5se t"e $et)sMer$ed,. met"od to determine if a** of t"e ce**s in a ran$e are mer$ed& 1,.$.,. 6etrie'ing& inserting& and deleting columns and ro1s 5se t"e met"ods $et#o*umns,. and $etRo%s,. to retriee co*umns and ro%s coered by ce**s and ce** ran$es& After retriein$ t"e co*umns for a ran$e or a ce**, you can retriee t"e indiidua* co*umns by usin$ t"e interfaces I2*ementAccess or Iinde3Access& 6ou can use t%o additiona* met"ods L insert+y)nde3,inde3, count. and remoe+y)nde3,inde3, count. L to insert and remoe co*umns& After obtainin$ a sin$*e co*umn, you can $et t"e co*umnGs name %it" $et4ame,., set ce** properties for t"e entire co*umn, and e3tract ce**s by usin$ t"e ce** ran$e met"ods in Tab*e 1M3& A** of t"e manipu*ations mentioned for co*umns L e3cept for $et4ame,. L a*so app*y to t"e ro%s obtained by usin$ t"e $etRo%s,. met"od& T"e difference *ies in t"e properties supported by t"e indiidua* co*umns and ro%s ,see Tab*e 1MM.& 463 Table 177. "ndividual row and column properties. Type Property Description #o*umn ;idt" ;idt" of t"e co*umn ,in 0&01 mm. as a Lon$ )nte$er& Ro% Eei$"t Eei$"t of t"e ro% ,in 0&01 mm. as a Lon$ )nte$er& #o*umn 1ptima*;idt" )f True, t"e co*umn a*%ays (eeps its optima* %idt"& Ro% 1ptima*Eei$"t )f True, t"e co*umn a*%ays (eeps its optima* "ei$"t& +ot" )sOisib*e )f True, t"e ro% or co*umn is isib*e& +ot" )sStart1f4e%'a$e )f True, a "oriConta* ,ertica*. pa$e brea( is attac"ed to t"e co*umn ,ro%.& T"e macro in Listin$ 3BB obtains t"e ran$e D+6:#BF and t"en traerses a** of t"e nonempty ce**s& T"e "ard part is done in t"e routine 4on2mpty#e**s)nRan$e,. as s"o%n in Listin$ 3BA& Listin$ 3BB, "o%eer, demonstrates "o% to e3tract t"e indiidua* ro%s from a ran$e& Typica**y, %"en %ritin$ a macro, you (no% %"ere t"e data *ies so you simp*y %rite code to traerse t"e data direct*y& 0i$ure 101 s"o%s t"e output from Listin$ 3BB %"en t"e macro is run usin$ t"e data s"o%n in 0i$ure BB& Listing 399. $numerate rows in a range and find empty cells. Sub 3ra:er#eRo*# -i! oRane )3(e pri!ar. rane -i! oS(eet )3(e $ourt( #(eet -i! oRo*# )Ro*# obNect -i! oRo* )A #inle ro* -i! oRo*Enu! )Enu!erator $or t(e ro*# -i! # A# Strin )Jeneral Strin Oariable
REM I no* *ant to $ind A,, o$ t(e cell# t(at are HO3 e!pt. in t(e REM ro*# t(at are related to t(e rane& Hotice t(at I do not *ant to REM li!it !.#el$ to cell# in t(e rane= but t(at I a! intere#ted in t(e REM ro*#& oRo*# 6 oRane&etRo*#BC REM Sure= I could acce## t(in# b. index= but .ou probabl. expected t(atK oRo*Enu! 6 oRo*#&createEnu!erationBC -o W(ile oRo*Enu!&(a#MoreEle!ent#BC oRo* 6 oRo*Enu!&nextEle!entBC # 6 # 4 HonE!pt.Cell#InRaneBoRo*= " "C 4 CHRFB>7C ,oop M#Box #= 7= "Hon9E!pt. Cell# In Ro*#" End Sub 464 +igure (C(. he nonempty cells are displayed from rows G through 0. 1,.$... 6etrie'ing and setting data as an arra" 6ou can 8uic(*y and easi*y obtain a** data from a ran$e as an array of arrays by usin$ t"e $etDataArray,. met"od& T"e data in eac" ce** is returned as eit"er a number or a strin$& 6ou can a*so set t"e data for a ran$e by usin$ t"e setDataArray,. met"od7 /ust be certain t"at t"e array dimensions matc" t"e ran$e dimensions ,see Listin$ !00.& Listing 400. <et and set data in a /alc sheet. Sub JetAndSet-ata -i! oRane )3(e pri!ar. rane -i! oS(eet )3(e $ourt( #(eet -i! oAll-ata )Arra. containin t(e data -i! # A# Strin )Jeneral #trin :ariable -i! i A# Inteer )Jeneral index :ariable
REM Jet t(e data contained in t(e raneK REM -ata $ro! e!pt. cell# i# included& oAll-ata 6 oRane&et-ataArra.BC "or i 6 7 3o 0BoundBoAll-ataC REM oAll-ataBiC i# an arra.= #o #i!pl. Noin t(e data toet(er REM $or a ;uic1 printinK # 6 # 4 "B" 4 MoinBoAll-ataBiC= "C B"C 4 "C" 4 CHRFB>7C Hext M#Box #= 7= "-ata In Rane" REM Ho* ;uic1l. #et #o!e data& oRane 6 oS(eet&etCellRaneB.Ha!eB"">:J'"C oRane&#et-ataArra.BArra.BArra.B>= "One"C= Arra.B'= "3*o"CCC End Sub Tip As of #a*c 3&0, t"e ma3imum number of co*umns is 102! ,co*umn is AMK., t"e ma3imum number of ro%s is 6A,A36, and t"e ma3imum number ce**s in a s"eet is 6M,10@,@6!& Laurent Jodard performed tests and increased t"e number for testin$ purposes: see "ttp:--b*o$s&nu3eo&com-de-2006-0@-t"e9spreads"eet9ne3t&"tm* "ttp:--%i(i&serices&openoffice&or$-%i(i-#a*c-"ac(s-number=of=ro%s 465 S"eet ce** ran$es a*so proide t"e abi*ity to $et and set formu*as in bu*( usin$ arrays& 5se t"e met"ods $et0ormu*aArray,. and set0ormu*aArray,. to $et and set t"e formu*as in a ran$e as an array L t"ese t%o met"ods can be a rea* time saer& )f you inspect a s"eet ran$e, you %i** notice t"at a s"eet supports $etData,. and $etDataArray,.& +ot" met"ods return an array of arrays& T"e met"od $etDataArray returns numbers and strin$s& T"e $etData met"od defined by t"e I#"artData interface, "o%eer, returns numbers and i$nores strin$s& 1,.$./. Computing functions on a range )tGs possib*e to compute a a*ue based on a specified ran$e ,see Listin$ 3BA and Listin$ 3BB., but it is tedious& 6ou can use t"e $etDataArray,. met"od ,see Listin$ !00. to 8uic(*y obtain a** of t"e data and simp*y process t"e data in t"e nested arrays& To easi*y app*y a simp*e function to a ran$e, use t"e ob/ect met"od compute0unction,Jenera*0unction.& Tab*e 1M@ *ists t"e functions supported by t"e Jenera*0unction enumeration& Table 178. he com.sun.star.sheet.<eneral+unction enumeration. Vale Description com&sun&star&s"eet&Jenera*0unction&4142 4ot"in$ is ca*cu*ated& com&sun&star&s"eet&Jenera*0unction&A5T1 5se S5M if a** a*ues are numerica*7 ot"er%ise use #154T& com&sun&star&s"eet&Jenera*0unction&S5M Sum ,add. a** of t"e numerica* a*ues& com&sun&star&s"eet&Jenera*0unctionšT #ount a** of t"e a*ues& com&sun&star&s"eet&Jenera*0unction&AO2RAJ2 Aera$e a** of t"e numerica* a*ues& com&sun&star&s"eet&Jenera*0unction&MAI Ma3imum numerica* a*ue& com&sun&star&s"eet&Jenera*0unction&M)4 Minimum numerica* a*ue& com&sun&star&s"eet&Jenera*0unction&'R1D5#T 'roduct ,mu*tip*ication. of a** t"e numerica* a*ues& com&sun&star&s"eet&Jenera*0unctionšT45MS #ount t"e numerica* a*ues& com&sun&star&s"eet&Jenera*0unction&STD2O Standard deiation based on a samp*e& com&sun&star&s"eet&Jenera*0unction&STD2O' Standard deiation based on t"e entire popu*ation& com&sun&star&s"eet&Jenera*0unction&OAR Oariance based on a samp*e& com&sun&star&s"eet&Jenera*0unction&OAR' Oariance based on t"e entire popu*ation& T"e macro in Listin$ !01 demonstrates t"e use of t"e compute function& 5sin$ t"e s"eet s"o%n in 0i$ure BB and t"e macro in Listin$ !01, t"ere are seen nonempty ce**s in t"e ran$e AA:#B& Listing 401. /ompute a function on a range. Sub 0#eCo!pute -i! oRane )3(e pri!ar. rane -i! oS(eet )3(e $ourt( #(eet -i! d A# -ouble )Return :alue
oS(eet 6 3(i#Co!ponent&S(eet#B%C oRane 6 oS(eet&etCellRaneB.Ha!eB"A<:C@"C d 6 oRane&co!pute"unctionBco!&#un&#tar&#(eet&Jeneral"unction&CO0H3C M#Box "Hon9E!pt. :alue# in A<:C@ 6 " 4 d= 7= "Co!put"untionBC" End Sub 466 1,.$.0. Clearing cells and cell ranges )n a #a*c document, c*ic( on a ce** and press t"e De*ete (ey& A dia*o$ opens %it" a *ist of t"in$s t"at can be de*eted& T"e abi*ity to de*ete any combination of t"in$s from different types of content or formattin$ is amaCin$*y po%erfu* and f*e3ib*e& T"e types of t"in$s t"at can be de*eted are encapsu*ated by t"e #e**0*a$s s"o%n in Tab*e 1M!& #e**0*a$s may be combined usin$ t"e 1R operator and passed to t"e c*ear#ontents,#e**0*a$s. met"od ,see Listin$ 3B6.& Tip T"e c*ear#ontents,. met"od is supported by ce**s, ce** ran$es, and een ro%s and co*umns& 1,.$.2. )utomatic data fill Listin$ 3B6 painfu**y fi**s consecutie ce**s %it" data& S"eet ce** ran$es proide a better met"od for automatica**y fi**in$ a ran$e %it" data by usin$ t"e fi**Auto,0i**Direction, n#ount. met"od& T"e 0i**Direction enumerated a*ues s"o%n in Tab*e 1MB contro* "o% t"e data is propa$ated& Table 179. he com.sun.star.sheet.+ill#irection enumeration. Vale Description com&sun&star&s"eet&0i**Direction&T1=+1TT1M Ro%s are fi**ed from top to bottom& com&sun&star&s"eet&0i**Direction&T1=R)JET #o*umns are fi**ed from *eft to ri$"t& com&sun&star&s"eet&0i**Direction&T1=T1' Ro%s are fi**ed from bottom to top& com&sun&star&s"eet&0i**Direction&T1=L20T #o*umns are fi**ed from ri$"t to *eft& 5se t"e met"od fi**Auto,0i**Direction, n#ount. to automatica**y fi** an area& 0irst, se*ect t"e ran$e t"at you %ant to fi**& Second, set t"e initia* a*ue t"at %i** be incremented by t"e fi**Auto,. met"od& T"e *ocation of t"e initia* a*ues depend on t"e direction t"at %i** be fi**ed& 0or e3amp*e, if usin$ T1=L20T, t"e ri$"tmost ce**s in t"e ran$e must contain an initia* a*ue so t"at t"ey can be fi**ed to t"e *eft& ;"i*e fi**in$ ne% a*ues, t"e fi**Auto,. met"od increments t"e number by 1 %"i*e moin$ to t"e ri$"t or bottom, and decrements t"e number by 1 %"i*e moin$ to t"e *eft or top& )f t"e number is formatted as a time or date, incrementin$ by 1 adds one day& Tip ;"en a time is incremented usin$ fi**Auto,., it is incremented by one day& )f t"e ce** is formatted to s"o% on*y t"e time, it %i** appear as t"ou$" t"e a*ue does not c"an$e L a*t"ou$" it "as& T"is s"ou*d be obious if you t"in( about it& T"e fi**Auto,. met"od uses t"e *ast ar$ument, n#ount, to determine "o% many ce**s to moe before enterin$ a ne% a*ue& A a*ue of 1, t"erefore, fi**s eery ce** as t"e cursor moes& ;"i*e fi**in$ ne% ce**s, t"e fi**Auto,. met"od %onGt moe outside t"e ran$e used to ca** fi**Auto,.& T"e code snippet in Listin$ !02 assumes t"at S"eet 3 contains numerica* a*ues in t"e ce** ran$e 211:220& Listing 402. +ill values from $((JN=C using fill-uto. oS(eet 6 3(i#Co!ponent&S(eet#B%C oRane 6 oS(eet&etCellRaneB.Ha!eB"E>>:H'7"C oRane&$illAutoBco!&#un&#tar&#(eet&"ill-irection&3O5RIJH3= >C 11o a*so supports more comp*icated fi** met"ods& T"e 0i**Mode enumeration ,see Tab*e 1@0. directs t"e specia* functiona*ity proided by t"e met"od fi**Series,.& T"e auto0i**,. met"od a*%ays uses t"e L)42AR mode to increment t"e a*ue by one, %"ereas t"e fi**Series,. met"od a**o%s for any fi** mode& 467 Table 180. he com.sun.star.sheet.+illMode enumeration. Vale Description com&sun&star&s"eet&0i**Mode&S)M'L2 A** of t"e a*ues are t"e same ,constant series.& com&sun&star&s"eet&0i**Mode&L)42AR T"e a*ues c"an$e by a constant increment ,arit"metic series.& com&sun&star&s"eet&0i**Mode&JR1;TE T"e a*ues c"an$e by a constant mu*tip*e ,$eometric series.& com&sun&star&s"eet&0i**Mode&DAT2 An arit"metic series for date a*ues& T"is causes a** numbers to be treated as dates, re$ard*ess of formattin$& com&sun&star&s"eet&0i**Mode&A5T1 T"e ce**s are fi**ed from a user9defined *ist& T"e fi**Series,. met"od reco$niCes dates and times based on t"e numerica* format used to disp*ay t"em& 5sin$ t"e 0i**Mode DAT2 forces a** numbers to be reco$niCed as dates rat"er t"an /ust numbers t"at are formatted as dates& ;"en a date is fi**ed, t"e day, mont", or year can be c"an$ed as specified by t"e 0i**DateMode enumerated a*ues ,see Tab*e 1@1.& Table 181. he com.sun.star.sheet.+ill#ateMode enumeration. Vale Description com&sun&star&s"eet&0i**DateMode&0)LL=DAT2=DA6 )ncrement t"e day by 1& com&sun&star&s"eet&0i**DateMode&0)LL=DAT2=;22<DA6 )ncrement t"e day by 1 but s(ip Saturday and Sunday& com&sun&star&s"eet&0i**DateMode&0)LL=DAT2=M14TE )ncrement t"e mont" ,t"e day is unc"an$ed.& com&sun&star&s"eet&0i**DateMode&0)LL=DAT2=62AR )ncrement t"e year ,t"e day and mont" are unc"an$ed.& T"e met"od fi**Series,0i**Direction, 0i**Mode, 0i**DateMode, nStep, n2ndOa*ue. proides t"e $reatest f*e3ibi*ity for fi**in$ a*ues& T"e nStep a*ue indicates "o% t"e a*ue is modified from ce** to ce**& T"e fina* ar$ument specifies a fina* a*ue not to e3ceed durin$ t"e fi**& T"e fi**Series,. met"od %i** not modify a a*ue outside of t"e ran$e and stops addin$ a*ues %"en passin$ t"e end a*ue& ;"i*e specifyin$ an end a*ue, remember t"at dates e3pressed as a re$u*ar number are rat"er *ar$e7 !0000 refers to Ku*y 6, 200B& Listin$ !03 uses t"e fi**Series,. met"od to fi** a ran$e of dates& Tip T"e fi**Auto,. met"od increments or decrements t"e a*ue dependin$ on t"e direction in %"ic" t"e a*ues are fi**ed& T"e fi**Series,. met"od, "o%eer, a*%ays uses t"e nStep a*ue re$ard*ess of t"e direction& Listing 403. +ill values from $((JN=C using fill*eries67. oS(eet 6 3(i#Co!ponent&S(eet#B%C oRane 6 oS(eet&etCellRaneB.Ha!eB"E>>:H'7"C oRane&$illSerie#Bco!&#un&#tar&#(eet&"ill-irection&3O5,E"3=5 co!&#un&#tar&#(eet&"illMode&,IHEAR=5 co!&#un&#tar&#(eet&"ill-ateMode&"I,,5-A3E5-AP='= ?7777C )f te3t containin$ a number is found in an initia* ce**, t"e copied a*ue copies t"e te3t and increments t"e ri$"tmost number in t"e te3t& 0or e3amp*e, ) entered t"e te3t DTe3t 1F and t"e fi**ed te3t contained DTe3t 3F, DTe3t AF, and so on& 468 1,.$.13. )rra" formulas T"e simp*est usa$e of an array formu*a t"at ) "ae seen ino*es p*acin$ an array formu*a in one ce** and usin$ t"e formu*a in mu*tip*e ce**s& 4o% t"at ) "ae proided /ust enou$" detai* to cause confusion, consider t"e simp*e e3amp*e s"o%n in Tab*e 1@2& Table 182. - simple formula in column ". + G ; I E % # 1 3 =G3+H3 $ 2 4 =G4+H4 , 3 5 =G5+H5 . 4 6 =G6+H6 / 5 7 =G7+H7 0 6 8 =G8+H8 #o*umn ) contains t"e formu*a to add co*umn J to co*umn E& T"is can be done usin$ an array formu*a by enterin$ one formu*a in one ce**& To enter an array formu*a into co*umn K t"at mimics t"e formu*a in co*umn ), first p*ace t"e cursor in ce** K3& 2nter t"e formu*a D?J3:J@NE3:E@F and t"en press #tr*9S"ift92nter& T"e ce**s K3 t"rou$" K@ no% contain t"e sin$*e formu*a D`?J3:J@NE3:E@bF and t"e a*ues in co*umn K s"ou*d matc" t"ose in co*umn )& #o*umn ) contains si3 formu*as t"at are not direct*y re*ated to eac" ot"er, but t"e ce**s in co*umn K use on*y one formu*a& T"e macro in Listin$ !0! sets a s"eet to *oo( *i(e Tab*e 1@2 and t"en sets co*umn K to contain an array formu*a t"at ca*cu*ates t"e same a*ues as co*umn )& Listing 404. #emonstrate an array formula. Sub Arra."or!ula -i! oRane )3(e pri!ar. rane -i! oS(eet )3(e $ourt( #(eet -i! oCell )Hold# a cell te!poraril. -i! i A# Inteer )Jeneral Index Oariable -i! o-oc )Re$erence ne*l. created calc docu!ent&
REM "ill t(e :alue# do*nK oRane 6 oS(eet&etCellRaneB.Ha!eB"J%:HQ"C oRane&$illAutoBco!&#un&#tar&#(eet&"ill-irection&3O5BO33OM= >C REM 3(i# de!on#trate# #ettin eac( cell indi:iduall.& "or i 6 % 3o Q oCell 6 oS(eet&etCellB.Po#itionBQ= i9>C )Cell I% 9 IQ oCell&#et"or!ulaB"6J" 4 i 4 "WH" 4 iC 469 Hext
REM Settin a #inle arra. $or!ula i# !uc( ea#ier in t(i# ca#e& oRane 6 oS(eet&etCellRaneB.Ha!eB"M%:MQ"C oRane&#etArra."or!ulaB"6J%:JQWH%:HQ"C
REM Add #o!e (eadin#K oRane 6 oS(eet&etCellRaneB.Ha!eB"J':M'"C oRane&#et-ataArra.BArra.BArra.B"J"= "H"= ""or!ula"= "Arra. "or!ula"CCC End Sub 1,.$.11. Computing multiple functions on a range 11o supports usin$ a series of sin$*e ariab*e formu*as a$ainst a series of a*ues& A typica* e3amp*e ino*es a sin$*e co*umn ,or ro%. of numbers %it" ad/acent co*umns ,or ro%s. containin$ formu*as usin$ t"e numbers& T"e enumerated a*ues in Tab*e 1@3 specify if ro%s or co*umns are used& Table 183. he com.sun.star.sheet.ableOperationMode enumeration Vale Description com&sun&star&s"eet&Tab*e1perationModeL5M4 App*y t"e operation do%n t"e co*umns& com&sun&star&s"eet&Tab*e1perationMode&R1; App*y t"e operation across t"e ro%s& com&sun&star&s"eet&Tab*e1perationMode&+1TE App*y t"e operation to bot" ro%s and co*umns& T"e setTab*e1peration,. met"od proides t"e abi*ity to 8uic(*y app*y mu*tip*e sin$*e ariab*e functions to t"e same set of data producin$ a tab*e of a*ues& T"e met"od setTab*e1peration,. accepts four ar$uments as fo**o%s: 1. CellRangeAddress Cell range address that contains the functions to apply. 2. TableOperationMode Identifies if the data is in rows or columns (see Table 183). 3. CellAddress Cell address that is used if using columns (row mode or both). 4. CellAddress Cell address that is used if using rows (column mode or both). T"e macro in Listin$ !0A $enerates a co*umn of numbers from 0 to 6&3, t"e functions Sin,. and #os,. are t"en app*ied to t"e co*umns& Listing 405. Use setableOperations to 8uickly set an operation on a column. Sub MultipleOp#Colu!n# -i! oRane )3(e pri!ar. rane -i! oS(eet )3(e $ourt( #(eet -i! oCell )Hold# a cell te!poraril. -i! oBloc1Addre## )Addre## o$ t(e bloc1 to $ill -i! oCellAddre## )Ro* or colu!n cell -i! o-oc )Re$erence ne*l. created calc docu!ent&
REM I reall. onl. need t(e colu!n :alue becau#e t(e ro* :alue i# not u#ed& oRane&#et3ableOperationBoBloc1Addre##=5 co!&#un&#tar&#(eet&3ableOperationMode&CO,0MH=5 oCellAddre##= oCellAddre##C End Sub )f t"e tab*e operation mode is set to +1TE rat"er t"an /ust R1; or #1L5M4, t"en a sin$*e function is app*ied to t%o ariab*es& T"e macro in Listin$ !06 creates t"e mu*tip*ication tab*e t"at ) memoriCed in t"ird $rade& Listing 406. Use a table operation to create a multiplication tables Sub createMultiplication3ableWrapperBC createMultiplication3ableBC End Sub "unction createMultiplication3ableBC -i! oRo*Cell )3(e ro* cell -i! oColCell )3(e colu!n cell -i! oRane )3(e pri!ar. rane -i! oS(eet )3(e $ourt( #(eet -i! oCell )Hold# a cell te!poraril. -i! oBloc1Addre## )Addre## o$ t(e bloc1 to $ill 471 -i! oCellAddre## )Ro* or colu!n cell -i! o-oc )Re$erence ne*l. created calc docu!ent&
REM Set t(e colu!n o$ con#tant :alue# oColCell 6 oS(eet&etCellB.Po#itionB7= >7C )Cell A>> oColCell&#etOalueB>C oRane 6 oS(eet&etCellRaneB.Ha!eB"A>>:A'7"C oRane&$illAutoBco!&#un&#tar&#(eet&"ill-irection&3O5BO33OM= >C oRane&C(arWei(t 6 co!&#un&#tar&a*t&"ontWei(t&BO,- oRane&C(arHei(t 6 >? REM Set t(e $or!ula t(at *ill be u#ed& It re$erence# t(e $ir#t :alue#K oCell 6 oS(eet&etCellB.Po#itionB7= @C )Cell A>7 oCell&#et"or!ulaB"6A>>*B>7"C REM Jet t(e rane o$ t(e cell# oRane 6 oS(eet&etCellRaneB.Ha!eB"A>7:^'7"C
REM "ill t(e !ultiplication table# $or t(e :alue# >x> t(rou( >7x>7 oRane&#et3ableOperationBoRane&etRaneAddre##BC=5 co!&#un&#tar&#(eet&3ableOperationMode&BO3H=5 oColCell&etCellAddre##BC=5 oRo*Cell&etCellAddre##BCC createMultiplication3ableBC 6 o-oc End "unction 1,.$.12. Cells 1ith the same formatting S"eet ce** ran$es proide t%o met"ods for obtainin$ $roups of ce**s t"at contain t"e same format& T"e $et#e**0ormatRan$es,. met"od returns an ob/ect t"at supports bot" inde3 and enumeration access& T"e e8ua**y formatted ce**s are sp*it into mu*tip*e rectan$u*ar ran$es& T"e enumerated ran$es are returned as a S"eet#e**Ran$e ob/ect& T"e ob/ect met"od $et5ni8ue#e**0ormatRan$es,. is ery simi*ar to t"e met"od $et#e**0ormatRan$es,. e3cept t"at t"e returned a*ues are ob/ects of type S"eet#e**Ran$es& T"e primary difference is t"at a** of t"e simi*ar*y formatted ob/ects are returned in one container& T"e macro in Listin$ !0M disp*ays t"e simi*ar*y formatted ran$es usin$ t"e t%o different met"ods& Listing 407. #isplay*imilarRanges is in the /alc module in this chapterSs source code files as */(2.s.c. Sub -i#pla.Si!ilarRane# -i! oS(eetCellRane )An indi:idual #(eet cell rane -i! oS(eetCellRane# )S(eet cell rane# 472 -i! oAddr )An addre## obNect $ro! t(e #(eet cell rane -i! #F )0tilit. #trin :ariable -i! x )3(e returned rane obNect# are #tored (ere -i! iG )0tilit. index :ariable -i! oS(eet -i! o-oc )Re$erence ne*l. created calc docu!ent&
REM S(eetCellRane# x 6 oS(eet&et0ni;ueCell"or!atRane#BC # 6 # 4 CHRFB>7C 4 "**** et0ni;ueCell"or!atRane#BC" 4 CHRFB>7C "or i 6 7 3o x&etcountBC9> oS(eetCellRane# 6 x&etB.IndexBiC # 6 # 4 i 4 " 6 "4 oS(eetCellRane#&etRaneAddre##e#A#StrinBC 4 CHRFB>7C Hext M#Box #= 7= ",i1e Rane#" End Sub 0i$ure 102 demonstrates ery c*ear*y t"e difference bet%een t"e t%o met"ods& T"e $et5ni8ue#e**0ormatRan$es,. met"od s"o%s t"at ei$"t of t"e ran$es are formatted simi*ar*y ,inde3 0 in 0i$ure 102.& +ot" met"ods contain t"e same ran$es7 it is on*y a 8uestion of $roupin$& 473 +igure (C=. he two methods group the data differently. 1,.$.1#. orting )n $enera*, 11o (no%s %"at type of data a ce** contains& <no%*ed$e of t"e contained data types reduces t"e need to inform 11o of t"e type of data t"at it is sortin$, but it is sti** possib*e usin$ t"e Tab*eSort0ie*dType enumeration ,see Tab*e 1@!.& ;"en you re8uest a sort operation, an array of Tab*eSort0ie*d structures identifies %"ic" co*umns or ro%s are used to determine t"e sort order and "o% t"ey are sorted ,see Tab*e 1@A.& Table 184. he com.sun.star.table.able*ort+ieldype enumeration. Vale Description com&sun&star&tab*e&Tab*eSort0ie*dType&A5T1MAT)# Automatica**y determine t"e data type& com&sun&star&tab*e&Tab*eSort0ie*dType&45M2R)# Sort t"e data as a number& com&sun&star&tab*e&Tab*eSort0ie*dType&AL'EA45M2R)# Sort t"e data as te3t& 474 Table 185. he com.sun.star.table.able*ort+ield structure. Property Description 0ie*d Pero9based inde3 of t"e ro% or co*umn in t"e tab*e to sort& T"e inde3 is re*atie to t"e start of t"e sort ran$e& )sAscendin$ )f True, sort t"e data in ascendin$ order& )s#aseSensitie )f True, t"e sort is case sensitie& 0ie*dType Specify t"e data type as a Tab*eSort0ie*dType ,see Tab*e 1@!.& #o**atorLoca*e T"e Loca*e ob/ect to use %"en sortin$ te3t& #o**atorA*$orit"m T"e sortin$ a*$orit"m used by t"e co**ator %"en sortin$ te3t& #"ec( t"e interface com&sun&star&i1@n&I#o**ator to inesti$ate %"at a*$orit"ms are supported for your *oca*e& ) "ae a*%ays used t"e defau*t a*ue& ;"en you re8uest a sort operation, an array of properties is passed to t"e sort routine& T"e properties determine %"at to sort and "o% it is sorted& 1ne of t"e supported properties is Sort0ie*ds ,see Tab*e 1@6., %"ic" contains t"e array of Tab*eSort0ie*d structures t"at determine "o% t"e ro%s or co*umns are sorted& Table 186. he old way to specify a sort using a *ort#escriptor. Property Description )s#aseSensitie )f True, t"e sort is case sensitie& SortAscendin$ )f True, sort t"e data in ascendin$ order& T"is property typica**y is not used, because t"e Tab*eSort0ie*d specifies )sAscendin$ for eac" fie*d& Sort#o*umns )f True, co*umns are sorted& )f 0a*se, ro%s are sorted& #o**atorLoca*e T"e Loca*e ob/ect to use %"en sortin$ te3t ,usua**y set in t"e Tab*eSort0ie*d.& #o**atorA*$orit"m Sortin$ a*$orit"m to use ,usua**y set in t"e Tab*eSort0ie*d.& Sort0ie*ds Array of type Tab*eSort0ie*d ,see Tab*e 1@A. t"at directs %"at is sorted& Ma3Sort0ie*ds#ount Lon$ )nte$er t"at specifies t"e ma3imum number of sort fie*ds t"e descriptor can "o*d& T"is a*ue cannot be set, but it can be read& #ontainsEeader )f True, t"e first ro% or co*umn is considered a "eader and is not sorted& 1rientation T"is property is deprecated and s"ou*d no *on$er be usedT Tab*es 2@ and 2B reea* t"at t"ere is a $reat dea* of redundancy& 0or e3amp*e, you can specify if t"e sort is case sensitie eit"er $*oba**y ,usin$ Tab*e 1@6. or for eac" specific fie*d ,usin$ Tab*e 1@A.& A*t"ou$" t"e redundant fie*ds in Tab*e 1@6 are not re8uired and are t"erefore typica**y not used, a ne% set of sort descriptors "as been introduced ,see Tab*e 1@M.& A*t"ou$" you can use properties from Tab*e 1@6 or Tab*e 1@M, you cannot mi3 t"e t%o& My recommendation is t"at you use t"e ne% set in Tab*e 1@M7 t"e 11o dee*opment team "as a*ready deprecated t"e use of t"e 1rientation property in Tab*e 1@6& 475 Table 187. he new way to specify a sort using a *ort#escriptor=. Property Description Sort0ie*ds Array of type Tab*eSort0ie*d ,see Tab*e 1@A. t"at directs %"at is sorted& Ma3Sort0ie*ds#ount Lon$ )nte$er t"at specifies t"e ma3imum number of sort fie*ds t"e descriptor can "o*d& T"is a*ue cannot be set, but it can be read& )sSort#o*umns )f True, co*umns are sorted& )f 0a*se, ro%s are sorted& +ind0ormatsTo#ontent )f True, ce** formats are moed %it" t"e contents durin$ t"e sort& T"is property matters on*y if different ce**s in t"e sort ran$e use different formattin$& )s5serList2nab*ed )f True, a user9defined sortin$ *ist is used from t"e J*oba*S"eetSettin$s& 5serList)nde3 Specify %"ic" user9defined sortin$ *ist is used as a Lon$ )nte$er& #opy1utputData )f True, t"e sorted data is copied to anot"er position in t"e document& 1utput'osition #e**Address t"at specifies %"ere to copy t"e sorted data ,if #opy1utputData is True.& #ontainsEeader )f True, t"e first ro% or co*umn is considered a "eader and is not sorted& T"e first step in sortin$ a ran$e is to define t"e fie*ds on %"ic" to sort by usin$ an array of type Sort0ie*d& 4e3t, define t"e properties from Tab*e 1@M t"at you intend to use in t"e sort& 0ina**y, ca** t"e sort,. routine on t"e ran$e to sort& T"e macro in Listin$ !0@ performs a descendin$ sort on t"e first co*umn& Listing 408. *ort one column in a /alc sheet. Sub SortColVero -i! oS(eet -i! oRane -i! oSort"ield#B7C a# ne* co!&#un&#tar&util&Sort"ield -i! oSort-e#cB7C a# ne* co!&#un&#tar&bean#&Propert.Oalue oS(eet 6 3(i#Co!ponent&S(eet#B7C REM Set t(e rane on *(ic( to #ort oRane 6 oS(eet&etCellRaneB.Ha!eB"B'Q:-%%"C REM Sort on t(e $ir#t $ield in t(e rane oSort"ield#B7C&"ield 6 7 oSort"ield#B7C&SortA#cendin 6 "A,SE REM Set t(e #ort $ield# to u#e oSort-e#cB7C&Ha!e 6 "Sort"ield#" oSort-e#cB7C&Oalue 6 oSort"ield#BC
REM Ho* #ort t(e raneK oRane&SortBoSort-e#cBCC End Sub Sortin$ on t%o co*umns rat"er t"an /ust one is as easy as addin$ a second sort fie*d& Listin$ !0B sorts on t"e second and t"ird co*umns& Listing 409. *ort two columns in a /alc sheet. Sub SortColOne -i! oS(eet -i! oRane 476 -i! oSort"ield#B>C a# ne* co!&#un&#tar&util&Sort"ield -i! oSort-e#cB7C a# ne* co!&#un&#tar&bean#&Propert.Oalue oS(eet 6 3(i#Co!ponent&S(eet#B7C REM Set t(e rane on *(ic( to #ort oRane 6 oS(eet&etCellRaneB.Ha!eB"B'Q:-%%"C REM Sort on t(e #econd $ield in t(e rane oSort"ield#B7C&"ield 6 > oSort"ield#B7C&SortA#cendin 6 3rue oSort"ield#B7C&"ield3.pe 6 co!&#un&#tar&util&Sort"ield3.pe&H0MERIC REM Sort on t(e t(ird $ield in t(e rane oSort"ield#B>C&"ield 6 ' oSort"ield#B>C&SortA#cendin 6 3rue oSort"ield#B>C&"ield3.pe 6 co!&#un&#tar&util&Sort"ield3.pe&A,PHAH0MERIC REM Set t(e #ort $ield# to u#e oSort-e#cB7C&Ha!e 6 "Sort"ield#" oSort-e#cB7C&Oalue 6 oSort"ield#BC
REM Ho* #ort t(e raneK oRane&SortBoSort-e#cBCC End Sub T"e met"od createSortDescriptor,. returns an array of property a*ues t"at define "o% a sort s"ou*d occur& )nspectin$ t"is created sort descriptor indicates t"at you can use a ma3imum of t"ree fie*ds %"en sortin$ ,see t"e Ma3Sort0ie*ds#ount in Tab*e 1@M.& T"e macro in Listin$ !10 creates a sort descriptor and t"en disp*ays t"e properties t"at it contains ,see 0i$ure 103.& Listing 2(C. #isplay sort descriptor properties in /alc. Sub -i#pla.Sort-e#criptor On Error Re#u!e Hext -i! oS(eet -i! oRane ) A rane i# needed to create t(e #ort de#criptor& -i! oSort-e#cript -i! iG -i! #F -i! o-oc )Re$erence ne*l. created calc docu!ent&
o-oc 6 Star-e#1top&loadCo!ponent"ro!0R,B"pri:ate:$actor.+#calc"= "5de$ault"= 7= Arra.BCC oS(eet 6 o-oc&S(eet#B7C oRane 6 oS(eet&etCellRaneB.Ha!eB"B'Q:-%%"C oSort-e#cript 6 oRane&createSort-e#criptorBC "or i 6 ,BoundBoSort-e#criptC 3o 0BoundBoSort-e#criptC # 6 # 4 oSort-e#criptBiC&Ha!e 4 " 6 " # 6 # 4 oSort-e#criptBiC&Oalue # 6 # 4 CHRFB>7C Hext M#Box #= 7= "Sort -e#criptor" End Sub 477 +igure (CF. *ort descriptor attributes. 1.. /heets Most of a #a*c documentGs functiona*ity is contained in t"e indiidua* s"eets rat"er t"an t"e document as a %"o*e& T"e interfaces imp*emented by t"e spreads"eet document ,see Tab*e 1AM. are primari*y re*ated to t"e document as a %"o*e, rat"er t"an t"e indiidua* s"eets& T"e s"eets in a #a*c document imp*ement t"e S"eet#e**Ran$e serice, %"ic" proides e3tensie functiona*ity& T"e functiona*ity proided by s"eet ce** ran$es app*ies to any s"eet ce** ran$e and is not *imited to s"eets& )n ot"er %ords, any ran$e is ab*e to use t"e met"ods imp*emented by t"e S"eet#e**Ran$e serice& T"e indiidua* s"eets support ot"er interfaces t"at are not direct*y re*ated to s"eet ce** ran$es ,see Tab*e 1@@.& Table 188. "nterfaces implemented by the com.sun.star.sheet.*preadsheet service. Interfaces Description com&sun&star&s"eet&ISpreads"eet Met"ods to create a ce** cursor& com&sun&star&container&I4amed Access t"e spreads"eet name& com&sun&star&uti*&I'rotectab*e Met"ods to protect and unprotect t"e indiidua* s"eet& com&sun&star&s"eet&IData'i*otTab*esSupp*ier Access t"e Data'i*ot tab*es %it" t"e met"od $etData'i*otTab*es,.& )n Libre1ffice, t"e Data 'i*ot is ca**ed 'iot Tab*es& com&sun&star&s"eet&IScenariosSupp*ier Access t"e scenarios %it" t"e met"od $etScenarios,.& com&sun&star&s"eet&IS"eetAnnotationsSupp*ier Access t"e annotations %it" t"e met"od $etAnnotations,.& com&sun&star&dra%in$&IDra%'a$eSupp*ier Access t"e s"eetGs dra% pa$e %it" t"e met"od $etDra%'a$e,.& com&sun&star&tab*e&ITab*e#"artsSupp*ier Access t"e documentGs c"art ob/ects %it" t"e met"od $et#"arts,.& com&sun&star&s"eet&I#e**Ran$eMoement Moe ce** ran$es inside t"e s"eet or to ot"er spreads"eets in t"is document& com&sun&star&s"eet&I'rintAreas Access to t"e print9area settin$s of t"is s"eet& com&sun&star&s"eet&IS"eet'a$e+rea( Access and modify t"e pa$e brea(s in t"is s"eet& com&sun&star&s"eet&IScenario 'roide met"ods for a scenario s"eet& com&sun&star&s"eet&IS"eet1ut*ine Access t"e ro% and co*umn out*ine settin$s for t"e s"eet& com&sun&star&s"eet&IS"eetAuditin$ Loo( for *in(ed ce**s ,detectie.& com&sun&star&s"eet&IS"eetLin(ab*e Met"ods to *in( to e3istin$ s"eets in ot"er documents& 478 1,.,.1. !inking to an external spreadsheet An indiidua* s"eet may *in( to a s"eet from anot"er spreads"eet document& Lin(in$ causes t"e D*in( s"eetF to act as a container for t"e D*in(ed s"eet&F After *in(in$ to a s"eet, a*t"ou$" you can modify t"e *in(ed s"eet in t"e container, t"ese updates are not propa$ated bac( to t"e ori$ina* document& )f t"e *in(ed s"eet is c"an$ed in t"e ori$ina* document, t"e c"an$e is not isib*e in t"e *in( document un*ess t"e *in( itse*f is refres"ed& 6ou can *in( documents by usin$ one of t"e enumerated a*ues in Tab*e 1@B& Table 189. 3alues supported by the com.sun.star.sheet.*heetLinkMode enumeration. Vale Description com&sun&star&s"eet&S"eetLin(Mode&4142 T"e s"eet is not *in(ed& com&sun&star&s"eet&S"eetLin(Mode&41RMAL #opy t"e entire content inc*udin$ a*ues and formu*as& com&sun&star&s"eet&S"eetLin(Mode&OAL52 #opy t"e content by a*ue7 eac" formu*aGs returned a*ue is copied rat"er t"an t"e formu*a itse*f& 5se t"e *in(,. met"od to estab*is" a *in( %it" a s"eet in anot"er document& Tab*e 1B0 *ists t"e *in(9re*ated met"ods supported by a s"eet& Table 190. 3alues supported by the com.sun.star.sheet.*heetLinkMode enumeration. )et6od Description $etLin(Mode,. Jet t"e s"eetGs *in( mode ,see Tab*e 1@B.& $etLin(Mode,S"eetLin(Mode. Set t"e *in( mode ,see Tab*e 1@B.& $etLin(5r*,. Jet t"e *in( 5RL& setLin(5r*,ur*. Set t"e *in( 5RL& $etLin(S"eet4ame,. Jet t"e name of t"e *in(ed s"eet& setLin(S"eet4ame,name. Set t"e name of t"e *in(ed s"eet& *in(,ur*, s"eet4ame, fi*ter4ame, fi*ter1ptions, S"eetLin(Mode. Lin( t"e s"eet to anot"er s"eet in anot"er document& T"e macro in Listin$ !11 creates a s"eet named DLin()tF and t"en *in(s to a s"eet in a specified e3terna* document& )f t"e DLin()tF s"eet a*ready e3ists, t"e *in( is obtained from t"e spreads"eet document and t"e *in( is refres"ed& Refres"in$ a *in( causes t"e data *in(ed into t"e current document to be updated& Listing 411. Link to an e.ternal sheet. Sub ,in1AS(eet -i! oS(eet# )3(e #(eet# obNect t(at contain# all o$ t(e #(eet# -i! oS(eet )Indi:idual #(eet -i! oS(eetEnu! )"or acce##in b. enu!eration -i! # A# Strin )Strin :ariable to (old te!porar. data -i! i A# Inteer )Index :ariable -i! #0R, A# Strin )0R, o$ t(e docu!ent to i!port -i! o,in1 )3(e lin1 obNect #0R, 6 "$ile:++C:+M.G'7-ocu!ent#+CH><+te#t&od#" oS(eet# 6 3(i#Co!ponent&S(eet# 479
I$ oS(eet#&(a#b.Ha!eB",in1It"C 3(en REM 3(e lin1# are a:ailable $ro! t(e docu!ent obNect REM ba#ed on t(e 0R, u#ed to load t(e!& o,in1 6 3(i#Co!ponent&S(eet,in1#&etB.Ha!eB#0R,C o,in1&re$re#(BC M#Box "3(e #(eet na!ed ,in1It *a# re$re#(ed" Exit Sub End I$
REM In#ert t(e ne* #(eet at t(e end& oS(eet#&in#ertHe*B.Ha!e B",in1It"= oS(eet#&etCountBCC oS(eet 6 oS(eet#&etB.Ha!eB",in1It"C
oS(eet&lin1B#0R,= "S(eet>"= ""= ""= co!&#un&#tar&#(eet&S(eet,in1Mode&HORMA,C End Sub T"e first app*ication t"at ) sa% for *in(ed s"eets %as to conso*idate a *ist of arious inestments t"at %ere trac(ed in different #a*c documents& 2ac" of t"e #a*c documents contained a summary s"eet for t"e inestments in t"e document& A sin$*e summary document inserted *in(s to t"e summary pa$e for eac" of t"e ot"er inestment s"eets& A*t"ou$" *in(ed s"eets are nice, t"ey are sometimes oer(i**& )f you donGt %ant to reference an entire s"eet from anot"er document, you can set t"e formu*a to direct*y access /ust one ce**& See Listin$ !12& Listing 412. Link cell -( to M01 in another document. oCell 6 t(i#co!ponent&#(eet#B7C&etcellb.po#itionB7=7C ) A> oCell&#et"or!ulaB"6" 4 ")$ile:+++(o!e+0SER+Calc"ile'&odt)LFS(eet'&^Q@"C 1,.,.2. +inding dependencies b" using auditing functions T"e met"ods 8ueryDependents,. and 8uery'recedents,., *isted in Tab*e 1MA, return a *ist of ce**s t"at depend on a ran$e& T"e 8uery met"ods are usefu* for %ritin$ macros t"at manipu*ate eac" dependent ce**& T"e auditin$ functiona*ity proided by t"e IS"eetAuditin$ interface proides met"ods for isua*iCin$ ce** dependencies ,see Tab*e 1B1.& Table 191. Methods supported by the com.sun.star.sheet.:*heet-uditing interface. )et6od Description "ideDependents,#e**Address. Remoe arro%s for one *ee* of dependents7 return True if ce**s are mar(ed& "ide'recedents,#e**Address. Remoe arro%s for one *ee* of precedents7 return True if ce**s are mar(ed& s"o%Dependents,#e**Address. Dra% arro%s from t"e #e**Address ,see Tab*e 1AB. to its dependents7 return True if ce**s are mar(ed& s"o%'recedents,#e**Address. Dra% arro%s to t"e #e**Address ,see Tab*e 1AB. from its dependents7 return True if ce**s are mar(ed& s"o%2rrors,#e**Address. Dra% arro%s from t"e #e**Address ,see Tab*e 1AB. containin$ an error and t"e ce**s causin$ t"e error7 return True if ce**s are mar(ed& s"o%)na*id,. S"o% a** ce**s containin$ ina*id a*ues7 return True if ce**s are mar(ed& c*earArro%s,. Remoe a** auditin$ arro%s from t"e s"eet& 480 2ac" time t"at t"e s"o%'recedents,. met"od is ca**ed, anot"er *ee* of precedents is mar(ed %it" arro%s& After t"e first ca**, arro%s are dra%n from a** ce**s direct*y referenced by t"e specified ce**& T"e _ueryRan$e macro in Listin$ 3B6 disp*ays t"e dependencies ,see 0i$ure B@.7 Listin$ !13, "o%eer, disp*ays t"e precedents in t"e spreads"eet& 0i$ure 10! s"o%s one *ee* of precedents& T"e ce** #M contains t"e formu*a D?Sum,#2:#6.F& As 0i$ure 10! s"o%s, ce** #M refers to a** of t"e DsummedF ce**s& )f you ca** t"e met"od s"o%'recedents,. a$ain, youG** see t"e ce**s t"at reference t"e ce**s #2:#6& T"e s"o%'recedents,. met"od returns True as *on$ as more precedent ce**s are mar(ed %it" arro%s& 0i$ure 10A s"o%s t"e ne3t *ee* of precedents& Listing 413. #isplay precedents. "unction Si!pleCalc-ocAdditionBC -i! o-oc )Re$erence ne*l. created calc docu!ent& -i! oS(eet -i! oRane
o-oc 6 Si!pleCalc-ocAdditionBC oS(eet 6 o-oc&S(eet#B7C oAddr 6 oS(eet&etCellB.Po#itionB>= AC&CellAddre## oS(eet&#(o*Precedent#BoAddrC Print "See one le:el o$ Precedent# $or cell B2" oS(eet&#(o*Precedent#BoAddrC Print "See t*o le:el# o$ Precedent# $or cell B2" End Sub 481 +igure (C2. One level of precedents. +igure (CI. wo levels of precedents with an array formula in !=J!G. T"e arro%s in 0i$ure 10A demonstrate t%o *ee*s of precedents assumin$ an array formu*a& )f a simp*e formu*a is used in eac" ce** rat"er t"an an array formu*a, t"e fi$ure c"an$es noticeab*y& As an e3ercise, consider %"y t"is is& +igure (CG. wo levels of precedents with formulas in !=J!G. 482 1,.,.#. Outlines 1ut*ines in a #a*c document $roup ro%s and co*umns to$et"er so t"at you can co**apse and e3pand t"e $roups %it" a sin$*e mouse c*ic(& ;"en you create an out*ine, you must specify %"et"er itGs ro%9centric or co*umn9centric by usin$ Tab*e1rientation enumeration ,see Tab*e 1B2.& T"e met"ods in Tab*e 1B3 be"ae *i(e t"eir menu counterparts in t"e 11o J5) for dea*in$ %it" spreads"eet out*ines& Table 192. 3alues defined by the com.sun.star.table.ableOrientation enumeration. Vale Description com&sun&star&tab*e&Tab*e1rientation&R1;S 5se ro%s& com&sun&star&tab*e&Tab*e1rientationL5M4S 5se co*umns& Table 193. Methods supported by the com.sun.star.sheet.:*heetOutline interface. Vale Description $roup,#e**Ran$eAddress, Tab*e1rientation. Jroup t"e ce**s in t"e ce** ran$e into one $roup& un$roup,#e**Ran$eAddress, Tab*e1rientation. Remoe t"e innermost *ee*s from t"e $roup& auto1ut*ine,#e**Ran$eAddress. #reate out*ine $roups based on formu*a references& c*ear1ut*ine,. Remoe a** out*ine $roups from t"e s"eet& "ideDetai*,#e**Ran$eAddress. #o**apse an out*ine $roup& s"o%Detai*,#e**Ran$eAddress. 1pen ,unco**apse. an out*ine $roup& s"o%Lee*,n, #e**Ran$eAddress. S"o% out*ined $roups from *ee*s one t"rou$" n& 1,.,.$. Cop"ing& mo'ing& and inserting cells )n a ;riter document, t"e primary met"od for moin$ or copyin$ te3t content is to use t"e c*ipboard& T"e Spreads"eet serice, "o%eer, proides met"ods for direct*y moin$ and insertin$ ce**s& ;"en ne% ce**s are inserted, you specify "o% ce**s are moed out of t"e %ay by usin$ t"e #e**)nsertMode enumeration ,see Tab*e 1B!.& Table 194. 3alues defined by the com.sun.star.sheet./ell"nsertMode enumeration. Vale Description com&sun&star&s"eet&#e**)nsertMode&4142 4o ce**s are moed& com&sun&star&s"eet&#e**)nsertMode&D1;4 Moe ce**s do%n& com&sun&star&s"eet&#e**)nsertMode&R)JET Moe ce**s ri$"t& com&sun&star&s"eet&#e**)nsertMode&R1;S Moe t"e entire ro% do%n& com&sun&star&s"eet&#e**)nsertModeL5M4S Moe t"e entire co*umn ri$"t& 5se t"e insert#e**s,#e**Ran$eAddress, #e**)nsertMode. met"od to create space t"e siCe of t"e ce** ran$e address& )f t"e insert mode is #1L5M4S, t"en t"e entire co*umn, startin$ %it" t"e *eftmost co*umn in t"e ran$e, is s"ifted to t"e ri$"t t"e %idt" of t"e ran$e& )f t"e insert mode is R)JET, t"en t"e entire co*umn is not s"ifted ri$"t7 on*y t"e ro%s in t"e ran$e are s"ifted& T"e ce** insert modes R1;S and D1;4 be"ae 483 simi*ar*y to t"e #1L5M4S and R)JET modes& 5sin$ t"e ce** insert ran$e of 4142 causes no ce**s to be moed7 in ot"er %ords, not"in$ "appens& Listin$ !1! moes ce**s do%n& Listing 414. Move the range L2JMI down. -i! oS(eet )3(e $ourt( #(eet -i! oRaneAddre## )3(e rane to !o:e oS(eet 6 3(i#Co!ponent&S(eet#B%C oRaneAddre## 6 oS(eet&etCellRaneB.Ha!eB",?:M<"C&etRaneAddre##BC oS(eet&in#ertCell#BoRaneAddre##= co!&#un&#tar&#(eet&CellIn#ertMode&-OWHC Tip T"e insert#e**s,. and remoeRan$e,. met"ods si*ent*y fai* if t"e insertion %i** cause an array formu*a to be sp*it& T"e remoeRan$e,#e**Ran$eAddress, #e**)nsertMode. met"od is essentia**y an DundoF command for t"e insert#e**s,. met"od& 5se t"e copyRan$e,#e**Address, #e**Ran$eAddress. met"od to copy a ran$e of ce**s to t"e *ocation specified by t"e ce** address& T"e top9*eft ce** in t"e ce** ran$e address is positioned at t"e specified ce** address %"en t"e ran$e is copied& T"e net effect of t"e copyRan$e,. met"od is t"e same as copyin$ a ran$e of ce**s to t"e c*ipboard, positionin$ t"e cursor at t"e specified ce**, and t"en pastin$ t"e ce**s into p*ace ,see Listin$ !1A.& Listing 415. /opy the range L2JMI to N0. -i! oS(eet )3(e $ourt( #(eet -i! oRaneAddre## )3(e rane to !o:e -i! oCellAddre## )-e#tination addre## oS(eet 6 3(i#Co!ponent&S(eet#B%C oRaneAddre## 6 oS(eet&etCellRaneB.Ha!eB",?:M<"C&etRaneAddre##BC oCellAddre## 6 oS(eet&etCellB.Po#itionB>%= 2C&etCellAddre##BC )HQ oS(eet&cop.RaneBoCellAddre##= oRaneAddre##C 5se t"e moeRan$e,#e**Address, #e**Ran$eAddress. met"od to moe ,rat"er t"an copy. a ran$e of ce**s& T"e be"aior of t"e moeRan$e,. met"od is simi*ar to t"at of t"e copyRan$e,. met"od e3cept t"at t"e ce**s are moed, rat"er t"an copied7 t"e ce**s in t"e ori$ina* ran$e are *eft empty& 1,.,.,. Cop" data bet1een documents T"e copyRan$e met"od on*y supports copyin$ a ran$e in t"e same document& 1t"er met"ods must be used to copy data bet%een different documents& "ata functions 5se $etData,. and setData,. to copy numbers& 5se $etDataArray,. and setDataArray,. to copy numbers and strin$s& T"e data functions are fast and easy, but t"ey on*y copy data, not formattin$& Clipboard 5se dispatc" commands to copy data usin$ t"e c*ipboard& T"e c*ipboard proides many options %"en copyin$ data& T"e primary issue %it" usin$ t"e c*ipboard, is t"at t"e c*ipboard is in"erent*y unsafe because ot"er app*ications may be usin$ t"e c*ipboard at t"e same time& A*t"ou$" t"e c*ipboard is not in"erent*y safe, 'aste Specia* proides numerous options %"en pastin$ data not aai*ab*e usin$ ot"er met"ods& 484 Listing 416. Use the clipboard to copy data between two documents. o-i#patc(er 6 create0noSer:iceB"co!&#un&#tar&$ra!e&-i#patc(Helper"C o"ra!e> 6 o-oc>&CurrentController&"ra!e ) 0#e t(e docu!ent# controller to #elect t(e cell# A>:B'& oS(eet 6 o-oc>&S(eet#B7C rn 6 oS(eet&etCellRaneB.Ha!eB"A>:B'"C o-oc>&CurrentController&SelectBrnC ) 0#e a di#patc( to cop. to t(e clipboard& o-i#patc(er&execute-i#patc(Bo"ra!e>= "&uno:Cop."= ""= 7= Arra.BCC ) 0pper le$t corner o$ *(ere to pa#te t(e data& rn 6 o-oc'&S(eet#B7C&etCellRaneB.Ha!eB"A>"C ) Place t(e :ie* cur#or t(ere t(en pa#te t(e clipboard& o-oc'&CurrentController&SelectBrnC o"ra!e' 6 o-oc'&CurrentController&"ra!e o-i#patc(er&execute-i#patc(Bo"ra!e'= "&uno:Pa#te"= ""= 7= Arra.BCC 5se t"e macro recorder %it" 'aste Specia* to see "o% ar$uments are set %it" paste specia*& 1ne e3amp*e is as fo**o%s: Listing 417. -rguments for 9aste *pecial. -i! ar#>B<C a# ne* co!&#un&#tar&bean#&Propert.Oalue ar#>B7C&Ha!e 6 ""la#" ar#>B7C&Oalue 6 "SO-H3" ar#>B>C&Ha!e 6 ""or!ulaCo!!and" ar#>B>C&Oalue 6 7 ar#>B'C&Ha!e 6 "S1ipE!pt.Cell#" ar#>B'C&Oalue 6 $al#e ar#>B%C&Ha!e 6 "3ran#po#e" ar#>B%C&Oalue 6 $al#e ar#>B?C&Ha!e 6 "A#,in1" ar#>B?C&Oalue 6 $al#e ar#>B<C&Ha!e 6 "Mo:eMode" ar#>B<C&Oalue 6 ? o-i#patc(er&execute-i#patc(Bo"ra!e'= "&uno:In#ertContent#"= ""= 7= ar#>BCC 0ransferable content Transferab*e content, t"e ne%est met"od aai*ab*e for copyin$ content, returns a copy of t"e se*ected data as t"ou$" it %as copied to t"e c*ipboard, %it"out usin$ t"e c*ipboard& Transferab*e content is a*so aai*ab*e in ;riter documents& 5n*i(e t"e c*ipboard, t"ere is no in"erent prob*ems %it" transferab*e content, but you a*so do not "ae t"e f*e3ibi*ity of paste specia*& Listing 418. Use transferable content to copy data between two documents. -i! o -i! oS(eet -i! oRane -i! o-oc oRane 6 o-oc>&S(eet#B7C&etCellRaneB.Ha!eB"B':C%"C o-oc>&CurrentController&#electBoRaneC o 6 o-oc>&CurrentController&et3ran#$erableBC
485 oRane 6 o-oc'&S(eet#B7C&etCellRaneB.Ha!eB"">"C o-oc'&CurrentController&#electBoRaneC o-oc'&CurrentController&in#ert3ran#$erableBoC 1,.,... (ata pilot and pi'ot tables 1pen1ffice&or$ "as a feature named Data 'i*ot, but Libre1ffice c"an$ed t"e name t"e 'iot Tab*es& T"is section assumes t"at you a*ready (no% and understand t"e feature, and mere*y demonstrates "o% imp*ement some of t"e functions usin$ macros& Tip ) cou*d %rite a *ar$e section on t"e numerous uses of data pi*ot tab*es& To $et a fee* for t"e possibi*ities, *oo( at t"e input tab*e in 2rror: Reference source not found and t"en inspect t"e summary data in 0i$ure 10M, %"ic" is automatica**y $enerated by t"e data pi*ot functiona*ity& T"e Data'i*ot is a po%erfu* mec"anism t"at a**o%s you to combine, compare, and ana*yCe *ar$e amounts of data& T"e Data'i*ot manipu*ates portions of t"e data from t"e Dsource tab*eF and t"en disp*ays t"e resu*ts in a ne% *ocation& 5nfortunate*y, numerous detai*s are ino*ed %it" t"e creation and manipu*ation of data pi*ot tab*es, but t"is is due to t"eir enormous f*e3ibi*ity& T"ere are numerous detai*s %it" respect to creatin$ and usin$ data pi*ot tab*es& A*t"ou$" t"e numerous detai*s are *o$ica* and strai$"tfor%ard, t"ey are so many t"at it is easy to become *ost in t"e detai*s& )tGs instructie, t"erefore, to reie% a simp*e e3amp*e t"at c*arifies t"e detai*s& )G** present t"e specific types and enumerations fo**o%in$ t"e e3amp*e7 you can reie% t"ese as re8uired& 2 data pilot e:ample 0or t"is e3amp*e, ) assume a fa(e company t"at se**s boo(s, candy, and pens& T"e company "as offices in t"ree states and mu*tip*e sa*espeop*e in eac" state& ) created a spreads"eet t"at s"o%s t"e sa*es for eac" product bro(en do%n by sa*esperson and year& T"e fina* $oa* of t"is e3amp*e is to create a data pi*ot tab*e t"at summariCes t"e sa*es of eac" product by type and state& T"e initia* data used for t"is e3amp*e in s"o%n in Tab*e 1BA& 486 Table 195. #ata values used for the #ata9ilot , 9ivotable e.amples. )tem State Team 2002 2003 200! +oo(s Mic"i$an Kean Y1!,M@@&00 Y30,222&00 Y23,!B0&00 #andy Mic"i$an Kean Y26,3@@&00 Y1A,6!1&00 Y32,@!B&00 'ens Mic"i$an Kean Y16,A6B&00 Y32,6MA&00 Y2A,3B6&00 +oo(s Mic"i$an Oo*(er Y21,B61&00 Y21,2!2&00 Y2B,00B&00 #andy Mic"i$an Oo*(er Y26,1!2&00 Y22,!0M&00 Y32,@!1&00 'ens Mic"i$an Oo*(er Y2B,1!B&00 Y1@,320&00 Y3!,!2B&00 +oo(s 1"io Rebecca Y21,@!A&00 Y33,A03&00 Y32,200&00 #andy 1"io Rebecca Y23,MBB&00 Y23,ABM&00 Y23,020&00 'ens 1"io Rebecca Y2@,32@&00 Y1M,B30&00 Y23,303&00 +oo(s 1"io #at"erine Y22,MBM&00 Y31,3@6&00 Y3B,!B0&00 #andy 1"io #at"erine Y13,613&00 Y16,1M!&00 Y3A,163&00 'ens 1"io #at"erine Y1M,103&00 Y32,A63&00 Y3A,@0!&00 +oo(s <entuc(y Mic"e**e Y2B,BA2&00 Y1B,133&00 Y33,!@0&00 #andy <entuc(y Mic"e**e Y1A,3!@&00 Y31,0B!&00 Y3B,M22&00 'ens <entuc(y Mic"e**e Y2!,3A@&00 Y2M,236&00 Y2M,12B&00 +oo(s <entuc(y Andy Y1M,1BB&00 Y26,3@6&00 Y30,!A0&00 #andy <entuc(y Andy Y11,62@&00 Y1@,232&00 Y2@,BA3&00 'ens <entuc(y Andy Y23,@2@&00 Y32,031&00 Y3M,AA1&00 Generating the data T"e data s"o%n in Tab*e 1BA is $enerated by t"e macro in Listin$ !1B, %"ic" sets bot" t"e data and t"e formattin$& ;atc" for t"e fo**o%in$ tec"ni8ues: Generating random data. Setting all of the data at one time using the method setDataArray(). Centering the headers and setting the cell background color. Formatting a cell as currency. 487 Listing 419. /reate the document used for the #ata9ilot , 9ivotable e.amples. "unction createPi:ot3able-ocBC -i! o-oc )Re$erence ne*l. created calc docu!ent& -i! oS(eet -i! oRane -i! o-ata -i! o"or!at#
) Set t(e title area oRane 6 oS(eet&etCellRaneB.Ha!eB"A>:">"C oRane&HoriMu#ti$. 6 co!&#un&#tar&table&CellHoriMu#ti$.&CEH3ER oRane&CellBac1Color 6 RJBB''<= ''<= ''<C
) "or!at nu!ber# a# currenc. o"or!at# 6 o-oc&Hu!ber"or!at# -i! a,ocale A# He* co!&#un&#tar&lan&,ocale oRane 6 oS(eet&etCellRaneB.Ha!eB"-':">@"C oRane&Hu!ber"or!at 6 o"or!at#&etStandard"or!atB5 co!&#un&#tar&util&Hu!ber"or!at&C0RREHCP= a,ocaleC createPi:ot3able-oc 6 o-oc End "unction Creating the data pilot table T"e macro in Listin$ !20 creates and inserts a data pi*ot tab*e as fo**o%s: 1& #reate t"e data pi*ot tab*e descriptor usin$ t"e met"od createData'i*otDescriptor,.& 2& Set t"e source ran$e of t"e data to use& 488 3& #onfi$ure %"ic" co*umn is used for %"ic" purpose& !& )nsert t"e data pi*ot tab*e descriptor into t"e set of tab*es& Listing 420. /reate#ata9ilotable is in the /alc module in this chapterSs source code files as */(2.s.c. Sub Create-ataPilot3ableBC -i! oS(eet )S(eet t(at contain# t(e data pilot -i! oRane )Rane $or t(e data pilot #ource -i! oRaneAddre##)3(e addre## o$ t(e rane obNect -i! o3able# )Collection o$ data pilot table# -i! o3-e#criptor )A #inle data pilot de#criptor -i! o"ield# )Collection o$ all $ield# -i! o"ield )A #inle $ield -i! oCellAddre## A# He* co!&#un&#tar&table&CellAddre## -i! o-oc o-oc 6 createPi:ot3able-ocBC oS(eet 6 o-oc&S(eet#&etB.IndexB7C oRane 6 oS(eet&etCellRaneB.Ha!eB"A>:">@"C
REM Sure= I could #i!pl. #peci$. t(e addre##= but t(i# i# !uc( !ore $unK REM Set t(e de#tination addre## to be t*o ro*# belo* t(e data& oRaneAddre## 6 oRane&etRaneAddre##BC oCellAddre##&S(eet 6 oRaneAddre##&S(eet oCellAddre##&Colu!n 6 oRaneAddre##&StartColu!n oCellAddre##&Ro* 6 oRaneAddre##&EndRo* W '
o3able# 6 oS(eet&et-ataPilot3able#BC
REM Step >= create t(e de#criptor o3-e#criptor 6 o3able#&create-ataPilot-e#criptorBC
REM Step '= Set t(e #ource rane o3-e#criptor&#etSourceRaneBoRaneAddre##C
REM Step %= Set t(e $ield# o"ield# 6 o3-e#criptor&et-ataPilot"ield#BC
REM Colu!n 7 in t(e #ource i# Ite! and I *ant t(i# a# a ro* ite!& o"ield 6 o"ield#&etB.IndexB7C o"ield&Orientation 6 co!&#un&#tar&#(eet&-ataPilot"ieldOrientation&ROW
REM Colu!n > in t(e #ource i# State and I *ant t(i# a# a colu!n ite!& o"ield 6 o"ield#&etB.IndexB>C o"ield&Orientation 6 co!&#un&#tar&#(eet&-ataPilot"ieldOrientation&CO,0MH
REM Colu!n % in t(e #ource i# '77'& Create a #u! in t(e data $or t(i#K o"ield 6 o"ield#&etB.IndexB%C o"ield&Orientation 6 co!&#un&#tar&#(eet&-ataPilot"ieldOrientation&-A3A o"ield&"unction 6 co!&#un&#tar&#(eet&Jeneral"unction&S0M
o3able#&in#ertHe*B.Ha!eB"M."ir#t-ataPilot"= oCellAddre##= o3-e#criptorC End Sub 489 +igure (CT. he macro in Listing 2=C inserts the data pilot table immediately after the source data. Manipulating data pilot tables T"e $etData'i*otTab*es,. met"od, supported by eac" spreads"eet, returns an ob/ect t"at supports t"e serice com&sun&star&s"eet&Data'i*otTab*es& T"e returned serice proides access to t"e data pi*ot tab*es in t"e spreads"eet usin$ bot" inde3ed and enumeration access& T"e Data'i*otTab*es ob/ect a*so supports t"e met"ods in Tab*e 1B6& able (1G. Methods defined by the com.sun.star.sheet.:#ata9ilotables interface. )et6od Description createData'i*otDescriptor,. #reate a ne% data pi*ot descriptor& insert4e%+y4ame,name, #e**Address, Data'i*otDescriptor. Add a ne% data pi*ot tab*e to t"e co**ection t"at uses t"e proided #e**Address ,see Tab*e 1AB. as t"e top9*eft corner of t"e tab*e& remoe+y4ame,name. De*ete a data pi*ot tab*e from t"e co**ection& (ata pilot fields 2ac" Dfie*dF in t"e created data pi*ot tab*e is represented by a co*umn in t"e source data pi*ot tab*e ,ce** ran$e. and is named usin$ t"e topmost ce** of t"e co*umn in t"e ran$e& T"e fie*d name is aai*ab*e t"rou$" t"e met"ods $et4ame,. and set4ame,Strin$.& 2ac" fie*d contains an 1rientation property of type Data'i*ot0ie*d1rientation t"at specifies "o% t"e fie*d is used in t"e fina* output ,see Tab*e 1BM.& T"e 0unction property specifies t"e function used to ca*cu*ate resu*ts for t"is fie*d based on t"e Jenera*0unction enumeration ,see Tab*e 1M@.& able (1T. 3alues defined by the com.sun.star.sheet.#ata9ilot+ieldOrientation enumeration. Vale Description com&sun&star&s"eet&Data'i*ot0ie*d1rientation&E)DD24 Do not use t"e fie*d& com&sun&star&s"eet&Data'i*ot0ie*d1rientationL5M4 5se t"e fie*d as a co*umn fie*d& com&sun&star&s"eet&Data'i*ot0ie*d1rientation&R1; 5se t"e fie*d as a ro% fie*d& com&sun&star&s"eet&Data'i*ot0ie*d1rientation&'AJ2 5se t"e fie*d as a pa$e fie*d& com&sun&star&s"eet&Data'i*ot0ie*d1rientation&DATA 5se t"e fie*d as a data fie*d& 490 +iltering data pilot fields T"e fie*ds in t"e created tab*e may be conditiona**y disp*ayed based on a 0i*ter1perator ,see Tab*e 1B@.& able (10. 3alues defined by the com.sun.star.sheet.+ilterOperator enumeration. Vale Description com&sun&star&s"eet&0i*ter1perator&2M'T6 Se*ect empty entries& com&sun&star&s"eet&0i*ter1perator&41T=2M'T6 Se*ect nonempty entries& com&sun&star&s"eet&0i*ter1perator&2_5AL T"e entryGs a*ue must e8ua* t"e specified a*ue& com&sun&star&s"eet&0i*ter1perator&41T=2_5AL T"e entryGs a*ue must not be e8ua* to t"e specified a*ue& com&sun&star&s"eet&0i*ter1perator&JR2AT2R T"e entryGs a*ue must be $reater t"an t"e specified a*ue& com&sun&star&s"eet&0i*ter1perator&JR2AT2R=2_5AL T"e entryGs a*ue must be $reater t"an or e8ua* to t"e specified a*ue& com&sun&star&s"eet&0i*ter1perator&L2SS T"e entryGs a*ue must be *ess t"an t"e specified a*ue& com&sun&star&s"eet&0i*ter1perator&L2SS=2_5AL T"e entryGs a*ue must be *ess t"an or e8ua* to t"e specified a*ue& com&sun&star&s"eet&0i*ter1perator&T1'=OAL52S Se*ect a specified number %it" t"e $reatest a*ues& com&sun&star&s"eet&0i*ter1perator&T1'='2R#24T Se*ect a specified percenta$e %it" t"e $reatest a*ues& com&sun&star&s"eet&0i*ter1perator&+1TT1M=OAL52S Se*ect a specified number %it" t"e *o%est a*ues& com&sun&star&s"eet&0i*ter1perator&+1TT1M='2R#24T Se*ect a specified percenta$e %it" t"e *o%est a*ues& T"e indiidua* fi*ter operators are combined usin$ t"e 0i*ter#onnection enumeration ,see Tab*e 1BB.& 2ac" indiidua* fi*ter fie*d is stored in a Tab*e0i*ter0ie*d structure ,see Tab*e 200.& T"e entire co**ection of Tab*e0i*ter0ie*ds is stored in a S"eet0i*terDescriptor& T"e descriptor supports t"e met"ods $et0i*ter0ie*ds,. and set0i*ter0ie*ds,., to $et and set t"e tab*e fi*ter fie*ds as an array of Tab*e0i*ter0ie*d structures& T"e properties in Tab*e 201 are defined by t"e S"eet0i*terDescriptor to direct t"e fi*terin$ process& able (11. 3alues defined by the com.sun.star.sheet.+ilter/onnection enumeration. Vale Description com&sun&star&s"eet&0i*ter#onnection&A4D +ot" conditions must be satisfied& com&sun&star&s"eet&0i*ter#onnection&1R At *east one of t"e conditions must be satisfied& 491 able =CC. 9roperties in the com.sun.star.sheet.able+ilter+ield structure. Property Description #onnection Specify "o% t"e condition is connected to t"e preious condition as a 0i*ter#onnection ,see Tab*e 1BB.& 0ie*d Specify %"ic" fie*d ,co*umn. is used for t"e condition as a Lon$ )nte$er& 1perator Specify t"e condition type as a 0i*ter1perator ,see Tab*e 1B@.& )s4umeric )f True, t"e 4umericOa*ue property is used7 ot"er%ise t"e Strin$Oa*ue is used& 4umericOa*ue Specify a numeric a*ue for t"e condition as a Doub*e& Strin$Oa*ue Specify a Strin$ a*ue for t"e condition& able =C(. 9roperties defined by the com.sun.star.sheet.*heet+ilter#escriptor service. Property Description )s#aseSensitie )f True, strin$ comparisons are case sensitie& S(ipDup*icates )f True, dup*icate entries are not inc*uded in t"e resu*t& 5seRe$u*ar23pressions )f True, strin$ a*ues in t"e Tab*e0i*ter0ie*d structure are interpreted as re$u*ar e3pressions& Sae1utput'osition )f True ,and #opy1utpuData is True., t"e 1utput'osition is saed for future ca**s& 1rientation Specify if co*umns or ro%s are fi*tered usin$ t"e Tab*e1rientation enumeration ,see Tab*e 1B2.& #ontainsEeader )f True, t"e first ro% ,or co*umn. is assumed to be a "eader and is not fi*tered& #opy1utputData )f True, t"e fi*tered data is copied to t"e 1utput'osition& 1utput'osition Specify %"ere fi*tered data is copied as a #e**Address ,see Tab*e 1AB.& Ma30ie*d#ount T"e ma3imum number of fi*ter fie*ds in t"e descriptor as a Lon$ )nte$er& Tables 2ac" data pi*ot tab*e is based on a spreads"eet ce** ran$e& 2ac" data pi*ot tab*e supports t"e ob/ect met"od $et1utputRan$e,., %"ic" returns a #e**Ran$eAddress ,see Tab*e 166.& T"e refres",. met"od re9creates t"e tab*e usin$ t"e current data in t"e source ran$e& 2ac" data pi*ot tab*e a*so suports t"e Data'i*otDescriptor serice, %"ic" defines t"e met"ods in Tab*e 202& 492 able =C=. Methods defined by the com.sun.star.sheet.:#ata9ilot#escriptor interface. )et6od Description $etTa$,. Jet t"e data pi*ot tab*e ta$ as a Strin$& setTa$,Strin$. Set t"e data pi*ot tab*e ta$& $etSourceRan$e,. Return t"e #e**Ran$eAddress ,see Tab*e 166. containin$ t"e data for t"e data pi*ot tab*e& setSourceRan$e,#e**Ran$eAddress. Set t"e ce** ran$e containin$ t"e data for t"e data pi*ot tab*e& $et0i*terDescriptor,. Jet t"e S"eet0i*terDescriptor ,see Tab*e 201. t"at specifies %"ic" data from t"e source ce** ran$e is used for t"e data pi*ot tab*e& $etData'i*ot0ie*ds,. Jet t"e data pi*ot fie*ds as an ob/ect t"at supports inde3ed access& $et#o*umn0ie*ds,. Jet t"e data pi*ot fie*ds used as co*umn fie*ds as an ob/ect t"at supports inde3ed access& $etRo%0ie*ds,. Jet t"e data pi*ot fie*ds used as ro% fie*ds as an ob/ect t"at supports inde3ed access& $et'a$e0ie*ds,. Jet t"e data pi*ot fie*ds used as pa$e fie*ds as an ob/ect t"at supports inde3ed access& $etData0ie*ds,. Jet t"e data pi*ot fie*ds used as data fie*ds as an ob/ect t"at supports inde3ed access& $etEidden0ie*ds,. Jet t"e data pi*ot fie*ds t"at are not used as co*umn, ro%, pa$e, or data fie*ds& 1,.,./. heet cursors )n a #a*c document, a cursor is a ce** ran$e t"at contains met"ods to moe t"rou$" t"e contained ce**s& #ursors are not used as fre8uent*y %it" #a*c documents as %it" ;riter documents because, un*i(e ;riter documents, most content is direct*y accessib*e by inde3 or name& S"eet cursors, *i(e ce** ran$es, are *imited to one s"eet at a time& T"e S"eet#e**#ursor serice used by #a*c documents is simi*ar to ce** cursors used in te3t tab*es ,see Tab*e 203.& able =CF. 9rimary components supported by the com.sun.star.sheet.*heet/ell/ursor service. Component Description com&sun&star&tab*e&#e**#ursor Met"ods to contro* t"e position of a ce** cursor& com&sun&star&tab*e&#e**Ran$e Met"ods to access ce**s or subran$es of a ce** ran$e ,see Tab*e 1M3.& com&sun&star&s"eet&IS"eet#e**#ursor Adanced met"ods to contro* t"e position of t"e cursor& com&sun&star&s"eet&S"eet#e**Ran$e A rectan$u*ar ran$e of ce**s in a spreads"eet document7 t"is is an e3tension of t"e #e**Ran$e serice for use in spreads"eet documents& com&sun&star&s"eet&I5sedArea#ursor Met"ods to find t"e used area in a s"eet& T"e primary met"ods supported by t"e S"eet#e**#ursor are s"o%n in Tab*e 20!& 493 able =C2. 9rimary methods supported by the com.sun.star.sheet.*heet/ell/ursor service. Interface )et6od Description I#e**#ursor $otoStart,. Moe t"e cursor to t"e first fi**ed ce** at t"e be$innin$ of a conti$uous series of fi**ed ce**s& T"is ce** may be outside t"e cursorGs ran$e& I#e**#ursor $oto2nd,. Moe t"e cursor to t"e *ast fi**ed ce** at t"e end of a conti$uous series of fi**ed ce**s& T"is ce** may be outside t"e cursorGs ran$e& I#e**#ursor $oto4e3t,. Moe t"e cursor to t"e ne3t ,ri$"t. unprotected ce**& I#e**#ursor $oto'reious,. Moe t"e cursor to t"e preious ,*eft. unprotected ce**& I#e**#ursor $oto1ffset,n#o*, nRo%. S"ift t"e cursorGs ran$e re*atie to t"e current position& 4e$atie numbers s"ift *eft and up7 positie numbers s"ift ri$"t and do%n& I#e**Ran$e $et#e**+y'osition,*eft, top. Jet a ce** %it"in t"e ran$e& I#e**Ran$e $et#e**Ran$e+y'osition,*eft , top, ri$"t, bottom. Jet a ce** ran$e %it"in t"e ran$e& I#e**Ran$e $et#e**Ran$e+y4ame,name . Jet a ce** ran$e %it"in t"e ran$e based on its name& T"e strin$ direct*y references ce**s usin$ t"e standard formats L suc" as D+2:DAF or DY+Y2F L or defined ce** ran$e names& IS"eet#e**#ursor co**apseTo#urrentRe$ion,. 23pand t"e ran$e to contain a** conti$uous nonempty ce**s& IS"eet#e**#ursor co**apseTo#urrentArray,. 23pand t"e ran$e to contain t"e current array formu*a& IS"eet#e**#ursor co**apseToMer$edArea,. 23pand t"e ran$e to contain mer$ed ce**s t"at intersect t"e ran$e& IS"eet#e**#ursor e3pandTo2ntire#o*umns,. 23pand t"e ran$e to contain a** co*umns t"at intersect t"e ran$e& IS"eet#e**#ursor e3pandTo2ntireRo%s,. 23pand t"e ran$e to contain a** ro%s t"at intersect t"e ran$e& IS"eet#e**#ursor co**apseToSiCe,n#o*s, nRo%s. ;it"out c"an$in$ t"e upper9*eft corner, set t"e cursor ran$e siCe& IS"eet#e**Ran$e $etSpreads"eet,. Jet t"e s"eet ob/ect t"at contains t"e ce** ran$e& I5sedArea#ursor $otoStart1f5sedArea,. Set t"e cursor to t"e start of t"e used area& I5sedArea#ursor $oto2nd1f5sedArea,. Set t"e cursor to t"e end of t"e used area& #e** ran$es, and t"erefore ce** cursors, dea* %it" rectan$u*ar re$ions& T"e use of rectan$u*ar re$ions may be obious no% t"at ) state it, but it cau$"t me by surprise %"en ) tested t"e $otoStart,. and $oto2nd,. met"ods *isted in Tab*e 20!& ) started %it" t"e confi$uration s"o%n in 0i$ure BB %"en %ritin$ t"e code in Listin$ !21& Listing 421. *imple cursor movement commands use contiguous blocks. oCur# 6 oS(eet&createCur#orB.RaneBoS(eet&etCellRaneB.Ha!eB"C%"CC oCur#&otoStartBC REM Mo:e t(e cur#or to cell B> oCur#&otoEndBC REM Mo:e t(e cur#or to cell EQ oCur#&otoStartBC REM Mo:e t(e cur#or to cell EQ T"e first *ine in Listin$ !21 positions t"e cursor at ce** #3, ri$"t in t"e midd*e of a b*oc( of a*ues& )n 0i$ure BB, t"e *eftmost conti$uous co*umn is + and t"e topmost conti$uous ro% is 1& T"e met"od $otoStart,., t"erefore, positions t"e cursor in t"e top9*eft corner at *ocation +1& T"is is %"ere t"in$s become a *itt*e bit une3pected& T"e ri$"tmost conti$uous co*umn is 2 and t"e bottommost conti$uous ro% is @& T"e met"od $oto2nd,., t"erefore, positions t"e cursor at *ocation 2@& As it is s"o%n in 0i$ure BB, t"e ce** 2@ is comp*ete*y disconnected from t"e conti$uous $roup of ce**s& T"e cursor is positioned to ce** 2@, een if it 494 does not contain a a*ue& T"e cursor is no *on$er re*ated to t"e ori$ina* b*oc( of ce**s, so t"e met"od $otoStart,. does not moe t"e cursor bac( to ce** +1& To understand t"e be"aior of Listin$ !21, itGs important to understand "o% 11o determines conti$uous ce**s, because it isnGt documented any%"ere t"at ) can find& 23perimenta**y, ) "ae determined t"at t"e set of conti$uous nonempty ce**s is defined as t"e sma**est ran$e ,s8uare b*oc( of ce**s. t"at can be enc*osed by empty ce**s& )f ce** 2B contained a a*ue, t"en een t"ou$" ce**s 2@ and 2B are not direct*y connected ia nonempty ce**s to t"e ori$ina* b*oc( of ce**s, t"ey %ou*d bot" be considered part of t"e b*oc( of conti$uous nonempty ce**s& T"e met"od co**apseTo#urrentRe$ion,. causes t"e cursor to contain t"e b*oc( of conti$uous ce**s& T"e on*y caeat is t"at after t"e ran$e is co**apsed, it a*%ays contains t"e ori$ina* ran$e, een if t"is ran$e inc*udes unnecessary empty ce**s& T"e met"od co**apseTo#urrentArray,. is simi*ar to co**apseTo#urrentRe$ion,., e3cept t"at it returns a ran$e t"at contains an array formu*a& T"e upper9*eft corner of t"e re$ion must inc*ude an array formu*a for t"e co**apseTo#urrentArray,. met"od to %or(& T"e code snippet in Listin$ !22 creates a cursor oer a ran$e and t"en demonstrates t"at $et#e**+y'osition,. and $et#e**Ran$e+y'osition,. are re*atie to t"e upper9*eft corner of t"e ran$e& T"e met"od $et#e**Ran$e+y4ame,. $enerates an e3ception if a ce** outside t"e ran$e is re8uested& Listing 422. *ome commands work only relative to the range. oCur# 6 oS(eet&createCur#orB.RaneBoS(eet&etCellRaneB.Ha!eB"C%:">'"CC oCell 6 oCur#&etCellB.Po#itionB7= 7C REM Cell C% oRane 6 oCur#&etCellRaneB.Po#itionB>= 7= %= 'C REM -%:"< oRane 6 oCur#&etCellRaneB.Ha!eB"C?:-A"C REM C?:-A oRane 6 oCur#&etCellRaneB.Ha!eB"C':-A"C REM Error C' not in raneK Tip T"e met"ods $et#e**+y'osition,., $et#e**Ran$e+y'osition,., and $et#e**Ran$e+y4ame,. cannot return a a*ue t"at is not in t"e ran$e& 1.#. Calc documents Many of t"e document9*ee* met"ods and properties affect t"e entire document L for e3amp*e, t"e abi*ity to sae and print a document& 1t"er met"ods and properties e3ist pure*y as a conenience and t"e information is a*so aai*ab*e at t"e s"eet *ee*& 0or e3amp*e, t"e #a*c document acts as a dra%9pa$e supp*ier to access a** of t"e dra% pa$es, een t"ou$" t"ey are aai*ab*e indiidua**y from t"e s"eet t"at contains t"em& 1,...1. -amed range T"e officia* definition of a named ran$e is a named formu*a e3pression& Typica**y, a named ran$e represents a ce** ran$e, but it may a*so refer to e3terna* data& 4amin$ ran$es a**o%s you to $ie meanin$fu* names to t"in$s t"at you reference& 4amed ran$es may t"erefore be used as an address in a formu*a7 for e3amp*e, after definin$ a ran$e named Scores, ) can use t"e formu*a ?Sum,Scores.& T"e 4amedRan$e0*a$ constants define "o% a named ran$e may be used ,see Tab*e 20A.& 495 able =CI. /onstants defined by the com.sun.star.sheet.NamedRange+lag constant group. Vale %ame Description 1 0)LT2R=#R)T2R)A T"e ran$e contains fi*ter criteria& 2 'R)4T=AR2A T"e ran$e can be used as a print ran$e& ! #1L5M4=E2AD2R T"e ran$e can be used as co*umn "eaders for printin$& @ R1;=E2AD2R T"e ran$e can be used as ro% "eaders for printin$& 2ac" named ran$e serice supports t"e met"ods in Tab*e 206& able =CG. Methods implemented by the com.sun.star.sheet.NamedRange service. )et6od Description $etReferred#e**s,. Jet t"e #e**Ran$e referenced by named ran$e& $et#ontent,. T"e named ran$e content is a strin$ and can be a reference to a ce**, ce** ran$e, or formu*a e3pression& set#ontent,Strin$. Set t"e content of t"e named ran$e& $etReference'osition,. Jet t"e #e**Address used as a base for re*atie references in t"e content& setReference'osition,#e**Address. Set t"e reference position& $etType,. Jet t"e type as a 4amedRan$e0*a$ constant ,see Tab*e 20A.& setType,4amedRan$e0*a$. Set t"e type of t"e named ran$e& T"e documentGs 4amedRan$es property contains t"e co**ection of named ran$es in t"e document& 6ou can e3tract eac" indiidua* named ran$e by usin$ named and inde3ed access& T"e met"od add4e%+yname,. accepts four ar$uments7 t"e name, content, position, and type& T"e fourt" ar$ument to t"e met"od add4e%+y4ame,. is a combination of f*a$s t"at specify "o% t"e named ran$e %i** be used L t"e most common a*ue is 0, %"ic" is not a defined constant a*ue& T"e name and t"e content are bot" of type Strin$& T"e #e**Address specifies t"e base address for re*atie ce** references& Listing 423. /reate a named range that references V*heet(.V!VFJV#VG. Sub AddHa!edRaneBC -i! oRane ) 3(e created rane& -i! oRane# ) All na!ed rane#& -i! #Ha!eF ) Ha!e o$ t(e na!ed rane to create& -i! oCell ) Cell obNect& -i! #F #Ha!eF 6 "M.HRane" oRane# 6 3(i#Co!ponent&Ha!edRane# I$ HO3 oRane#&(a#B.Ha!eB#Ha!eFC 3(en REM I can obtain t(e cell addre## b. obtainin t(e cell REM and t(en extractin t(e addre## $ro! t(e cell& -i! oCellAddre## A# ne* co!&#un&#tar&table&CellAddre## oCellAddre##&S(eet 6 7 )3(e $ir#t #(eet& oCellAddre##&Colu!n 6 > )Colu!n B& oCellAddre##&Ro* 6 ' )Ro* %& 496 REM 3(e $ir#t aru!ent i# t(e rane na!e& REM 3(e #econd aru!ent i# $or!ula or expre##ion to REM u#e& 3(e #econd aru!ent i# u#uall. a #trin t(at REM de$ine# a rane& REM 3(e t(ird aru!ent #peci$ie# t(e ba#e addre## $or REM relati:e cell re$erence#& REM 3(e $ourt( aru!ent i# a #et o$ $la# t(at de$ine REM (o* t(e rane i# u#ed= but !o#t rane# u#e 7& REM 3(e $ourt( aru!ent u#e# :alue# $ro! t(en REM Ha!edRane"la con#tant# B#ee "iure %C& #F 6 "FS(eet>&FBF%:F-FA" oRane#&addHe*B.Ha!eB#Ha!eF= #F= oCellAddre##= 7C End I$ REM Jet a rane u#in t(e created na!ed rane& oRane 6 3(i#Co!ponent&Ha!edRane#&etB.Ha!eB#Ha!eFC REM Print t(e #trin contained in cell FS(eet>&FBF% oCell 6 oRane&etRe$erredCell#BC&etCellB.Po#itionB7=7C Print oCell&etStrinBC End Sub T"e t"ird ar$ument, a ce** address, acts as t"e base address for ce**s referenced in a re*atie %ay& )f t"e ce** ran$e is not specified as an abso*ute address, t"e referenced ran$e %i** be different based on %"ere in t"e spreads"eet t"e ran$e is used& T"e re*atie be"aior is i**ustrated in Listin$ !2!, %"ic" a*so i**ustrates anot"er usa$e of a named ran$eLdefinin$ an e8uation& T"e macro creates t"e named ran$e AddLeft, %"ic" refers to t"e e8uation A3N+3 %it" #3 as t"e reference ce**& T"e ce**s A3 and +3 are t"e t%o ce**s direct*y to t"e *eft of #3, so, t"e e8uation ?AddLeft,. ca*cu*ates t"e sum of t"e t%o ce**s direct*y to t"e *eft of t"e ce** t"at contains t"e e8uation& #"an$in$ t"e reference ce** to #!, %"ic" is be*o% A3 and +3, causes t"e AddLeft e8uation to ca*cu*ate t"e sum of t"e t%o ce**s t"at are to t"e *eft on t"e preious ro%& Listing 424. /reate the -ddLeft named range. ,i#tin '& Create t(e Add,e$t na!ed rane& Sub AddHa!ed"unctionBC -i! oS(eet )S(eet t(at contain# t(e na!ed rane& -i! oCellAddre## )Addre## $or relati:e re$erence#& -i! oRane# )3(e Ha!edRane# propert.& -i! oRane )Sinle cell rane& -i! #Ha!e A# Strin )Ha!e o$ t(e e;uation to create& #Ha!e 6 "Add,e$t" oRane# 6 3(i#Co!ponent&Ha!edRane# I$ HO3 oRane#&(a#B.Ha!eB#Ha!eC 3(en oS(eet 6 3(i#Co!ponent&etS(eet#BC&etB.IndexB7C oRane 6 oS(eet&etCellRaneB.Ha!eB"C%"C oCellAddre## 6 oRane&etCellAddre##BC oRane#&addHe*B.Ha!eB#Ha!e= "A%WB%"= oCellAddre##= 7C End I$ End Sub 5se t"e met"od add4e%0romTit*es,#e**Ran$eAddress, +order. to create named ce** ran$es from tit*es in a ce** ran$e& T"e +order a*ue is ta(en from Tab*e 20M and it specifies %"ere t"e tit*es are *ocated in t"e ce** ran$e& 497 Table 207. $numerated values defined by the com.sun.star.sheet.!order enumeration. Vale Description com&sun&star&s"eet&+order&T1' Se*ect t"e top border& com&sun&star&s"eet&+order&+1TT1M Se*ect t"e bottom border& com&sun&star&s"eet&+order&R)JET Se*ect t"e ri$"t border& com&sun&star&s"eet&+order&L20T Se*ect t"e *eft border& T"e ne3t macro creates t"ree named ran$es based on t"e top ro% of a named ran$e& Listing 425. /reate many named ranges. Sub AddMan.Ha!edRane#BC -i! oS(eet )S(eet t(at contain# t(e na!ed rane& -i! oAddre## )Rane addre##& -i! oRane# )3(e Ha!edRane# propert.& -i! oRane )Sinle cell rane& oRane# 6 3(i#Co!ponent&Ha!edRane# oS(eet 6 3(i#Co!ponent&etS(eet#BC&etB.IndexB7C oRane 6 oS(eet&etCellRaneB.Ha!eB"A>:C'7"C oAddre## 6 oRane&etRaneAddre##BCd oRane#&addHe*"ro!3itle#BoAddre##= co!&#un&#tar&#(eet&Border&3OPC End Sub 5se t"e met"od outputList,#e**Address. to %rite a *ist of t"e named ran$es to a s"eet& T"e first co*umn contains t"e name of eac" named ran$e, and t"e second co*umn contains t"e content& 0ina**y, use t"e remoe+y4ame,name. met"od to remoe a named ran$e& 1,...2. (atabase range A*t"ou$" a database ran$e can be used as a re$u*ar named ran$e, a database ran$e a*so defines a ran$e of ce**s in a spreads"eet to be used as a database& 2ac" ro% in a ran$e corresponds to a record and eac" ce** corresponds to a fie*d& 6ou can sort, $roup, searc", and perform ca*cu*ations on t"e ran$e as if it %ere a database& A database ran$e proides be"aior t"at is usefu* %"en performin$ database re*ated actiities& 0or e3amp*e, you can mar( t"e first ro% as "eadin$s& To create, modify, or de*ete a database ran$e, use $ata > $efine %ange to open t"e Define Data Ran$e dia*o$& )n a macro, a database ran$e is accesses, created, and de*eted from t"e DatabaseRan$es property& T"e fo**o%in$ macro creates a database ran$e named DMy4ameF and sets t"e ran$e to be used as an auto fi*ter& Listing 426. /reate a database range and an auto filter. Sub AddHe*-ataba#eRaneBC -i! oRane )-ataba#eRane obNect& -i! oAddr )Cell addre## rane $or t(e databa#e rane& -i! oS(eet )"ir#t #(eet= *(ic( *ill contain t(e rane& -i! o-oc )Re$erence 3(i#Co!ponent *it( a #(orter na!e& o-oc 6 3(i#Co!ponent I$ HO3 o-oc&-ataba#eRane#&(a#B.Ha!eB"M.Ha!e"C 3(en 498 oS(eet 6 3(i#Co!ponent&etS(eet#BC&etB.IndexB7C oRane 6 oS(eet&etCellRaneB.Ha!eB"A>:">7"C oAddr 6 oRane&etRaneAddre##BC o-oc&-ataba#eRane#&addHe*B.Ha!eB"M.Ha!e"= oAddrC End I$ oRane 6 o-oc&-ataba#eRane#&etB.Ha!eB"M.Ha!e"C oRane&Auto"ilter 6 3rue End Sub 1,...#. +ilters 5se fi*ters to *imit t"e isib*e ro%s in a spreads"eet& Jeneric fi*ters, common to a** sorts of data manipu*ations, are automatica**y proided by t"e auto fi*ter capabi*ity& 6ou can a*so define your o%n fi*ters& Listing 427. /reate a simple sheet filter. Sub Si!pleS(eet"ilterBC -i! oS(eet ) S(eet t(at *ill contain t(e $ilter& -i! o"ilter-e#c ) "ilter de#criptor& -i! o"ield#B7C A# He* co!&#un&#tar&#(eet&3able"ilter"ield
oS(eet 6 3(i#Co!ponent&etS(eet#BC&etB.IndexB7C
REM I$ aru!ent i# 3rue= create# an e!pt. $ilter REM de#criptor& I$ aru!ent i# "al#e= create a REM de#criptor *it( t(e pre:iou# #ettin#& o"ilter-e#c 6 oS(eet&create"ilter-e#criptorB3rueC
Wit( o"ield#B7C REM I could u#e t(e Connection propert. to indicate REM (o* to connect to t(e pre:iou# $ield& 3(i# i# REM t(e $ir#t $ield #o t(i# i# not re;uired& )&Connection 6 co!&#un&#tar&#(eet&"ilterConnection&AH- )&Connection 6 co!&#un&#tar&#(eet&"ilterConnection&OR REM 3(e "ield propert. i# t(e 8ero ba#ed colu!n REM nu!ber to $ilter& I$ .ou (a:e t(e cell= .ou REM can u#e &"ield 6 oCell&CellAddre##&Colu!n& &"ield 6 < REM Co!pare u#in a nu!eric or a #trinU &I#Hu!eric 6 3rue REM 3(e Hu!ericOalue propert. i# u#ed REM becau#e &I#Hu!eric 6 3rue $ro! abo:e& &Hu!ericOalue 6 Q7 REM I$ I#Hu!eric *a# "al#e= t(en t(e REM StrinOalue propert. *ould be u#ed& REM &StrinOalue 6 "*(at e:er" REM Oalid operator# include EMP3P= HO35EMP3P= E[0A,= REM HO35E[0A,= JREA3ER= JREA3ER5E[0A,= ,ESS= REM ,ESS5E[0A,= 3OP5OA,0ES= 3OP5PERCEH3= 499 REM BO33OM5OA,0ES= and BO33OM5PERCEH3 &Operator 6 co!&#un&#tar&#(eet&"ilterOperator&JREA3ER5E[0A, End Wit(
REM 3(e $ilter de#criptor #upport# t(e $ollo*in REM propertie#: I#Ca#eSen#iti:e= S1ip-uplicate#= REM 0#eReularExpre##ion#= REM Sa:eOutputPo#ition= Orientation= Contain#Header= REM Cop.Output-ata= OutputPo#ition= and Max"ieldCount& o"ilter-e#c&#et"ilter"ield#Bo"ield#BCC o"ilter-e#c&Contain#Header 6 3rue oS(eet&$ilterBo"ilter-e#cC End Sub ;"en a fi*ter is app*ied to a s"eet, it rep*aces any e3istin$ fi*ter for t"e s"eet& Settin$ an empty fi*ter in a s"eet %i** t"erefore remoe a** fi*ters for t"at s"eet& Listing 428. Remove the current sheet filter. Sub Re!o:eS(eet"ilterBC -i! oS(eet ) S(eet to $ilter& -i! o"ilter-e#c ) "ilter de#criptor&
oS(eet 6 3(i#Co!ponent&etS(eet#BC&etB.IndexB7C o"ilter-e#c 6 oS(eet&create"ilter-e#criptorB3rueC oS(eet&$ilterBo"ilter-e#cC End Sub A more adanced fi*ter may fi*ter more t"an one co*umn& Listing 429. - simple sheet filter using two columns. Sub Si!pleS(eet"ilter5'BC -i! oS(eet ) S(eet to $ilter& -i! oRane ) Rane to be $iltered& -i! o"ilter-e#c ) "ilter de#criptor& -i! o"ield#B>C A# He* co!&#un&#tar&#(eet&3able"ilter"ield
REM I$ aru!ent i# 3rue= create# an REM e!pt. $ilter de#criptor& o"ilter-e#c 6 oRane&create"ilter-e#criptorB3rueC REM Setup a $ield to :ie* cell# *it( content t(at REM #tart *it( t(e letter b& Wit( o"ield#B7C &"ield 6 7 ) "ilter colu!n A& &I#Hu!eric 6 "al#e ) 0#e a #trin= not a nu!ber& &StrinOalue 6 "b&*" ) E:er.t(in #tartin *it( b& &Operator 6 co!&#un&#tar&#(eet&"ilterOperator&E[0A, End Wit( REM Setup a $ield t(at re;uire# bot( condition# and 500 REM t(i# ne* condition re;uire# a :alue reater or REM e;ual to 27& Wit( o"ield#B>C &Connection 6 co!&#un&#tar&#(eet&"ilterConnection&AH- &"ield 6 < ) "ilter colu!n "& &I#Hu!eric 6 3rue ) 0#e a nu!ber &Hu!ericOalue 6 27 ) Oalue# reater t(an 27 &Operator 6 co!&#un&#tar&#(eet&"ilterOperator&JREA3ER5E[0A, End Wit( o"ilter-e#c&#et"ilter"ield#Bo"ield#BCC o"ilter-e#c&Contain#Header 6 "al#e o"ilter-e#c&0#eReularExpre##ion# 6 3rue oS(eet&$ilterBo"ilter-e#cC End Sub An adanced fi*ter supports up to ei$"t fi*ter conditions, as opposed to t"e t"ree supported by t"e simp*e fi*ter& T"e criteria for an adanced fi*ter is stored in a s"eet& T"e first step in creatin$ an adanced fi*ter is enterin$ t"e fi*ter criteria into t"e spreads"eet& 1& Se*ect an empty space in t"e #a*c document& T"e empty space may reside in any s"eet in any *ocation in t"e #a*c document& 2& Dup*icate t"e co*umn "eadin$s from t"e area to be fi*tered into t"e area t"at %i** contain t"e fi*ter criteria& 3& 2nter t"e fi*ter criteria underneat" t"e co*umn "eadin$s ,see Tab*e !.& T"e criterion in eac" co*umn of a ro% is connected %it" A4D& T"e criteria from eac" ro% are connected %it" 1R& App*yin$ an adanced fi*ter usin$ a macro is simp*e& T"e ce** ran$e containin$ t"e fi*ter criteria is used to create a fi*ter descriptor, %"ic" is t"en used to fi*ter t"e ran$e containin$ t"e data& Listing 430. Use an advanced filter. Sub 0#eAnAd:anced"ilterBC -i! oS(eet )A #(eet $ro! t(e Calc docu!ent& -i! oRane# )3(e Ha!edRane# propert.& -i! oCritRane )Rane t(at contain# t(e $ilter criteria& -i! o-ataRane )Rane t(at contain# t(e data to $ilter& -i! o"ilt-e#c )"ilter de#criptor& REM Rane t(at contain# t(e $ilter criteria oS(eet 6 3(i#Co!ponent&etS(eet#BC&etB.IndexB>C oCritRane 6 oS(eet&etCellRaneB.Ha!eB"A>:J%"C REM Pou can al#o obtain t(e rane containin t(e REM $ilter criteria $ro! a na!ed rane& REM oRane# 6 3(i#Co!ponent&Ha!edRane# REM oRane 6 oRane#&etB.Ha!eB"A:erae,e##Q7"C REM oCritRane 6 oRane&etRe$erredCell#BC REM 3(e data t(at I *ant to $ilter oS(eet 6 3(i#Co!ponent&etS(eet#BC&etB.IndexB7C o-ataRane 6 oS(eet&etCellRaneB.Ha!eB"A>:J>A"C 501 o"ilt-e#c 6 oCritRane&create"ilter-e#criptorB.ObNectBo-ataRaneC o-ataRane&$ilterBo"ilt-e#cC End Sub 1,...$. <rotecting documents and sheets #a*c documents and indiidua* spreads"eets support t"e I'rotectab*e interface& 5se t"e met"ods protect,pass%ord. and unprotect,pass%ord. to actiate or disab*e protection& T"e pass%ord is passed in as a Strin$& T"e is'rotected,. met"od returns True if protection is current*y actie& 1,...,. Controlling recalculation +y defau*t, a #a*c document automatica**y reca*cu*ates formu*as %"en t"e ce**s to %"ic" t"ey refer are modified& At times, it is usefu* to disab*e automatic reca*cu*ation& T"e met"ods in Tab*e 20@ a**o% you to contro* reca*cu*ation in t"e entire document& Table 208. Methods defined by the com.sun.star.sheet.:/alculatable interface. )et6od Description ca*cu*ate,. Reca*cu*ate a** ce**s %it" c"an$ed content& ca*cu*ateA**,. Reca*cu*ate a** ce**s& isAutomatic#a*cu*ation2nab*ed,. True if automatic ca*cu*ation is enab*ed& enab*eAutomatic#a*cu*ation,+oo*ean. 2nab*e or disab*e automatic ca*cu*ation& 1,..... 9sing Goal eek DJoa* See(F attempts to so*e e8uations %it" one un(no%n ariab*e& )n ot"er %ords, after definin$ a formu*a %it" mu*tip*e fi3ed a*ues and one ariab*e a*ue, Joa* See( tries to find an acceptab*e a*ue for t"e un(no%n ariab*e& #onsider a ery simp*e e3amp*e& )f you /ump off a c*iff, $raity %i** acce*erate you to%ard t"e $round at 32 feet per second eac" second& )n ot"er %ords, in one second you %i** be trae*in$ at 32 feet per second and in t%o seconds you %i** be trae*in$ at 6! feet per second& T"e e8uation is $ien as De*ocity ? acce*eration \ timeF& ) "ae a constant a*ue for t"e acce*eration due to $raity, and ) %ant to (no% "o% *on$ before ) am trae*in$ at 100 feet per second& Admitted*y, t"is is a triia* e3amp*e, but it is easy to understand& 5se t"e document met"od see(Joa*,#e**Address, #e**Address, Strin$. to perform a Joa* See( operation& T"e first ce** address identifies t"e ce** t"at contains t"e formu*a to so*e& T"e second ce** address identifies t"e ce** t"at contains t"e ariab*e t"at %i** c"an$e& '*ace t"e best $uess t"at you can ma(e into t"is ce**& T"e fina* strin$ contains t"e a*ue t"at you %ant to obtain from t"e formu*a& T"e macro in Listin$ !31 sets t"e formu*a and t"en performs a Joa* See( operation& Listing 431. *et a simple goal seek. Sub JoalSee1Exa!ple -i! oS(eet )oS(eet *ill contain t(e $ourt( #(eet& -i! oJCell )B'?= ra:it. :alue o$ %' -i! o3Cell )C'?= ti!e :alue -i! oRCell )Re#ultin e;uation "6B'?*C'?" -i! oJoal )Returned oal obNect oS(eet 6 3(i#Co!ponent&S(eet#B7C oJCell 6 oS(eet&etCellB.Po#itionB>= '%C 502 oJCell&#etOalueB%'C
oJoal63(i#Co!ponent&#ee1JoalBoRCell&CellAddre##= o3Cell&CellAddre##= ">77"C M#Box "Re#ult 6 " 4 oJoal&Re#ult 4 CHRFB>7C 45 "3(e re#ult c(aned b. " 4 oJoal&-i:erence 45 " in t(e la#t iteration"= 7= "Joal See1" End Sub T"e see(Joa*,. met"od returns a structure containin$ t%o f*oatin$9point Doub*e a*ues& T"e Resu*t property identifies t"e proposed so*ution& T"e Dier$ence property identifies t"e difference bet%een t"e *ast $uessed resu*t and t"e current resu*t& )f t"e dier$ence is sma**, t"e resu*t is probab*y reasonab*y accurate& )f, "o%eer, t"e dier$ence is *ar$e, t"e resu*t is probab*y inaccurate& ) performed a test %"ere t"ere %as no so*ution& T"e dier$ence a*ue %as rou$"*y 1&0230@& Do not *et t"e simp*icity of t"e proided e3amp*e foo* you& ) used t"e see(Joa*,. met"od to proide a so*ution to a prob*em t"at "ad no c*osed form so*ution L ) "ad to use a numerica* a*$orit"m to so*e t"e prob*em& 1.$. 1riting 'our own spreadsheet functions ;it" 11o, itGs triia* to %rite and use your o%n functions t"at are reco$niCed by t"e #a*c document& )tGs as simp*e as %ritin$ a macro and t"en addressin$ it direct*y& ) %rote an e3amp*e of t"is in Listin$ !32 t"at returns information about t"e passed ar$ument as a Strin$& Tab*e 20B s"o%s t"e return a*ues for different ar$uments& Listing 432. 9rint information about the argument. "unction Wa(oo"uncBOptional xC A# Oariant -i! #F # 6 "I a! in Wa(oo"unc& " I$ I#Mi##inBxC 3(en # 6 # 4 "Ho aru!ent *a# pa##ed" El#eI$ HO3 I#Arra.BxC 3(en # 6 # 4 "Scalar aru!ent B" 4 CStrBxC 4 "C i# t.pe " 4 3.peHa!eBxC El#e # 6 # 4 "Aru!ent i# an arra. B" 4 ,BoundBx= >C 4 " 3o " 4 0BoundBx= >C 45 "= " 4 ,BoundBx= 'C 4 " 3o " 4 0BoundBx= 'C 4 "C" End I$ Wa(oo"unc 6 # End "unction 503 Table 209. Return values for different arguments to 'ahoo+unc 6assume cell $1 contains =7. !nction &etrn D?;a"oo0unc,.F ) am in ;a"oo0unc& 4o ar$ument %as passed& D?;a"oo0unc,2B.F ) am in ;a"oo0unc& Sca*ar ar$ument ,2. is type Doub*e& D?;a"oo0unc,2.F ) am in ;a"oo0unc& Sca*ar ar$ument ,2. is type Doub*e& D?;a"oo0unc,A11:#1A.F ) am in ;a"oo0unc& Ar$ument is an array ,1 To A, 1 To 3.& T"e ar$ument t"at is passed to t"e function t"at you %rite, may be missin$& )f t"e ar$ument is dec*ared as optiona*, use t"e )sMissin$,. met"od to test if a a*ue "as been passed& 0or e3amp*e, D?;a"oo0unc,.F& 6ou can direct*y pass a sin$*e sca*ar a*ue eit"er as a constant, or by referencin$ a sin$*e ce**& 0or e3amp*e, D?;a"oo0unc,32.F and D?;a"oo0unc,2M.F bot" pass a sca*ar a*ue to t"e function& T"e first e3amp*e passes t"e numeric a*ue 32 and t"e second e3amp*e passes t"e contents of ce** 2M& Tip T"e actua* type of ar$ument t"at is passed to your o%n functions depends on "o% it is ca**ed ,see Tab*e 20B.& ;"en a ran$e is used as t"e ar$ument, t"e data is passed as a t%o9dimensiona* array t"at does not use t"e traditiona* *o%er bound of Cero& )f t"e ar$ument refers to a ran$e, a t%o9dimensiona* array is passed to t"e function& 0or e3amp*e, D?;a"oo0unc,2M:032.F passes t"e contents of t"e ce**s in t"e ran$e 2M t"rou$" 032 as a t%o9dimensiona* array& +e abso*ute*y certain to use t"e functions L+ound,. and 5+ound,., because t"e *o%er bounds start at 1 rat"er t"an at t"e e3pected a*ue of 0 ,see Listin$ !33.& Listing 2FF. -dd all elements together. "unction Su!AllB!.Arra. a# OariantC -i! iRo*G= iColG -i! d A# -ouble "or iRo* 6 ,BoundB!.Arra.= >C 3o 0BoundB!.Arra.= >C "or iCol 6 ,BoundB!.Arra.= 'C 3o 0BoundB!.Arra.= 'C d 6 d W !.Arra.BiRo*= iColC Hext Hext Su!All 6 d End "unction Different ersions of 11o "ae different be"aior %"i*e definin$ your o%n #a*c functions& T"e #a*c function must be isib*e - aai*ab*e to t"e #a*c document, so ) store my #a*c functions in t"e Standard *ibrary of t"e document t"at %i** use t"e functions& Sometimes, %"en ) %rite a ne% function, t"e ne% function is not noticed unti* t"e document "as been saed, c*osed, and t"en reopened& 1.&. )sing the current controller 2ac" 11o document contains a contro**er t"at interacts %it" t"e user& T"erefore, t"e current contro**er (no%s %"at te3t is se*ected, t"e *ocation of t"e current cursor, and %"ic" s"eet is actie& 504 1,.0.1. elected cells T"e documentGs contro**er interacts %it" t"e user and t"erefore (no%s %"ic" ce**s are se*ected& )n a #a*c document, a se*ected ce** can be a fe% different t"in$s& T"e fo**o%in$ cases are numbered to simp*y reference eac" case7 t"e numberin$ seres no ot"er purpose& 1& 1ne ce** se*ected& To se*ect an entire ce**, c*ic( in a ce** once and t"en "o*d do%n t"e S"ift (ey and c*ic( in t"e ce** a$ain& 2& 'artia* te3t in a sin$*e ce** se*ected& Doub*e9c*ic( in a sin$*e ce** and t"en se*ect some te3t& 3& 4ot"in$ appears se*ected& Sin$*e9c*ic( in a ce** or tab bet%een ce**s& !& Mu*tip*e ce**s se*ected& Sin$*e9c*ic( in a ce** and t"en dra$ t"e cursor& A& Mu*tip*e dis/ointed se*ections& Se*ect some ce**s& Eo*d do%n t"e #tr* (ey and se*ect some more& So far, ) "ae not been ab*e to distin$uis" bet%een t"e first t"ree cases7 t"ey a** *oo( *i(e one ce** is se*ected& )f on*y one ce** is se*ected, t"e current se*ection returned by t"e current contro**er is t"e s"eet ce** containin$ t"e cursor& )f a sin$*e ce** is se*ected ,cases 1 t"rou$" 3., t"e se*ections ob/ect supports t"e S"eet#e** serice ,see Listin$ !3!.& )f mu*tip*e ce**s are se*ected as a sin$*e ran$e ,case !., t"e se*ections ob/ect is a S"eet#e**Ran$e& #"ec( to see if t"e se*ections ob/ect supports t"e S"eet#e**Ran$e serice& )f so, t"en more t"an one ce** ran$e is se*ected& 5se t"e $et#ount,. met"od of t"e se*ections ob/ect to see "o% many ran$es are se*ected& Listing 434. #etermine if anything is selected. "unction CalcI#An.t(inSelectedBo-ocC A# Boolean -i! oSelection# REM A##u!e t(at not(in i# #elected& CalcI#An.t(inSelected 6 "al#e I$ I#HullBo-ocC 3(en Exit "unction REM 3(e current #election in t(e current controller& REM I$ t(ere i# no current controller= t(i# return# H0,,& oSelection# 6 o-oc&etCurrentSelectionBC I$ I#HullBoSelection#C 3(en Exit "unction I$ oSelection#&#upport#Ser:iceB"co!&#un&#tar&#(eet&S(eetCell"C 3(en Print "One Cell #elected 6 " 4 oSelection#&etI!ple!entationHa!eBC M#Box "etStrinBC 6 " 4 oSelection#&etStrinBC El#eI$ oSelection#&#upport#Ser:iceB"co!&#un&#tar&#(eet&S(eetCellRane"C 3(en Print "One Cell Rane #elected 6 " 4 oSelection#&etI!ple!entationHa!eBC El#eI$ oSelection#&#upport#Ser:iceB"co!&#un&#tar&#(eet&S(eetCellRane#"C 3(en Print "Multiple Cell Rane# #elected 6 " 45 oSelection#&etI!ple!entationHa!eBC Print "Count 6 " 4 oSelection#&etCountBC El#e Print "So!et(in el#e #elected 6 " 4 oSelection#&etI!ple!entationHa!eBC End I$ CalcI#An.t(inSelected 6 3rue End "unction 505 Enumerating the selected cells Listin$ !3A is a uti*ity routine t"at sets t"e te3t of t"e ce**s in a ran$e to a specific a*ue& A*t"ou$" Listin$ !3A is specifica**y desi$ned to operate on a ce** ran$e, it uses met"ods t"at are a*so supported by a sin$*e ce**& T"e macro, t"erefore, may be used by a ce** or a ce** ran$e ob/ect& T"e met"od used in Listin$ !3A is a modification of an a*$orit"m introduced to me by Sasa <e*eceic, on t"e 11o de mai*in$ *ist& Listing 435. *et all te.t in a range to a value. Sub SetRane3extBoRane= # A# StrinC -i! nCol A# ,on )Colu!n index :ariable -i! nRo* A# ,on )Ro* index :ariable -i! oCol# )Colu!n# in t(e #elected rane -i! oRo*# )Ro*# in t(e #elected rane oCol# 6 oRane&Colu!n# : oRo*# 6 oRane&Ro*# "or nCol 6 7 3o oCol#&etCountBC 9 > "or nRo* 6 7 3o oRo*#&etCountBC 9 > oRane&etCellB.Po#itionBnCol= nRo*C&#etStrinB#C Hext Hext End Sub To demonstrate "o% to inspect a** of t"e se*ected ce**s, t"e macro in Listin$ !36 sets t"e te3t in eery se*ected ce** to a specific te3t a*ue& Listing 436. *et all selected cells to a value. Sub SetSelectedCell#B# A# StrinC -i! oSelection# )3(e #election# obNect -i! oCell )I$ one cell i# #elected -i! oRane# )I$ !ultiple rane# are #elected= u#e t(i# -i! i A# ,on )Jeneral index :ariable REM 3(e current #election in t(e current controller& REM I$ t(ere i# no current controller= t(i# return# H0,,& oSelection# 6 3(i#Co!ponent&etCurrentSelectionBC I$ I#HullBoSelection#C 3(en Exit Sub I$ oSelection#&#upport#Ser:iceB"co!&#un&#tar&#(eet&S(eetCell"C 3(en oCell 6 oSelection# oCell&#etStrinB#C
REM "or con#i#tenc.= I could u#e t(e #a!e call $or a rane a# a cell REM but t(i# i# onl. becau#e a cell can al#o return t(e colu!n# and ro*#& REM SetRane3extBoSelection#= #C El#eI$ oSelection#&#upport#Ser:iceB"co!&#un&#tar&#(eet&S(eetCellRane"C 3(en SetRane3extBoSelection#= #C El#eI$ oSelection#&#upport#Ser:iceB"co!&#un&#tar&#(eet&S(eetCellRane#"C 3(en oRane# 6 oSelection# "or i 6 7 3o oRane#&etCountBC 9 > SetRane3extBoRane#&etB.IndexBiC= #C Hext El#e Print "So!et(in el#e #elected 6 " 4 oSelection#&etI!ple!entationHa!eBC 506 End I$ End Sub ;"i*e %ritin$ t"e macro in Listin$ !36, ) e3perienced some initia**y perp*e3in$ be"aior& My initia* ersion of Listin$ !36 %ou*d sometimes $enerate an error as it attempted to enter t"e subroutine, dependin$ on t"e se*ected a*ues& T"e run9time error %ou*d comp*ain t"at an unsupported property or ina*id a*ue %as used& To e3p*ain t"e prob*em ,and t"e so*ution., notice t"at t"ere are t%o p*aces in t"e code %"ere ) assi$n oSe*ections to a temporary ariab*e and t"en ) use t"e ariab*e& Listin$ !3M contains t"e sma** sections of code e3tracted from Listin$ !36& Listing 437. " assign o*elections to a temporary variable before use. oCell 6 oSelection# oCell&#etStrinB#C &&&&& oRane# 6 oSelection# "or i 6 7 3o oRane#&etCountBC 9 > SetRane3extBoRane#&etB.IndexBiC= #C Hext )f oSe*ections refers to a ce**, it doesnGt support t"e ob/ect met"od $et#ount,.& )f oSe*ections refers to a S"eet#e**Ran$es ob/ect, it doesnGt support t"e setStrin$,. ob/ect met"od& ) can but assume t"at t"e 11o +asic interpreter attempts to reso*e t"e properties and met"ods t"at an ob/ect references %"en it is assi$ned a a*ue& 0or e3amp*e, if t"e se*ections ob/ect is a ce**, an error is raised because a ce** doesnGt support t"e $et#ount,. met"od& 1n t"e ot"er "and, if more t"an one ce** is se*ected, t"e returned ob/ect does not support t"e setStrin$,. met"od& A*t"ou$" t"is is not t"e first time t"at ) "ae e3perienced t"is prob*em, it is t"e first time t"at ) determined t"e nature of t"e prob*em and "o% to aoid it& /electing te:t T"e current contro**er is used to determine t"e current se*ection, and it can a*so be used to set t"e current se*ection& 5se t"e current contro**erGs se*ect,ob/. met"od to se*ect ce**s in a s"eet& T"e documentation essentia**y says t"at if t"e contro**er reco$niCes and is ab*e to se*ect t"e ob/ect passed as an ar$ument, it %i**& Listin$ !3@ demonstrates "o% to se*ect ce**s& Listing 438. *elect !=0J#FF and then select cell -( instead. -i! oS(eet= oRane= oCell= oController oController 6 3(i#Co!ponent&etCurrentControllerBC oS(eet 6 3(i#Co!ponent&S(eet#B%C oRane 6 oS(eet&etCellRaneB.Ha!eB"B'Q:-%%"C oController&#electBoRaneC oCell 6 oS(eet&etCellB.Po#itionB7= 7C oController&#electBoCellC 0he active cell T"e actie ce** contains t"e cursor& T"ere is an actie ce** een %"en mu*tip*e ce**s are se*ected& 5nfortunate*y, 11o does not proide a met"od to return t"e actie ce** %"en more t"an one ce** is se*ected& 'ao*o Mantoani posted a ery nice so*ution to t"is prob*em on t"e de mai*in$ *ist as s"o%n in Listin$ !3B& T"e disadanta$e to t"e macro in Listin$ !3B is t"at t"e actie ce** is no *on$er actie after t"e macro runs& Listing 2F1. Obtain the active cell. REM Aut(or: Paolo Manto:ani REM e!ail: !anto:ani&paoloItin&it 507 Sub Retrie:e3(eActi:eCellBC -i! oOldSelection )3(e oriinal #election o$ cell rane# -i! oRane# )A blan1 rane created b. t(e docu!ent -i! oActi:eCell )3(e current acti:e cell -i! oCon: )3(e cell addre## con:er#ion #er:ice -i! o-oc o-oc 6 3(i#Co!ponent REM #tore t(e current #election oOldSelection 6 o-oc&CurrentSelection REM Create an e!pt. S(eetCellRane# #er:ice and t(en #elect it& REM 3(i# lea:e# OH,P t(e acti:e cell #elected& oRane# 6 o-oc&createIn#tanceB"co!&#un&#tar&#(eet&S(eetCellRane#"C o-oc&CurrentController&SelectBoRane#C REM Jet t(e acti:e cellK oActi:eCell 6 o-oc&CurrentSelection oCon: 6 o-oc&createIn#tanceB"co!&#un&#tar&table&CellAddre##Con:er#ion"C oCon:&Addre## 6 oActi:eCell&etCellAddre## Print oCon:&0#erInter$aceRepre#entation print oCon:&Per#i#tentRepre#entation REM Re#tore t(e old #election= but loo#e t(e pre:iou#l. acti:e cell o-oc&CurrentController&SelectBoOldSelectionC End Sub 1,.0.2. General functionalit" ;"en searc"in$ for ie%9re*ated functiona*ity, t"e current contro**er is a $ood p*ace to start& Tab*e 210 and Tab*e 211 contain most of t"e met"ods and properties supported by t"e current contro**er t"at "ae not a*ready been discussed& 508 Table 210. Methods supported by the current controller not already discussed. )et6ods Description $etActieS"eet,. Jet t"e actie spreads"eet& setActieS"eet,ISpreads"eet. #ause t"e specified s"eet to become actie& $et)s;indo%Sp*it,. Return True if t"e ie% is sp*it& $etSp*itEoriConta*,. Lon$ )nte$er "oriConta* sp*it position ,in pi3e*s.& $etSp*itOertica*,. Lon$ )nte$er ertica* sp*it position ,in pi3e*s.& $etSp*it#o*umn,. Lon$ )nte$er co*umn before %"ic" t"e ie% is sp*it& $etSp*itRo%,. Lon$ )nte$er ro% before %"ic" t"e ie% is sp*it& sp*itAt'osition,3, y. Sp*it t"e ie% at t"e specified position& )f 3?0, t"e sp*it is on*y "oriConta*& )f y?0, t"e sp*it is on*y ertica*& "as0roCen'anes,. True if t"e ie% contains froCen panes& freeCeAt'osition,n#o*, nRo%. 0reeCe panes %it" t"e specified number of co*umns and ro%s& $et0irstOisib*e#o*umn,. Jet t"e first isib*e co*umn in t"e pane as a Lon$ )nte$er& set0irstOisib*e#o*umn,Lon$. Set t"e first isib*e co*umn in t"e pane& $et0irstOisib*eRo%,. Jet t"e first isib*e ro% in t"e pane as a Lon$ )nte$er& set0irstOisib*eRo%,Lon$. Set t"e first isib*e ro% in t"e pane& $etOisib*eRan$e,. Jet t"e isib*e ran$e in t"e pane as a #e**Ran$eAddress& 509 able =((. 9roperties supported by the current controller not already discussed. Property Description S"o%0ormu*as )f True, formu*as are disp*ayed instead of t"eir resu*ts& S"o%PeroOa*ues )f True, Cero a*ues are isib*e& )sOa*ueEi$"*i$"tin$2nab*ed )f True, strin$s, a*ues, and formu*as are disp*ayed in different co*ors& S"o%4otes )f True, a mar(er is s"o%n for notes in ce**s& EasOertica*Scro**+ar )f True, a ertica* scro** bar is used in t"e ie%& EasEoriConta*Scro**+ar )f True, a "oriConta* scro** bar is used in t"e ie%& EasS"eetTabs )f True, s"eet tabs are used in t"e ie%& )s1ut*ineSymbo*sSet )f True, out*ine symbo*s are disp*ayed& Eas#o*umnRo%Eeaders )f True, co*umn and ro% "eaders are isib*e& S"o%Jrid )f True, ce** $rid *ines are disp*ayed& Jrid#o*or Jrid co*or as a Lon$ )nte$er& S"o%Ee*pLines )f True, "e*p *ines are disp*ayed %"i*e moin$ dra%in$ ob/ects& S"o%Anc"or )f True, anc"or symbo*s are disp*ayed %"en dra%in$ ob/ects are se*ected& S"o%'a$e+rea(s )f True, pa$e brea(s are disp*ayed& So*idEand*es )f True, so*id ,co*ored. "and*es are disp*ayed %"en dra%in$ ob/ects are se*ected& S"o%1b/ects )f True, embedded ob/ects are disp*ayed& S"o%#"arts )f True, c"arts are disp*ayed& S"o%Dra%in$ )f True, dra%in$ ob/ects are disp*ayed& EideSpe**Mar(s )f True, spe**in$ mar(s are not disp*ayed& PoomType Document Coom type as a com&sun&star&ie%&DocumentPoomType %it" t"e fo**o%in$ a*ues: 1'T)MAL ? 0 H 0it t"e current pa$e content %idt" ,no mar$ins.& 'AJ2=;)DTE ? 1 H 0it t"e pa$e %idt" at t"e current se*ection& 24T)R2='AJ2 ? 2 H 0it an entire pa$e& +6=OAL52 ? 3 H T"e Coom is re*atie and set by PoomOa*ue& 'AJ2=;)DTE=2IA#T ? ! H 0it t"e current %idt" and fit e3act*y to pa$e end& PoomOa*ue Poom a*ue if t"e PoomType is set to +6=OAL52 & 1.(. Control Calc from Microsoft Office )t turns out t"at you can contro* 11o from %it"in t"e Microsoft 1ffice fami*y of products& T"e tric( is to create a serice mana$er, %"ic" starts 11o if it is not current*y runnin$& Accessin$ 11o documents from Microsoft 1ffice is simi*ar to accessin$ 11o documents usin$ ot"er non9Star+asic *an$ua$es& 11o +asic proides nice s"ortcuts t"at are not aai*ab*e from Microsoft 1ffice& 0or e3amp*e, in 11o +asic, %"en ) %ant t"e t"ird s"eet, ) simp*y use oDoc&S"eets,2.7 in Microsoft 1ffice, "o%eer, you cannot access t"e S"eets property as an array& ) %rote and ran t"e macro in Listin$ !!0 from Microsoft Oisua* +asic from Microsoft 23ce*& 510 Listing 440. /ontrolOOo67 demonstrates how to control OOo from $.cel. Sub ControlOOoBC Re! 3(e #er:ice !anaer i# al*a.# t(e $ir#t t(in to create& Re! I$ OOo i# not runnin= it i# #tarted& Set oManaer 6 CreateObNectB"co!&#un&#tar&Ser:iceManaer"C Re! Create t(e de#1top& Set o-e#1top 6 oManaer&createIn#tanceB"co!&#un&#tar&$ra!e&-e#1top"C Re! Open a ne* e!pt. Calc docu!ent& -i! ar#BC -i! # A# Strin Set # 6 "pri:ate:$actor.+#calc" Set o-oc 6 o-e#1top&loadCo!ponent"ro!0R,B#= "5blan1"= 7= ar#BCC -i! oS(eet A# ObNect -i! oS(eet# A# ObNect -i! oCell A# ObNect
Set oS(eet# 6 o-oc&#(eet#&CreateEnu!eration Set oS(eet 6 oS(eet#&nextEle!ent Set oCell 6 oS(eet&etCellB.Po#itionB7= 7C oCell&#et"or!ula B"Hello "ro! Excel"C )Cell A> oCell&CellBac1Color 6 RJBB>'2= >'2= >'2C End Sub 1.1+. 2ccessing Calc functions 6ou can ca** #a*c functions from a macro& Listing 441. /all the M"N function directly. Sub call"unction -i! o"A o"A 6 create0noSer:iceB "co!&#un&#tar&#(eet&"unctionAcce##" C ) Calculate !in o$ nu!ber#& print o"A&call"unctionB "MIH"= arra.B >7= '%= <= %?< C C End Sub 1.11. Conclusion #a*c documents are feature9ric" and t"ey support a %ide ariety of capabi*ities& )n my opinion, #a*c documents proide more functiona*ity t"an any ot"er document type supported by 11o& T"is c"apter, t"erefore, is on*y t"e be$innin$ of t"e %onderfu* t"in$s t"at you can do usin$ #a*c documents& 511