22.01.2015 Views

OpenOffice.org Macros Explained - LibreOffice-NA.US

OpenOffice.org Macros Explained - LibreOffice-NA.US

OpenOffice.org Macros Explained - LibreOffice-NA.US

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Listing 18. Demonstrate simple array.<br />

Sub ExampleSimpleArray1<br />

Dim a(2) As Integer, b(-2 To 1) As Long<br />

Dim m(1 To 2, 3 To 4)<br />

REM Did you know that multiple statements can be placed<br />

REM on a single line if separated by a colon<br />

a(0) = 0 : a(1) = 1 : a(2) = 2<br />

b(-2) = -2 : b(-1) = -1 : b(0) = 0 : b(1) = 1<br />

m(1, 3) = 3 : m(1, 4) = 4<br />

m(2, 3) = 6 : m(2, 4) = 8<br />

Print "m(2,3) = " & m(2,3)<br />

Print "b(-2) = " & b(-2)<br />

End Sub<br />

To quickly fill a Variant array, use the Array function (see Listing 19), which returns a Variant array with the<br />

included data. The functions LBound and Ubound return the lower bound and upper bound of an array.<br />

Routines supported by OOo Basic are summarized in Table 12, and discussed thoroughly later.<br />

Listing 19. Use Array() to quickly fill an array.<br />

Sub ExampleArrayFunction<br />

Dim a, i%, s$<br />

a = Array("Zero", 1, Pi, Now)<br />

Rem String, Integer, Double, Date<br />

For i = LBound(a) To UBound(a)<br />

s$ = s$ & i & " : " & TypeName(a(i)) & " : " & a(i) & CHR$(10)<br />

Next<br />

MsgBox s$, 0, "Example of the Array Function"<br />

End Sub<br />

Figure 22. Different variable types in the same array.<br />

A variable defined as an array but not dimensioned, such as Dim a(), is called an empty array. Test for an<br />

empty array by comparing the upper bound of the array to the lower bound. If the upper bound is less than<br />

the lower bound, the array is empty and no dimensions have been set. An array that has been dimensioned,<br />

such as Dim a(5), is not empty.<br />

The behavior for LBound and UBound has changed over time. Some releases of OOo produce an error for<br />

UBound(b) and some do not. All versions should work correctly with UBound(b()). At the time of this<br />

writing, the upper and lower array bounds for c (in Listing 20) fails because c is an empty object.<br />

Listing 20. Parentheses are not always required but are always allowed.<br />

Sub ArrayDimensionError<br />

On Error Goto ErrorHandler<br />

46

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!