Basic Programming Guide
Basic Programming Guide
PDF generated using the open source mwlib toolkit see http://code.pediapress.com/ for more information
Compatibility between OpenOffice.org Basic and VBA relates to the OpenOffice.org Basic language as well as the runtime library. The OpenOffice.org API and the Dialog Editor are not compatible with VBA (standardizing these interfaces would have made many of the concepts provided in OpenOffice.org impossible).
More Information
The components of the OpenOffice.org API that are discussed in this guide were selected based on their practical benefits for the OpenOffice.org Basic programmer. In general, only parts of the interfaces are discussed. For a more detailed picture, see the API reference [1]. The Developer's Guide describes the OpenOffice.org API in more detail than this guide, but is primarily intended for Java and C++ programmers. Anyone who is already familiar with OpenOffice.org Basic programming can find additional information in the Developer's Guide on OpenOffice.org Basic and OpenOffice.org programming. Programmers who want to work directly with Java or C++ rather than OpenOffice.org Basic should consult the OpenOffice.org Developer's Guide instead of this guide. OpenOffice.org programming with Java or C++ is a considerably more complex process than programming with OpenOffice.org Basic. Download as a PDF Collection
External links
[1] http:/ / api. openoffice. org/ docs/ common/ ref/ com/ sun/ star/ module-ix. html Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide&oldid=91335
Program Lines
The Basic interpreter's line-oriented execution produces one of the key differences between Basic and other programming languages. Whereas the position of hard line breaks in the source code of Java, C++, or Delphi programs is irrelevant, each line in a Basic program forms a self-contained unit. Function calls, mathematical expressions, and other linguistic elements, such as function and loop headers, must be completed on the same line that they begin on.
Overview of a Basic Program If there is not enough space, or if this results in long lines, then several lines can be linked together by adding underscores _. The following example shows how four lines of a mathematical expression can be linked: LongExpression (Expression3 * (Expression5 * (Expression7 * = (Expression1 * Expression2) + _ Expression4) + _ Expression6) + _ Expression8)
The underscore must always be the last character in a linked line and cannot be followed by a space or a tab, otherwise the code generates an error.
In addition to linking individual lines, OpenOffice.org Basic, you can use colons to divide one line into several sections so that there is enough space for several expressions. The assignments a = 1 a = a + 1 a = a + 1 can be written as follows: a = 1 : a = a + 1 : a = a + 1
Comments
In addition to the program code to be executed, an OpenOffice.org Basic program can also contain comments that explain the individual parts of the program and provide important information that can be helpful at a later point. OpenOffice.org Basic provides two methods for inserting comments in the program code: All characters that follow an apostrophe are treated as comments: Dim A ' This is a comment for variable A
The keyword Rem, followed by the comment: Rem This comment is introduced by the keyword Rem. A comment usually includes all characters up to the end of the line. OpenOffice.org Basic then interprets the following line as a regular instruction again. If comments cover several lines, each line must be identified as a comment: Dim B ' ' ' ' This comment for variable B is relatively long and stretches over several lines. The comment character must therefore be repeated in each line.
Markers
A OpenOffice.org Basic program can contain dozens, hundreds, or even thousands of markers, which are names for variables, constants, functions, and so on. When you select a name for a marker, the following rules apply: Markers can only contain Latin letters, numbers, and underscores (_). The first character of a marker must be a letter or an underscore. Markers cannot contain special characters, such as . The maximum length of a marker is 255 characters.
No distinction is made between uppercase and lowercase characters. The OneTestVariable marker, for example, defines the same variable as onetestVariable and ONETESTVARIABLE. There is, however, one exception to this rule: a distinction is made between uppercase and lowercase characters for UNO-API constants. More information about UNO is presented in Introduction to the OpenOffice.org API.
The rules for constructing markers are different in OpenOffice.org Basic than in VBA. For example, OpenOffice.org Basic only allows special characters in markers when using Option Compatible, since they can cause problems in international projects.
Here are a few examples of correct and incorrect markers: Surname Surname5 First Name DjVu 5Surnames First,Name ' ' ' ' ' ' Correct Correct (number 5 is not the first digit) Incorrect (spaces are not permitted) Incorrect (letters such as , are not permitted) Incorrect (the first character must not be a number) Incorrect (commas and full stops are not permitted)
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Program_ Overview&oldid=91342 Principle Authors: Fpe, Ccornell
Working With Variables with a value of 0. It can be very difficult to locate errors of this kind in your code.
The variables declared in the previous example can even be used for different variable types in the same program. Although this provides considerable flexibility, it is best to restrict a variable to one variable type. When OpenOffice.org Basic encounters an incorrectly defined variable type in a particular context, an error message is generated. Use the following style when you make a type-bound variable declaration: Dim MyVar As Integer ' Declaration of a variable of the integer type
The variable is declared as an integer type and can record whole number values. You can also use the following style to declare an integer type variable: Dim MyVar% ' Declaration of a variable of the integer type
The Dim instruction can record several variable declarations: Dim MyVar1, MyVar2 If you want to assign the variables to a permanent type, you must make separate assignments for each variable: Dim MyVar1 As Integer, MyVar2 As Integer If you do not declare the type for a variable, OpenOffice.org Basic assigns the variable a variant type. For example, in the following variable declaration, MyVar1 becomes a variant and MyVar2 becomes an integer: Dim MyVar1, MyVar2 As Integer
Working With Variables The following sections list the variable types that are available in OpenOffice.org Basic and describe how they can be used and declared. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Working_ With_ Variables&oldid=91343 Principle Authors: Fpe, Ccornell, TJFrazier
Strings
Strings, together with numbers, form the most important basic types of OpenOffice.org Basic. A string consists of a sequence of consecutive individual characters. The computer saves the strings internally as a sequence of numbers where each number represents one specific character.
Code Pages
The ISO 8859 character sets provide an international standard. The first 128 characters of the ISO character set correspond to the ASCII character set. The ISO standard introduces new character sets (code pages ) so that more languages can be correctly displayed. However, as a result, the same character value can represent different characters in different languages.
Strings
10
Unicode
Unicode increases the length of a character to four bytes and combines different character sets to create a standard to depict as many of the world's languages as possible. Version 2.0 of Unicode is now supported by many programs including OpenOffice.org and OpenOffice.org Basic.
String Variables
OpenOffice.org Basic saves strings as string variables in Unicode. A string variable can store up to 65535 characters. Internally, OpenOffice.org Basic saves the associated Unicode value for every character. The working memory needed for a string variable depends on the length of the string. Example declaration of a string variable: Dim Variable As String You can also write this declaration as: Dim Variable$
When porting VBA applications, ensure that the maximum allowed string length in OpenOffice.org Basic is observed (65535 characters).
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Strings&oldid=91344 Principle Authors: Fpe, Ccornell, Strompf
Numbers
11
Numbers
OpenOffice.org Basic supports five basic types for processing numbers: Integer Long Integer Single Double Currency
Integer Variables
Integer variables can store any whole number between -32768 and 32767. An integer variable can take up to two bytes of memory. The type declaration symbol for an integer variable is %. Calculations that use integer variables are very fast and are particularly useful for loop counters. If you assign a floating point number to an integer variable, the number is rounded up or down to the next whole number. Example declarations for integer variables: Dim Variable As Integer Dim Variable%
Single Variables
Single variables can store any positive or negative floating point number between 3.402823 x 1038 and 1.401298 x 10-45. A single variable can take up to four bytes of memory. The type declaration symbol for a single variable is !. Originally, single variables were used to reduce the computing time required for the more precise double variables. However, these speed considerations no longer apply, reducing the need for single variables. Example declarations for single variables: Dim Variable as Single Dim Variable!
Numbers
12
Double Variables
Double variables can store any positive or negative floating point numbers between 1.79769313486232 x 10308 and 4.94065645841247 x 10-324. A double variable can take up to eight bytes of memory. Double variables are suitable for precise calculations. The type declaration symbol is #. Example declarations of double variables: Dim Variable As Double Dim Variable#
Currency Variables
Currency variables differ from the other variable types by the way they handle values. The decimal point is fixed and is followed by four decimal places. The variable can contain up to 15 numbers before the decimal point. A currency variable can store any value between -922337203685477.5808 and +922337203685477.5807 and takes up to eight bytes of memory. The type declaration symbol for a currency variable is @. Currency variables are mostly intended for business calculations that yield unforeseeable rounding errors due to the use of floating point numbers. Example declarations of currency variables: Dim Variable As Currency Dim Variable@
Floats
The types single, double and currency are often collectively referred to as floats, or floating-point number types. They can contain numerical values with decimal fractions of various length, hence the name: The decimal point seems to be able to 'float' through the number. You can declare variables of the type float. The actual variable type (single, long, currency) is determined the moment a value is assigned to the variable: Dim A As Float A = 1210.126
Whole Numbers
The simplest method is to work with whole numbers. They are listed in the source text without a comma separating the thousand figure: Dim A As Integer Dim B As Float
Numbers A = 1210 B = 2438 The numbers can be preceded by both a plus (+) or minus (-) sign (with or without a space in between): Dim A As Integer Dim B As Float A = + 121 B = - 243
13
Decimal Numbers
When you type a decimal number, use a period (.) as the decimal point. This rule ensures that source texts can be transferred from one country to another without conversion. Dim A As Integer Dim B As Integer Dim C As Float A = 1223.53 ' is rounded B = - 23446.46 ' is rounded C = + 3532.76323 You can also use plus (+) or minus (-) signs as prefixes for decimal numbers (again with or without spaces). If a decimal number is assigned to an integer variable, OpenOffice.org Basic rounds the figure up or down.
Note, that in the first and third incorrect examples that no error message is generated even though the variables return incorrect values. The expression
Numbers A = 1.43E -2 is interpreted as 1.43 minus 2, which corresponds to the value -0.57. However, the value 1.43 x 10-2 (corresponding to 0.0143) was the intended value. With the value A = 1.43E2.2 OpenOffice.org Basic ignores the part of the exponent after the decimal point and interprets the expression as A = 1.43E2
14
Hexadecimal Values
In the hexadecimal system (base 16 system), a 2-digit number corresponds to precisely one byte. This allows numbers to be handled in a manner which more closely reflects machine architecture. In the hexadecimal system, the numbers 0 to 9 and the letters A to F are used as numbers. An A stands for the decimal number 10, while the letter F represents the decimal number 15. OpenOffice.org Basic lets you use whole numbered hexadecimal values, so long as they are preceded by &H. Dim A As Long A = &HFF ' Hexadecimal value FF, corresponds to the decimal value 255 A = &H10 ' Hexadecimal value 10, corresponds to the decimal value 16
Octal Values
OpenOffice.org Basic also understands the octal system (base 8 system), which uses the numbers 0 to 7. You must use whole numbers that are preceded by &O. Dim A As Long A = &O77 ' Octal value 77, corresponds to the decimal value 63 A = &O10 ' Octal value 10, corresponds to the decimal value 8
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Numbers&oldid=91345 Principle Authors: Fpe, Ccornell, Strompf
Boolean Values
Boolean variables can only contain one of two values: True or False. They are suitable for binary specifications that can only adopt one of two statuses. A Boolean value is saved internally as a two-byte integer value, where 0 corresponds to the False and any other value to True. There is no type declaration symbol for Boolean variables. The declaration can only be made using the supplement As Boolean. Example declaration of a Boolean variable:
15
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Boolean&oldid=91346 Principle Authors: Fpe, Ccornell
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Date&oldid=91347 Principle Authors: Fpe, Ccornell
Arrays
In addition to simple variables (scalars), OpenOffice.org Basic also supports arrays (data fields). A data field contains several variables, which are addressed through an index.
Simple Arrays
An array declaration is similar to that of a simple variable declaration. However, unlike the variable declaration, the array name is followed by parentheses which contain the specifications for the number of elements. The expression Dim MyArray(3) declares an array that has four variables of the variant data type, namely MyArray(0), MyArray(1), MyArray(2), and MyArray(3). You can also declare type-specific variables in an array. For example, the following line declares an array with four integer variables: Dim MyInteger(3) As Integer In the previous examples, the index for the array always begins with the standard start value of zero. As an alternative, a validity range with start and end values can be specified for the data field declaration. The following example declares a data field that has six integer values and which can be addressed using the indexes 5 to 10:
Arrays Dim MyInteger(5 To 10) The indexes do not need to be positive values. The following example also shows a correct declaration, but with negative data field limits: Dim MyInteger(-10 To -5) It declares an integer data field with 6 values that can be addressed using the indexes -10 to -5. There are three limits that you must observe when you define data field indexes: The smallest possible index is -32768. The largest possible index is 32767. The maximum number of elements (within a data field dimension) is 16368.
Other limit values sometimes apply for data field indexes in VBA. The same also applies to the maximum number of elements possible per dimension. The values valid there can be found in the relevant VBA documentation.
16
Arrays
17
Unlike VBA, where you can only dimension dynamic arrays by using Dim MyArray(), OpenOffice.org Basic lets you change both static and dynamic arrays using ReDim.
The following example changes the dimension of the initial array so that it can record 11 or 21 values: Dim MyArray(4) As Integer ' Declaration with five elements ' ... ReDim MyArray(10) As Integer ' Increase to 11 elements ' ... ReDim MyArray(20) As Integer ' Increase to 21 elements When you reset the dimensions of an array, you can use any of the options outlined in the previous sections. This includes declaring multi-dimensional data fields and specifying explicit start and end values. When the dimensions of the data field are changed, all contents are lost. If you want to keep the original values, use the Preserve command: Dim MyArray(10) As Integer ' Defining the initial ' dimensions ' ... ReDim Preserve MyArray(20) As Integer ' Increase in ' data field, while ' retaining content When you use Preserve, ensure that the number of dimensions and the type of variables remain the same.
Arrays
18
Unlike VBA, where only the upper limit of the last dimension of a data field can be changed through Preserve, OpenOffice.org Basic lets you change other dimensions as well.
If you use ReDim with Preserve, you must use the same data type as specified in the original data field declaration. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Arrays&oldid=91348 Principle Authors: Jdpipe, Fpe, Ccornell, TJFrazier
Local Variables
Variables that are declared in a function or a procedure are called local variables: Sub Test Dim MyInteger As Integer ' ... End Sub Local variables only remain valid as long as the function or the procedure is executing, and then are reset to zero. Each time the function is called, the values generated previously are not available. To keep the previous values, you must define the variable as Static: Sub Test Static MyInteger As Integer ' ... End Sub
Unlike VBA, OpenOffice.org Basic ensures that the name of a local variable is not used simultaneously as a global and a private variable in the module header. When you port a VBA application to OpenOffice.org Basic, you must change any duplicate variable names.
19
Global Variables
In terms of their function, global variables are similar to public domain variables, except that their values are retained even after the associated macro has executed. Global variables are declared in the header section of a module using the keyword Global: Global A As Integer
Private Variables
Private variables are only available in the module in which they are defined. Use the keyword Private to define the variable: Private MyInteger As Integer If several modules contain a Private variable with the same name, OpenOffice.org Basic creates a different variable for each occurrence of the name. In the following example, both module A and B have a Private variable called C. The Test function first sets the Private variable in module A and then the Private variable in module B.
Scope and Life Span of Variables Module A: Private C As Integer Sub Test SetModuleA SetModuleB ShowVarA ShowVarB End Sub Sub SetmoduleeA C = 10 End Sub Sub ShowVarA MsgBox C End Sub Module B: Private C As Integer Sub SetModuleB C = 20 End Sub Sub ShowVarB MsgBox C End Sub
20
Sets the variable C from module A Sets the variable C from module B Shows the variable C from module A (= 10) Shows the variable C from module B (= 20)
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Scope_ of_ Variables&oldid=91349 Principle Authors: Fpe, TJFrazier, Ccornell
Constants
Constants are values which may be used but not changed by the program.
Defining Constants
In OpenOffice.org Basic, use the keyword Const to declare a constant. Const A = 10 You can also specify the constant type in the declaration: Const B As Double = 10
Constants
21
Scope of Constants
Constants have the same scope as variables (see Scope and Life Span of Variables), but the syntax is slightly different. A Const definition in the module header is available to the code in that module. To make the definition available to other modules, add the Public keyword. Public Const one As Integer = 1
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Constants&oldid=91350 Principle Authors: Fpe, Ccornell, TJFrazier
Operators
OpenOffice.org Basic understands common mathematical, logical, and comparison operators.
Mathematical Operators
Mathematical operators can be applied to all numbers types, whereas the + operator can also be used to link strings.
+ * / \ ^ MOD Addition of numbers and date values, linking of strings Subtraction of numbers and date values Multiplication of numbers Division of numbers Division of numbers with a whole number result (rounded) Raising the power of numbers modulo operation (calculation of the rest of a division)
Logical Operators
Logical operators allow you to link elements according to the rules of Boolean algebra. If the operators are applied to Boolean values, the link provides the result required directly. If used in conjunction with integer and long integer values, the linking is done at the bit level.
AND OR XOR NOT EQV IMP And linking Or linking Exclusive or linking Negation Equivalent test (both parts True or False) Implication (if the first expression is true, then the second must also be true)
Operators
22
Comparison Operators
Comparison operators can be applied to all elementary variable types (numbers, date details, strings, and Boolean values).
= <> > >= < <= Equality of numbers, date values and strings Inequality of numbers, date values and strings Greater than check for numbers, date values and strings Greater than or equal to check for numbers, date values and strings Less than check for numbers, date values and strings Less than or equal to check for numbers, date values and strings
OpenOffice.org Basic does not support the VBA Like comparison operator.
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Operators&oldid=93077 Principle Authors: Fpe, Ccornell, TJFrazier
Branching
Use branching statements to restrict the execution of a code block until a particular condition is satisfied.
Branching If A = 0 Then B = 0 ElseIf A < 3 Then B = 1 Else B = 2 End If If the value of variable A equals zero, B is assigned the value 0. If A is less than 3 (but not equal to zero), then B is assigned the value 1. In all other instances (that is, if A is greater than or equal to 3), B is assigned the value 2.
23
Select. . . Case
The Select...Case instruction is an alternative to the cascaded If statement and is used when you need to check a value against various conditions: Select Case DayOfWeek Case 1: NameOfWeekday = "Sunday" Case 2: NameOfWeekday = "Monday" Case 3: NameOfWeekday = "Tuesday" Case 4: NameOfWeekday = "Wednesday" Case 5: NameOfWeekday = "Thursday" Case 6: NameOfWeekday = "Friday" Case 7: NameOfWeekday = "Saturday" End Select In this example, the name of a weekday corresponds to a number, so that the DayOfWeek variable is assigned the value of 1 for Sunday, 2 for Monday value, and so on. The Select command is not restricted to simple 1:1 assignments you can also specify comparison operators or lists of expressions in a Case branch. The following example lists the most important syntax variants: Select Case Var Case 1 To 5 ' ... Var is between the numbers 1 and 5 Case 6, 7, 8 ' ... Var is 6, 7 or 8 Case Var > 8 And Var < 11 ' ... Var is greater than 8 and less than 11 Case Else ' ... all other instances
24
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Branching&oldid=91351 Principle Authors: Fpe, Ccornell
Loops
A loop executes a code block for the number of passes that are specified. You can also have loops with an undefined number of passes.
For. . . Next
The For...Next loop has a fixed number of passes. The loop counter defines the number of times that the loop is to be executed. In the following example, variable I is the loop counter, with an initial value of 1. The counter is incremented by 1 at the end of each pass. When variable I equals 10, the loop stops. Dim I For I = 1 To 10 ' ... Inner part of loop Next I If you want to increment the loop counter by a value other than 1 at the end of each pass, use the Step function: Dim I For I = 1 To 10 Step 0.5 ' ... Inner part of loop Next I In the preceding example, the counter is increased by 0.5 at the end of each pass and the loop is executed 19 times. You can also use negative step values: Dim I For I = 10 To 1 Step -1 ' ... Inner part of loop Next I In this example, the counter begins at 10 and is reduced by 1 at the end of each pass until the counter is 1. The Exit For instruction allows you to exit a For loop prematurely. In the following example, the loop is terminated during the fifth pass: Dim I For I = 1 To 10
Loops If I = 5 Then Exit For End If ' ... Inner part of loop Next I
25
For Each
The For Each...Next loop variant in VBA is supported in OpenOffice.org Basic. For Each loops do not use an explicit counter like a For...Next loop does. A For Each loop says "do this to everything in this set", rather than "do this n times". For example: Const d1 = 2 Const d2 = 3 Const d3 = 2 Dim a(d1, d2, d3) For Each i In a() ' ... Inner part of loop Next i
Do. . . Loop
The Do...Loop is not linked to a fixed number of passes. Instead, the Do...Loop is executed until a certain condition is met. There are four versions of the Do...Loop. In the first two examples, the code within the loop may not be executed at all ("do 0 times" logic). In the latter examples, the code will be executed at least once. (In the following examples, A > 10 represents any condition): 1. The Do While...Loop version Do While A > 10 ' ... loop body Loop checks whether the condition after the While is true before every pass and only then executes the loop. 2. The Do Until...Loop version Do Until A > 10 ' ... loop body Loop executes the loop as long as the condition after the Until evaluates to false. 3. The Do...Loop While version Do ' ... loop body Loop While A > 10 only checks the condition after the first loop pass and terminates if the condition after the While evaluates to false.
Loops 4. The Do...Loop Until version Do ' ... loop body Loop Until A > 10 also checks its condition after the first pass, but terminates if the condition after the Until evaluates to true. As in the For...Next loop, the Do...Loop also provides a terminate command. The Exit Do command can exit at loop at any point within the loop. Do If A = 4 Then Exit Do End If ' ... loop body Loop While A > 10
26
Loops
27
Loops
28
External links
[1] http:/ / en. wikipedia. org/ wiki/ Bubble_sort Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Loops&oldid=91352 Principle Authors: Ccornell, TJFrazier, Fpe
Procedures
A procedure executes an action without providing an explicit value. Its syntax is Sub Test ' ... here is the actual code of the procedure End Sub The example defines a procedure called Test that contains code that can be accessed from any point in the program. The call is made by entering the procedure name at the relevant point of the program.
Functions
A function, just like a procedure, combines a block of programs to be executed into one logical unit. However, unlike a procedure, a function provides a return value. Function Test ' ... here is the actual code of the function Test = 123 End Function The return value is assigned using simple assignment. The assignment does not need to be placed at the end of the function, but can be made anywhere in the function. The preceding function can be called within a program as follows: Dim A A = Test The code defines a variable A and assigns the result of the Test function to it. The return value can be overwritten several times within the function. As with classic variable assignment, the function in this example returns the value that was last assigned to it. Function Test Test = 12
Procedures and Functions ' ... Test = 123 End Function In this example, the return value of the function is 123. If nothing is assigned, the function returns a zero value (number 0 for numerical values and a blank for strings). The return value of a function can be any type. The type is declared in the same way as a variable declaration: Function Test As Integer ' ... here is the actual code of the function End Function
29
Passing Parameters
Functions and procedures can receive one or more parameters. Essential parameters must be enclosed in parentheses after the function or procedure names. The following example defines a procedure that expects an integer value A and a string B as parameters. Sub Test (A As Integer, B As String) ' ... End Sub Parameters are normally passed by Reference [1] in OpenOffice.org Basic. Changes made to the variables are retained when the procedure or function is exited: Sub Test Dim A As Integer A = 10 ChangeValue(A) ' The parameter A now has the value 20
Procedures and Functions End Sub Sub ChangeValue(TheValue As Integer) TheValue = 20 End Sub In this example, the value A that is defined in the Test function is passed as a parameter to the ChangeValue function. The value is then changed to 20 and passed to TheValue, which is retained when the function is exited. You can also pass a parameter as a value if you do not want subsequent changes to the parameter to affect the value that is originally passed. To specify that a parameter is to be passed as a value, ensure that the ByVal keyword precedes the variable declaration in the function header. In the preceding example, if we replace the ChangeValue function then the superordinate variable A remains unaffected by this change. After the call for the ChangeValue function, variable A retains the value 10. Sub ChangeValue(ByVal TheValue As Integer) TheValue = 20 End Sub
30
The method for passing parameters to procedures and functions in OpenOffice.org Basic is virtually identical to that in VBA. By default, the parameters are passed by reference. To pass parameters as values, use the ByVal keyword. In VBA, you can also use the keyword ByRef to force a parameter to be passed by reference. OpenOffice.org Basic recognizes but ignores this keyword, because this is already the default procedure in OpenOffice.org Basic.
Optional Parameters
Functions and procedures can only be called up if all the necessary parameters are passed during the call. OpenOffice.org Basic lets you define parameters as optional, that is, if the corresponding values are not included in a call, OpenOffice.org Basic passes an empty parameter. In the following example the A parameter is obligatory, whereas the B parameter is optional. Sub Test(A As Integer, Optional B As Integer) ' ... End Sub The IsMissing function checks whether a parameter has been passed or is left out. Sub Test(A As Integer, Optional B As Integer) Dim B_Local As Integer ' Check whether B parameter is actually present If Not IsMissing (B) Then B_Local = B ' B parameter present Else B_Local = 0 ' B parameter missing -> default value 0 End If
Procedures and Functions ' ... Start the actual function End Sub The example first tests whether the B parameter has been passed and, if necessary, passes the same parameter to the internal B_Local variable. If the corresponding parameter is not present, then a default value (in this instance, the value 0) is passed to B_Local rather than the passed parameter.
The ParamArray keyword present in VBA is not supported in OpenOffice.org Basic.
31
Recursion
A recursive procedure or function is one that has the ability to call itself until it detects that some base condition has been satisfied. When the function is called with the base condition, a result is returned. The following example uses a recursive function to calculate the factorial of the numbers 42, -42, and 3.14: Sub Main Msgbox CalculateFactorial( 42 ) ' Displays 1,40500611775288E+51 Msgbox CalculateFactorial( -42 ) ' Displays "Invalid number for factorial!" Msgbox CalculateFactorial( 3.14 ) ' Displays "Invalid number for factorial!" End Sub Function CalculateFactorial( Number ) If Number < 0 Or Number <> Int( Number ) Then CalculateFactorial = "Invalid number for factorial!" ElseIf Number = 0 Then CalculateFactorial = 1 Else ' This is the recursive call: CalculateFactorial = Number * CalculateFactorial( Number - 1 ) Endif End Function The example returns the factorial of the number 42 by recursively calling the CalculateFactorial function until it reaches the base condition of 0! = 1.
The recursion levels are set at different levels based on the software platform. For Windows the recursion level is 5800. For Solaris and Linux, an evaluation of the stacksize is performed and the recursion level is calculated.
32
External links
[1] http:/ / en. wikipedia. org/ wiki/ Pass_by_reference#Call_by_reference Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Procedures_ and_ Functions&oldid=91354 Principle Authors: Ccornell, Fpe, TJFrazier
Error Handling
Correct handling of error situations is one of the most time-consuming tasks of programming. OpenOffice.org Basic provides a range of tools for simplifying error handling.
Error Handling To continue a program without an error message when an error occurs, use the following format: Sub Test On Error Resume Next ' ... perform task during which an error may occur End Sub Use the On Error Resume Next command with caution as its effect is global.
33
The status information remains valid until the program encounters a Resume or On Error command, whereupon the information is reset.
In VBA, the Err.Clear method of the Err object resets the error status after an error occurs. In OpenOffice.org Basic, this is accomplished with the On Error or Resume commands.
Error Handling On Error Goto 0 ' Deactivate error handling ' End of regular program implementation Exit Sub ' Start point of error handling ErrorHandler: ' Check whether error was expected If Err = ExpectedErrorNo Then ' ... Process error Else ' ... Warning of unexpected error End If On Error Goto 0 ' Deactivate error handling End Sub This procedure begins with the definition of an error handler, followed by the actual program code. At the end of the program code, the error handling is deactivated by the On Error Goto 0 call and the procedure implementation is ended by the Exit Sub command (not to be confused with End Sub). The example first checks if the error number corresponds to the expected number (as stored in the imaginary ExpectedErrorNo constant) and then handles the error accordingly. If another error occurs, the system outputs a warning. It is important to check the error number so that unanticipated errors can be detected. The On Error Goto 0 call at the end of the code resets the status information of the error (the error code in the Err system variables) so that an error occurring at a later date can be clearly recognized. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Error_ Handling&oldid=91355 Principle Authors: Ccornell, Fpe, Strompf
34
Error Handling
35
Runtime Library
Documentation/BASIC Guide/ Runtime Library
The following sections present the central functions of the runtime library: Conversion Functions Strings Date and Time Files and Directories Message and Input Boxes Other Functions
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Runtime_ Library&oldid=91356 Principle Authors: Fpe
Conversion Functions
In many situations, circumstances arise in which a variable of one type has to be changed into a variable of another type.
Conversion Functions Dim A As String Dim B As Integer Dim C As Integer B = 1 C = 1 A = B + C which at first glance seems straightforward, ultimately proves to be something of a trap. The Basic interpreter first calculates the result of the addition process and then converts this into a string, which, as its result, produces the string 2. If, on the other hand, the Basic interpreter first converts the start values B and C into a string and applies the plus operator to the result, it produces the string 11. The same applies when using variant variables: Dim A Dim B Dim C B = 1 C = "1" A = B + C Since variant variables may contain both numbers and strings, it is unclear whether variable A is assigned the number 2 or the string 11. The error sources noted for implicit type conversions can only be avoided by careful programming; for example, by not using the variant data type. To avoid other errors resulting from implicit type conversions, OpenOffice.org Basic offers a range of conversion functions, which you can use to define when the data type of an operation should be converted: CStr(Var) converts any data type into a string. CInt(Var) converts any data types into an integer value. CLng(Var) converts any data types into a long value. CSng(Var) converts any data types into a single value. CDbl(Var) converts any data types into a double value. CBool(Var) converts any data types into a Boolean value. CDate(Var) converts any data types into a date value.
36
Conversion Functions You can use these conversion functions to define how OpenOffice.org Basic should perform these type conversion operations: Dim A As String Dim B As Integer Dim C As Integer B = 1 C = 1 A = CStr(B + C) A = CStr(B) + CStr(C)
37
B and C are added together first, then converted to the string "2" B and C are converted into a string,then combined to produce the string "11"
During the first addition in the example, OpenOffice.org Basic first adds the integer variables and then converts the result into a chain of characters. A is assigned the string 2. In the second instance, the integer variables are first converted into two strings and then linked with one another by means of the assignment. A is therefore assigned the string 11. The numerical CSng and CDbl conversion functions also accept decimal numbers. The symbol defined in the corresponding country-specific settings must be used as the decimal point symbol. Conversely, the CStr methods use the currently selected country-specific settings when formatting numbers, dates and time details. The Val function is different from the Csng, Cdbl and Cstr methods. It converts a string into a number; however it always expects a period to be used as the decimal point symbol. Dim A As String Dim B As Double A = "2.22" B = Val(A)
In the example shown, the assignment of the test string to a date variable makes no sense, so the Basic interpreter reports an error. The same applies when attempting to assign a string to a Boolean variable: Dim A As String Dim B As Boolean
38
Again, the basic interpreter reports an error. These error messages can be avoided by checking the program before an assignment, in order to establish whether the content of the variable to be assigned matches the type of the target variable. OpenOffice.org Basic provides the following test functions for this purpose: IsNumeric(Value) checks whether a value is a number. IsDate(Value) checks whether a value is a date. IsArray(Value) checks whether a value is an array. These functions are especially useful when querying user input. For example, you can check whether a user has typed a valid number or date. If IsNumeric(UserInput) Then ValidInput = UserInput Else ValidInput = 0 MsgBox "Error message." End If In the previous example, if the UserInput variable contains a valid numerical value, then this is assigned to the ValidInput variable. If UserInput does not contain a valid number, ValidInput is assigned the value 0 and an error message is returned. While test functions exist for checking numbers, date details and arrays in OpenOffice.org Basic, a corresponding function for checking Boolean values does not exist. The functionality can, however, be imitated by using the IsBoolean function: Function IsBoolean(Value As Variant) As Boolean On Error Goto ErrorIsBoolean: Dim Dummy As Boolean Dummy = Value IsBoolean = True On Error Goto 0 Exit Sub ErrorIsBoolean: IsBoolean = False On Error Goto 0 End Function The IsBoolean function defines an internal Dummy help variable of the Boolean type and tries to assign this to the transferred value. If assignment is successful, the function returns True. If it fails, a runtime error is produced, which intercepts the test function to return an
39
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Conversion_ Functions_ (Runtime_ Library)&oldid=91372 Principle Authors: Fpe, Ccornell
Strings
Working with Sets of Characters
When administering strings, OpenOffice.org Basic uses the set of Unicode characters. The Asc and Chr functions allow the Unicode value belonging to a character to be established and/or the corresponding character to be found for a Unicode value. The following expressions assign the various Unicode values to the code variable: Code = Asc("A") ' Latin letter A (Unicode-value 65) Code = Asc("") ' Euro character (Unicode-value 8364) Code = Asc("") ' Cyrillic letter (Unicode-value 1083) Conversely, the expression MyString = Chr(13) ensures that the MyString string is initialized with the value of the number 13, which stands for a hard line break. The Chr command is often used in Basic languages to insert control characters in a string. The assignment MyString = Chr(9) + "This is a test" + Chr(13) therefore ensures that the text is preceded by a tab character (Unicode-value 9) and that a hard line break (Unicode-value 13) is added after the text.
Strings returns first Length characters of MyString as of the Start position. Len(MyString) returns the number of characters in MyString. Here are a few example calls for the named functions: Dim MyString As String Dim MyResult As String Dim MyLen As Integer MyString = "This is a small test" MyResult = Left(MyString,5) ' MyResult = Right(MyString, 5) ' MyResult = Mid(MyString, 8, 5) ' MyLen = Len(MyString) '
40
string "This " string " test" string " a sm" value 21
Strings Else Do While CurrentPos <> 0 CurrentPos = InStr(StartPos, Source, Search) If CurrentPos <> 0 Then Result = Result + Mid(Source, StartPos, _ CurrentPos - StartPos) Result = Result + NewPart StartPos = CurrentPos + Len(Search) Else Result = Result + Mid(Source, StartPos, Len(Source)) End If ' Position <> 0 Loop End If Replace = Result End Function The function searches through the transferred Search string in a loop by means of InStr in the original term Source. If it finds the search term, it takes the part before the expression and writes it to the Result return buffer. It adds the new Part section at the point of the search term Search. If no more matches are found for the search term, the function establishes the part of the string still remaining and adds this to the return buffer. It returns the string produced in this way as the result of the replacement process. Since replacing parts of character sequences is one of the most frequently used functions, the Mid function in OpenOffice.org Basic has been extended so that this task is performed automatically. The following example replaces three characters with the string is from the sixth position of the MyString string. Dim MyString As String MyString = "This was my text" Mid(MyString, 6, 3, "is")
41
Formatting Strings
The Format function formats numbers as a string. To do this, the function expects a Format expression to be specified, which is then used as the template for formatting the numbers. Each place holder within the template ensures that this item is formatted correspondingly in the output value. The five most important place holders within a template are the zero (0), pound sign (#), period (.), comma (,) and dollar sign ($) characters. The 0 character within the template ensures that a number is always placed at the corresponding point. If a number is not provided, 0 is displayed in its place. A . stands for the decimal point symbol defined by the operating system in the country-specific settings. The example below shows how the 0 and . characters can define the digits after the decimal point in an expression:
Strings MyFormat MyString MyString MyString MyString = = = = = "0.00" Format(-1579.8, MyFormat) Format(1579.8, MyFormat) Format(0.4, MyFormat) Format(0.434, MyFormat)
42
In the same way, zeros can be added in front of a number to achieve the desired length: MyFormat MyString MyString MyString MyString = = = = = "0000.00" Format(-1579.8, MyFormat) Format(1579.8, MyFormat) Format(0.4, MyFormat) Format(0.434, MyFormat)
A , represents the character that the operating system uses for a thousands separator, and the # stands for a digit or place that is only displayed if it is required by the input string. MyFormat MyString MyString MyString MyString = = = = = "#,##0.00" Format(-1579.8, MyFormat) Format(1579.8, MyFormat) Format(0.4, MyFormat) Format(0.434, MyFormat)
In place of the $ place holder, the Format function displays the relevant currency symbol defined by the system (this example assumes a European locale has been defined): MyFormat MyString MyString MyString MyString = = = = = "#,##0.00 $" Format(-1579.8, MyFormat) ' Provides "-1.579,80 " Format(1579.8, MyFormat) ' Provides "1.579,80 " Format(0.4, MyFormat) ' Provides "0,40 " Format(0.434, MyFormat) ' Provides "0,43 "
The format instructions used in VBA for formatting date and time details can also be used: sub main dim myDate as date myDate = "01/06/98" TestStr = Format(myDate, "mm-dd-yyyy") ' 01-06-1998 MsgBox TestStr end sub
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Strings_ (Runtime_ Library)&oldid=91375 Principle Authors: Ccornell, Fpe, SingleTrackMind
43
Date and Time Weekday(MyDate) returns the number of the weekday from MyDate. Hour(MyTime) returns the hours from MyTime. Minute(MyTime) returns the minutes from MyTime. Second(MyTime) returns the seconds from MyTime. These functions extract the date or time sections from a specified Date variable. The following example checks whether the date saved in MyDate is in the year 2003. Dim MyDate As Date ' ... Initialization of MyDate If Year(MyDate) = 2003 Then ' ... Specified date is in the year 2003 End If In the same way, the following example checks whether MyTime is between 12 and 14 hours. Dim MyTime As Date ' ... Initialization of MyTime If Hour(MyTime) >= 12 And Hour(MyTime) < 14 Then ' ... Specified time is between 12 and 14 hours End If The Weekday function returns the number of the weekday for the transferred date: Dim MyDate As Date Dim MyWeekday As String ' ... initialize MyDate Select Case WeekDay(MyDate) case 1 MyWeekday = "Sunday" case 2 MyWeekday = "Monday" case 3 MyWeekday = "Tuesday" case 4 MyWeekday = "Wednesday" case 5 MyWeekday = "Thursday" case 6 MyWeekday = "Friday"
44
45
46
Administering Files
Searching Through Directories
The Dir function in OpenOffice.org Basic is responsible for searching through directories for files and sub-directories. When first requested, a string containing the path of the directories to be searched must be assigned to Dir as its first parameter. The second parameter of Dir specifies the file or directory to be searched for. OpenOffice.org Basic returns the name of the first directory entry found. To retrieve the next entry, the Dir function should be requested without parameters. If the Dir function finds no more entries, it returns an empty string. The following example shows how the Dir function can be used to request all files located in one directory. The procedure saves the individual file names in the AllFiles variable and then displays this in a message box. Sub ShowFiles Dim NextFile As String Dim AllFiles As String AllFiles = "" NextFile = Dir("C:\", 0) While NextFile <> "" AllFiles = AllFiles & Chr(13) & NextFile = Dir Wend MsgBox AllFiles End Sub The 0 (zero) used as the second parameter in the Dir function ensures that Dir only returns the names of files and directories are ignored. The following parameters can be specified here: 0 : returns normal files 16 : sub-directories The following example is virtually the same as the preceding example, but the Dir function transfers the value 16 as a parameter, which returns the sub-directories of a folder rather than the file names. Sub ShowDirs Dim NextDir As String Dim AllDirs As String AllDirs = "" NextDir = Dir("C:\", 16) While NextDir <> "" AllDirs = AllDirs & Chr(13) &
NextFile
NextDir
47
When requested in OpenOffice.org Basic, the Dir function, using the parameter 16, only returns the sub-directories of a folder. In VBA, the function also returns the names of the standard files so that further checking is needed to retrieve the directories only. When using the CompatibilityMode ( true ) function, OpenOffice.org Basic behaves like VBA and the Dir function, using parameter 16, returns sub-directories and standard files.
The options provided in VBA for searching through directories specifically for files with the concealed, system file, archived, and volume name properties does not exist in OpenOffice.org Basic because the corresponding file system functions are not available on all operating systems.
The path specifications listed in Dir may use the * and ? place holders in both VBA and OpenOffice.org Basic. In OpenOffice.org Basic, the * place holder may however only be the last character of a file name and/or file extension, which is not the case in VBA.
In VBA, RmDir produces an error message if a directory contains a file. In OpenOffice.org Basic, the directory and all its files are deleted. If you use the CompatibilityMode ( true ) function, OpenOffice.org Basic will behave like VBA.
48
49
If FileDescription = "" Then FileDescription = " normal " End IF MsgBox FileDescription
The flags used in VBA for querying the concealed, system file,archived and volume name file properties are not supported in OpenOffice.org Basic because these are Windows-specific and are not or are only partially available on other operating systems.
The SetAttr function permits the properties of a file to be changed. The following call can therefore be used to provide a file with read-only status: SetAttr("test.txt", 1) An existing read-only status can be deleted with the following call: SetAttr("test.txt", 0) The date and time of the last amendment to a file are provided by the FileDateTime function. The date is formatted here in accordance with the country-specific settings used on the system. FileDateTime("test.txt") ' Provides date and time of the last file amendment. The FileLen function determines the length of a file in bytes (as long integer value). FileLen("test.txt") ' Provides the length of the file in bytes
Files and Directories FileNo also stands for the file handle here. The second parameter specifies the text that is to be saved as a line of the text file. Once the writing process has been completed, the file must be closed using a Close call: Close #FileNo Again here, the file handle should be specified. The following example shows how a text file is opened, described and closed: Dim FileNo As Integer Dim CurrentLine As String Dim Filename As String Filename = "c:\data.txt" FileNo = Freefile ' Define file name ' Establish free file handle
50
Open Filename For Output As #FileNo ' Open file (writing mode) Print #FileNo, "This is a line of text" ' Save line Print #FileNo, "This is another line of text" ' Save line Close #FileNo ' Close file
' Define filename Filename = "c:\data.txt" ' Establish free file handle FileNo = Freefile ' Open file (reading mode) Open Filename For Input As FileNo ' Check whether file end has been reached
Files and Directories Do While not eof(FileNo) ' Read line Line Input #FileNo, CurrentLine If CurrentLine <>"" then Msg = Msg & CurrentLine & Chr(13) end if Loop
51
' Close file Close #FileNo Msgbox Msg The individual lines are retrieved in a Do While loop, saved in the Msg variable, and displayed at the end in a message box. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Files_ and_ Directories_ (Runtime_ Library)&oldid=91379 Principle Authors: Fpe, Ccornell
Displaying Messages
MsgBox displays a basic information box, which can have one or more buttons. In its simplest variant the MsgBox only contains text and an OK button: MsgBox "This is a piece of information!" The appearance of the information box can be changed using a parameter. The parameter provides the option of adding additional buttons, defining the pre-assigned button, and adding an information symbol. The values for selecting the buttons are: 0 1 2 3 4 5 OK button OK and Cancel button Abort, Retry, and Ignore buttons Yes, No, and Cancel buttons Yes and No buttons Retry and Cancel buttons
To set a button as the default button, add one of the following values to the parameter value from the list of button selections. For example, to create Yes, No and Cancel buttons (value 3) where Cancel is the default (value 512), the parameter value is 3 + 512 = 515. 0 - First button is default value 256 - Second button is default value
Message and Input Boxes 512 - Third button is default value Finally, the following information symbols are available and can also be displayed by adding the relevant parameter values: 16 32 48 64 Stop sign Question mark Exclamation point Tip icon
52
The following call displays an information box with the Yes and No buttons (value 4), of which the second button (No) is set as the default value (value 256) and which also receives a question mark (value 32), 4+256+32=292. MsgBox "Do you want to continue?", 292
If an information box contains several buttons, then a return value should be queried to determine which button has been pressed. The following return values are available in this instance: 1 - Ok 2 3 4 5 6 7 Cancel Abort Retry Ignore Yes No
In the previous example, checking the return values could be as follows: If MsgBox ("Do you want to continue?", ' Yes button pressed Else ' No button pressed End IF 292) = 6 Then
In addition to the information text and the parameter for arranging the information box, MsgBox also permits a third parameter, which defines the text for the box title: MsgBox "Do you want to continue?", 292, "Box Title"
53
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Message_ and_ Input_ Boxes_ (Runtime_ Library)&oldid=91381 Principle Authors: Ccornell, Fpe, TJFrazier
Other Functions
Beep
The Beep function causes the system to play a sound that can be used to warn the user of an incorrect action. Beep does not have any parameters: Beep ' creates an informative tone
Shell
External programs can be started using the Shell function. Shell(Pathname, Windowstyle, Param) Pathname defines the path of the program to be executed. Windowstyle defines the window in which the program is started. The following values are possible: 0 1 2 3 4 The The The The The program program program program program receives the focus and is started in a concealed window. receives the focus and is started in a normal-sized window. receives the focus and is started in a minimized window. receives the focus and is started in a maximized window. is started in a normal-sized window, without receiving the focus.
6 - The program is started in a minimized window, the focus remains in the current window. 10 - The program is started in full screen mode. The third parameter, Param, permits command line parameters to be transferred to the program to be started.
Other Functions
54
Wait
The Wait function terminates program execution for a specified time. The waiting period is specified in milliseconds. The command Wait 2000 specifies an interrupt of 2 seconds (2000 milliseconds).
Environ
The Environ function returns the environmental variables of the operating system. Depending on the system and configuration, various types of data are saved here. The following call determines the environment variables of temporary directory of the operating system: Dim TempDir TempDir=Environ ("TEMP")
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Other_ Functions_ (Runtime_ Library)&oldid=91382 Principle Authors: Fpe, Ccornell
Other Functions
55
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ API_ Intro&oldid=91452 Principle Authors: Fpe
Universal Network Objects (UNO) The object variable created must then be initialized so that it can be used. This can be done using the createUnoService function: Obj = createUnoService("com.sun.star.frame.Desktop") This call assigns to the Obj variable a reference to the newly created object. com.sun.star.frame.Desktop resembles an object type; however in UNO terminology it is called a service rather than a type. In accordance with UNO philosophy, an Obj is described as a reference to an object which supports the com.sun.star.frame.Desktop service. The service term used in OpenOffice.org Basic therefore corresponds to the type and class terms used in other programming languages. There is, however, one main difference: a Universal Network Object may support several services at the same time. Some UNO services in turn support other services so that, through one object, you are provided with a whole range of services. For example, that the aforementioned object, which is based on the com.sun.star.frame.Desktop service, can also include other services for loading documents and for ending the program.
Whereas the structure of an object in VBA is defined by the class to which it belongs, in OpenOffice.org Basic the structure is defined through the services which it supports. A VBA object is always assigned to precisely one single class. A OpenOffice.org Basic object can, however, support several services.
56
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ UNO&oldid=91453 Principle Authors: Ccornell, Fpe
Properties
Properties are like the properties of an object; for example, Filename and Title for a Document object. The properties are set by means of a simple assignment: Document.Title = "{{OOo}} Basic Programmer's Guide" Document.Filename = "basguide.odt" A property, just like a normal variable, has a type that defines which values it can record. The preceding Filename and Title properties are of the string type.
57
Methods
Methods can be understood as functions that relate directly to an object and through which this object is called. The preceding Document object could, for example, provide a Save method, which can be called as follows: Document.Save() Methods, just like functions, may contain parameters and return values. The syntax of such method calls is oriented towards classic functions. The following call also specifies the True parameter for the document object when requesting the Save method. Ok = Document.Save(True) Once the method has been completed, Save saves a return value in the Ok variable. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Properties_ and_ Methods_ (API)&oldid=91455 Principle Authors: Fpe, Ccornell
Modules, Services and Interfaces This detail may be of interest in particular to Java- or C++ programmers, since in these languages, the interface is needed to request a method. In OpenOffice.org Basic, this is irrelevant. Here, the methods are called directly by means of the relevant object. For an understanding of the API, it is, however, useful to have the assignment of methods to various interfaces handy, since many interfaces are used in the different services. If you are familiar with an interface, then you can transfer your knowledge from one service to another. Some central interfaces are used so frequently, triggered by different services, that they are shown again at the end of this chapter. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Modules,_ Services_ and_ Interfaces&oldid=91456 Principle Authors: Ccornell, Fpe
58
Debug Properties
Every UNO object in OpenOffice.org Basic knows what properties, methods and interfaces it already contains. It provides properties that return these in the form of a list. The corresponding properties are: DBG_properties returns a string containing all properties of an object DBG_methods returns a string containing all methods of an object DBG_supportedInterfaces returns a string containing all interfaces which support an object.
Tools for Working with UNO The following program code shows how DBG_properties and DBG_methods can be used in real-life applications. It first creates the com.sun.star.frame.Desktop service and then displays the supported properties and methods in message boxes. Dim Obj As Object Obj = createUnoService("com.sun.star.frame.Desktop") MsgBox Obj.DBG_Properties MsgBox Obj.DBG_methods When using DBG_properties, note that the function returns all properties that one particular service can theoretically support. No assurances are, however, provided for whether these can also be used by the object in question. Before calling up properties, you must therefore use the IsEmpty function to check whether this is actually available.
59
API Reference
More information about the available services, and their interfaces, methods and properties can be found in the reference for the OpenOffice.org API [1].
External links
[1] http:/ / api. openoffice. org/ docs/ common/ ref/ com/ sun/ star/ module-ix. html Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ UNO_ Tools&oldid=91458 Principle Authors: Ccornell, Fpe, TJFrazier, Billiam
60
Overview of Central Interfaces Dim Sheets As Object Dim SheetNames Dim I As Integer Sheets = Spreadsheet.Sheets SheetNames = Sheets.getElementNames For I=LBound(SheetNames) To UBound(SheetNames) MsgBox SheetNames(I) Next I The hasByName method of the XNameAccess interface reveals whether a subordinate object with a particular name exists within the basic object. The following example therefore displays a message that informs the user whether the Spreadsheet object contains a page of the name Sheet1. Dim Sheets As Object Sheets = Spreadsheet.Sheets If Sheets.HasByName("Sheet1") Then MsgBox " Sheet1 available" Else MsgBox "Sheet1 not available" End If
61
62
63
64
The StarDesktop
When working with documents, there are two services which are used most frequently: The com.sun.star.frame.Desktop service, which is similar to the core service of OpenOffice.org. It provides the functions for the frame object of OpenOffice.org, under which all document windows are classified. Documents can also be created, opened and imported using this service. The basic functionality for the individual document objects is provided by the com.sun.star.document.OfficeDocument service. This provides the methods for saving, exporting and printing documents. The com.sun.star.frame.Desktop service is created automatically when OpenOffice.org is started. This service can be addressed in OpenOffice.org Basic using the global name StarDesktop. The most important interface of the StarDesktop is com.sun.star.frame.XComponentLoader . This basically covers the loadComponentFromURL method, which is responsible for creating, importing, and opening documents.
The StarDesktop The name of the StarDesktop object dates back to StarOffice 5, in which all document windows were embedded in one common application called StarDesktop. In the present version of OpenOffice.org, a visible StarDesktop is no longer used. The name StarDesktop was, however, retained for the frame object of OpenOffice.org because it clearly indicates that this is a basic object for the entire application. The StarDesktop object replaces the Application object of StarOffice 5 which previously applied as a root object. Unlike the old Application object however it is primarily responsible for opening new documents. The functions resident in the old Application object for controlling the on-screen depiction of OpenOffice.org (for example, FullScreen, FunctionBarVisible, Height, Width, Top, Visible) are no longer used.
Whereas the active document in Word is accessed through Application.ActiveDocument and in Excel through Application.ActiveWorkbook, in OpenOffice.org, the StarDesktop is responsible for this task. The active document object is accessed in OpenOffice.org through the StarDesktop.CurrentComponent property, or through ThisComponent.
65
ThisComponent
ThisComponent generally returns the same object as StarDesktop.CurrentComponent, with one significant advantage. If you are running from within the Basic IDE, debugging or exploring, then StarDesktop returns the Basic IDE itself. This is probably not what you want. ThisComponent returns the last previously active document.
The StarDesktop The example converts a local file name into a URL and displays it in a message box. It then converts a URL into a local file name and also displays this. The Internet Standard RFC 1738, upon which this is based, permits use of the 0-9, a-z, and A-Z characters. All other characters are inserted as escape coding in the URLs. To do this, they are converted into their hexadecimal value in the ISO 8859-1 (ISO-Latin) set of characters and are preceded by a percent sign. A space in a local file name therefore, for example, becomes a %20 in the URL.
66
Compression of Files
Since XML is based on standard text files, the resultant files are usually very large. OpenOffice.org therefore compresses the files and saves them as a ZIP file. By means of a storeAsURL method option, the user can save the original XML files directly. See storeAsURL Method Options.
The StarDesktop
67
SearchFlags = com.sun.star.frame.FrameSearchFlag.CREATE + _ com.sun.star.frame.FrameSearchFlag.ALL Url = "file:///C:/test.odt" Doc = StarDesktop.loadComponentFromURL(Url, "MyFrame", SearchFlags, Dummy) MsgBox "Press OK to display the second document." Url = "file:///C:/test2.odt" Doc = StarDesktop.loadComponentFromURL(Url, "MyFrame", _ SearchFlags, Dummy) The example first opens the test.odt file in a new window with the frame name of MyFrame. Once the message box has been confirmed, it replaces the content of the window with the test2.odt file.
The StarDesktop specifies a special filter for the loadComponentFromURL function. The filter names available are defined in the \share\config\registry\instance\org\openoffice\office\TypeDetection.xml file. FilterOptions (String) defines additional options for filters. JumpMark (String) once a document has been opened, jumps to the position defined in JumpMark. Password (String) transfers a password for a protected file. ReadOnly (Boolean) loads a read-only document. The following example shows how a text file separated by a comma in OpenOffice.org Calc can be opened using the FilterName option. Dim Doc As Object Dim FileProperties(0) As New com.sun.star.beans.PropertyValue Dim Url As String Url = "file:///C:/csv.doc" FileProperties(0).Name = "FilterName" FileProperties(0).Value ="scalc: Text - txt - csv ({{OOo}} Calc)" Doc = StarDesktop.loadComponentFromURL(Url, "_blank", 0, FileProperties()) The FileProperties data field covers precisely one value because it records one option. The Filtername property defines whether OpenOffice.org uses a OpenOffice.org Calc text filter to open files.
68
The StarDesktop
69
Document Objects
The loadComponentFromURL function introduced in the previous section returns a document object. This supports the com.sun.star.document.OfficeDocument service, which in turn provides two central interfaces: The com.sun.star.frame.XStorable interface, which is responsible for saving documents. The com.sun.star.view.XPrintable interface, which contains the methods for printing documents.
The StarDesktop specifies whether a document has read-only protection. isModified() specifies whether a document has been modified since it was last saved. The code for saving a document can be extended by these options so that the document is only saved if the object has actually been modified and the file name is only queried if it is actually needed: If (Doc.isModified) Then If (Doc.hasLocation And (Not Doc.isReadOnly)) Then Doc.store() Else Doc.storeAsURL(URL, Dummy()) End If End If The example first checks whether the relevant document has been modified since it was last saved. It only continues with the saving process if this is the case. If the document has already been assigned a URL and is not a read-only document, it is saved under the existing URL. If it does not have a URL or was opened in its read-only status, it is saved under a new URL.
70
The StarDesktop Dim Doc As Object Dim FileProperties(0) As New com.sun.star.beans.PropertyValue Dim Url As String ' ... Initialize Doc Url = "file:///c:/test3.odt" FileProperties(0).Name = "Overwrite" FileProperties(0).Value = True Doc.storeAsURL(sUrl, mFileProperties()) The example then saves Doc under the specified file name if a file already exists under the name.
71
Printing Documents
Similar to saving, documents are printed out directly by means of the document object. The Print method of the com.sun.star.view.Xprintable interface is provided for this purpose. In its simplest form, the print call is: Dim Dummy() Doc.print(Dummy()) As in the case of the loadComponentFromURL method, the Dummy parameter is a PropertyValue data field through which OpenOffice.org can specify several options for printing.
The StarDesktop Dim Doc As Object Dim PrintProperties(0) As New com.sun.star.beans.PropertyValue PrintProperties(0).Name="Pages" PrintProperties(0).Value="1-3; 7; 9" Doc.print(PrintProperties())
72
The StarDesktop PrinterProperties (1).Name="PaperSize" PrinterProperties (1).Value=PaperSize Doc.Printer = PrinterProperties() The example defines an object named PaperSize with the com.sun.star.awt.Size type. This is needed to specify the paper size. Furthermore, it creates a data field for two PropertyValue entries named PrinterProperties. This data field is then initialized with the values to be set and assigned the Printer property. From the standpoint of UNO, the printer is not a real property but an imitated one. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ StarDesktop&oldid=91468 Principle Authors: Ccornell, Fpe, TJFrazier, KentTong
73
Templates
Templates are named lists containing formatting attributes. They move through all applications of OpenOffice.org and help to significantly simplify formatting. If the user changes one of the attributes of a template, then OpenOffice.org automatically adjusts all document sections depending on the attribute. The user can therefore, for example, change the font type of all level one headers by means of a central modification in the document. Depending on the relevant document types, OpenOffice.org recognizes a whole range of different types of template. OpenOffice.org Writer supports the following templates: Character templates Paragraph templates Frame templates Page templates Numbering templates
OpenOffice.org Calc supports the following templates: Cell template Page templates OpenOffice.org Impress supports the following templates: Character element templates Presentation templates In OpenOffice.org terminology, the different types of templates are called StyleFamilies in accordance with the com.sun.star.style.StyleFamily service on which they are based. The StyleFamilies are accessed by means of the document object:
Templates Dim Dim Dim Dim Doc As Object Sheet As Object StyleFamilies As Object CellStyles As Object
74
Doc = StarDesktop.CurrentComponent StyleFamilies = Doc.StyleFamilies CellStyles = StyleFamilies.getByName("CellStyles") The example uses the StyleFamilies property of a spreadsheet document to establish a list containing all available cell templates. The individual templates can be accessed directly by means of an index: Dim Dim Dim Dim Dim Dim Doc As Object Sheet As Object StyleFamilies As Object CellStyles As Object CellStyle As Object I As Integer
Doc = StarDesktop.CurrentComponent StyleFamilies = Doc.StyleFamilies CellStyles = StyleFamilies.getByName("CellStyles") For I = 0 To CellStyles.Count - 1 CellStyle = CellStyles(I) MsgBox CellStyle.Name Next I The loop added since the previous example displays the names of all cell templates one after another in a message box.
Templates service Page properties, com.sun.star.style.PageProperties service Character element properties, Various services The format properties are by no means restricted to the applications in which these are explained, but instead can be used universally. For example, most of the page properties described in Spreadsheets can therefore be used not only in OpenOffice.org Calc, but also in OpenOffice.org Writer. More information about working with templates can be found in the Default values for character and paragraph properties section in Text Documents. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Templates&oldid=91470 Principle Authors: Ccornell, Fpe
75
Templates
76
Text Documents
Text Documents
In addition to pure strings, text documents also contain formatting information. These may appear at any point in the text. The structure is further complicated by tables. These include not only single-dimensional strings, but also two-dimensional fields. Most word processing programs now finally provide the option of placing drawing objects, text frames and other objects within a text. These may be outside the flow of text and can be positioned anywhere on the page. This chapter presents the central interfaces and services of text documents. The Structure of Text Documents Editing Text Documents More than Just Text The first section deals with the anatomy of text documents and concentrates on how a OpenOffice.org Basic program can be used to take iterative steps through a OpenOffice.org document. It focuses on paragraphs, paragraph portions and their formatting. The second section focuses on efficiently working with text documents. For this purpose, OpenOffice.org provides several help objects, such as the TextCursor object, which extend beyond those specified in the first section. The third section moves beyond work with texts. It concentrates on tables, text frames, text fields, bookmarks, content directories and more. Information about how to create, open, save and print documents is described in Working with Documents, because it can be used not only for text documents, but also for other types of documents. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Text_ Documents&oldid=91471 Principle Authors: Fpe
77
The Structure of Text Documents current element to TextElement object. The example uses the supportsService method to check whether the TextElement is a paragraph or a table.
78
Paragraphs
The com.sun.star.text.Paragraph service grants access to the content of a paragraph. The text in the paragraph can be retrieved and modified using the String property: Dim Doc As Object Dim Enum As Object Dim TextElement As Object Doc = StarDesktop.CurrentComponent Enum = Doc.Text.createEnumeration While Enum.hasMoreElements TextElement = Enum.nextElement If TextElement.supportsService("com.sun.star.text.Paragraph") Then TextElement.String = Replace(TextElement.String, "you", "U") TextElement.String = Replace(TextElement.String, "too", "2") TextElement.String = Replace(TextElement.String, "for", "4") End If Wend The example opens the current text document and passes through it with the help of the Enumeration object. It uses the TextElement.String property in all paragraphs to access the relevant paragraphs and replaces the you, too and for strings with the U, 2 and 4 characters. The Replace function used for replacing does not fall within the standard linguistic scope of OpenOffice.org Basic. This is an instance of the example function described in Search and Replace.
The content of the procedure described here for accessing the paragraphs of a text is comparable with the Paragraphs listing used in VBA, which is provided in the Range and Document objects available there. Whereas in VBA the paragraphs are accessed by their number (for example, by the Paragraph(1) call), in OpenOffice.org Basic, the Enumeration object described previously should be used.
There is no direct counterpart in OpenOffice.org Basic for the Characters, Sentences and Words lists provided in VBA. You do, however, have the option of switching to a TextCursor which allows for navigation at the level of characters, sentences and words.
79
Paragraph Portions
The previous example may change the text as requested, but it may sometimes also destroy the formatting. This is because a paragraph in turn consists of individual sub-objects. Each of these sub-objects contains its own formatting information. If the center of a paragraph, for example, contains a word printed in bold, then it will be represented in OpenOffice.org by three paragraph portions: the portion before the bold type, then the word in bold, and finally the portion after the bold type, which is again depicted as normal. If the text of the paragraph is now changed using the paragraph's String property, then OpenOffice.org first deletes the old paragraph portions and inserts a new paragraph portion. The formatting of the previous sections is then lost. To prevent this effect, the user can access the associated paragraph portions rather than the entire paragraph. Paragraphs provide their own Enumeration object for this purpose. The following example shows a double loop which passes over all paragraphs of a text document and the paragraph portions they contain and applies the replacement processes from the previous example: Dim Dim Dim Dim Dim Doc As Object Enum1 As Object Enum2 As Object TextElement As Object TextPortion As Object
Doc = StarDesktop.CurrentComponent Enum1 = Doc.Text.createEnumeration ' loop over all paragraphs While Enum1.hasMoreElements TextElement = Enum1.nextElement If TextElement.supportsService("com.sun.star.text.Paragraph") Then Enum2 = TextElement.createEnumeration ' loop over all sub-paragraphs While Enum2.hasMoreElements TextPortion = Enum2.nextElement MsgBox "'" & TextPortion.String & "'" TextPortion.String = Replace(TextPortion.String, "you", "U") TextPortion.String = Replace(TextPortion.String, "too", "2") TextPortion.String = Replace(TextPortion.String, "for", "4") Wend End If Wend The example runs through a text document in a double loop. The outer loop refers to the paragraphs of the text. The inner loop processes the paragraph portions in these
The Structure of Text Documents paragraphs. The example code modifies the content in each of these paragraph portions using the String property of the string. as is the case in the previous example for paragraphs. Since however, the paragraph portions are edited directly, their formatting information is retained when replacing the string.
80
Formatting
There are various ways of formatting text. The easiest way is to assign the format properties directly to the text sequence. This is called direct formatting. Direct formatting is used in particular with short documents because the formats can be assigned by the user with the mouse. You can, for example, highlight a certain word within a text using bold type or center a line. In addition to direct formatting, you can also format text using templates. This is called indirect formatting. With indirect formatting, the user assigns a pre-defined template to the relevant text portion. If the layout of the text is changed at a later date, the user only needs to change the template. OpenOffice.org then changes the way in which all text portions which use this template are depicted.
In VBA, the formatting properties of an object are usually spread over a range of sub-objects (for example, Range.Font, Range.Borders, Range.Shading, Range.ParagraphFormat). The properties are accessed by means of cascading expressions (for example, Range.Font.AllCaps). In OpenOffice.org Basic, the formatting properties on the other hand are available directly, using the relevant objects (TextCursor, Paragraph, and so on). You will find an overview of the character and paragraph properties available in OpenOffice.org in the following two sections.
The formatting properties can be found in each object (Paragraph, TextCursor, and so on) and can be applied directly.
Character Properties
Those format properties that refer to individual characters are described as character properties. These include bold type and the font type. Objects that allow character properties to be set have to support the com.sun.star.style.CharacterProperties service. OpenOffice.org recognizes a whole range of services that support this service. These include the previously described com.sun.star.text.Paragraph services for paragraphs as well as the com.sun.star.text.TextPortion services for paragraph portions. The com.sun.star.style.CharacterProperties
The Structure of Text Documents service does not provide any interfaces, but instead offers a range of properties through which character properties can be defined and called. A complete list of all character properties can be found in the OpenOffice.org API reference. The following list describes the most important properties: CharFontName (String) name of font type selected. CharColor (Long) text color. CharHeight (Float) character height in points (pt). CharUnderline (Constant group) type of underscore (constants in accordance with com.sun.star.awt.FontUnderline ). CharWeight (Constant group) font weight (constants in accordance with com.sun.star.awt.FontWeight ). CharBackColor (Long) background color. CharKeepTogether (Boolean) suppression of automatic line break. CharStyleName (String) name of character template.
81
Paragraph Properties
Formatting information that does not refer to individual characters, but to the entire paragraph is considered to be a paragraph property. This includes the distance of the paragraph from the edge of the page as well as line spacing. The paragraph properties are available through the com.sun.star.style.ParagraphProperties service. Even the paragraph properties are available in various objects. All objects that support the com.sun.star.text.Paragraph service also provide support for the paragraph properties in com.sun.star.style.ParagraphProperties .
The Structure of Text Documents A complete list of the paragraph properties can be found in the OpenOffice.org API reference. The most common paragraph properties are: ParaAdjust (enum) vertical text orientation (constants in accordance with com.sun.star.style.ParagraphAdjust ). ParaLineSpacing (struct) line spacing (structure in accordance with com.sun.star.style.LineSpacing ). ParaBackColor (Long) background color. ParaLeftMargin (Long) left margin in 100ths of a millimeter. ParaRightMargin (Long) right margin in 100ths of a millimeter. ParaTopMargin (Long) top margin in 100ths of a millimeter. ParaBottomMargin (Long) bottom margin in 100ths of a millimeter. ParaTabStops (Array of struct) type and position of tabs (array with structures of the Typs com.sun.star.style.TabStop ). ParaStyleName (String) name of the paragraph template.
82
83
Filename = "c:\text.html" FileNo = Freefile Open Filename For Output As #FileNo Print #FileNo, "<HTML><BODY>" Doc = StarDesktop.CurrentComponent Enum1 = Doc.Text.createEnumeration ' loop over all paragraphs While Enum1.hasMoreElements TextElement = Enum1.nextElement If TextElement.supportsService("com.sun.star.text.Paragraph") Then Enum2 = TextElement.createEnumeration CurLine = "" ' loop over all paragraph portions While Enum2.hasMoreElements TextPortion = Enum2.nextElement If TextPortion.CharWeight = com.sun.star.awt.FontWeight.BOLD THEN CurLine = CurLine & "<B>" & TextPortion.String & "</B>" Else CurLine = CurLine & TextPortion.String End If Wend ' output the line CurLine = CurLine & "" Print #FileNo, CurLine End If Wend ' write HTML footer
The Structure of Text Documents Print #FileNo, "</BODY></HTML>" Close #FileNo The basic structure of the example is oriented towards the examples for running though the paragraph portions of a text already discussed previously. The functions for writing the HTML file, as well as a test code that checks the font weight of the corresponding text portions and provides paragraph portions in bold type with a corresponding HTML tag, have been added.
84
Doc = StarDesktop.CurrentComponent Enum1 = Doc.Text.createEnumeration ' loop over all paragraphs While Enum1.hasMoreElements
The Structure of Text Documents TextElement = Enum1.nextElement If TextElement.supportsService("com.sun.star.text.Paragraph") Then Enum2 = TextElement.createEnumeration ' loop over all paragraph portions While Enum2.hasMoreElements TextPortion = Enum2.nextElement If TextPortion.CharWeight = _ com.sun.star.awt.FontWeight.BOLD AND _ TextPortion.getPropertyState("CharWeight") = _ com.sun.star.beans.PropertyState.DIRECT_VALUE Then TextPortion.setPropertyToDefault("CharWeight") TextPortion.CharStyleName = "MyBold" End If Wend End If Wend
85
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Structure_ of_ Text_ Documents&oldid=91518 Principle Authors: Ccornell, Fpe, TJFrazier
86
The TextCursor
A TextCursor in the OpenOffice.org API is comparable with the visible cursor used in a OpenOffice.org document. It marks a certain point within a text document and can be navigated in various directions through the use of commands. The TextCursor objects available in OpenOffice.org Basic should not, however, be confused with the visible cursor. These are two very different things.
Terminology differs from that used in VBA: In terms of scope of function, the Range object from VBA can be compared with the TextCursor object in OpenOffice.org and not as the name possibly suggests with the Range object in OpenOffice.org.
The TextCursor object in OpenOffice.org, for example, provides methods for navigating and changing text which are included in the Range object in VBA (for example, MoveStart, MoveEnd, InsertBefore, InsertAfter). The corresponding counterparts of the TextCursor object in OpenOffice.org are described in the following sections.
Editing Text Documents Here are the central methods that the com.sun.star.text.TextCursor service provides for navigation: goLeft (Count, Expand) jumps Count characters to the left. goRight (Count, Expand) jumps Count characters to the right. gotoStart (Expand) jumps to the start of the text document. gotoEnd (Expand) jumps to the end of the text document. gotoRange (TextRange, Expand) jumps to the specified TextRange-Object. gotoStartOfWord (Expand) jumps to the start of the current word. gotoEndOfWord (Expand) jumps to the end of the current word. gotoNextWord (Expand) jumps to the start of the next word. gotoPreviousWord (Expand) jumps to the start of the previous word. isStartOfWord () returns True if the TextCursor is at the start of a word. isEndOfWord () returns True if the TextCursor is at the end of a word. gotoStartOfSentence (Expand) jumps to the start of the current sentence. gotoEndOfSentence (Expand) jumps to the end of the current sentence. gotoNextSentence (Expand) jumps to the start of the next sentence. gotoPreviousSentence (Expand) jumps to the start of the previous sentence. isStartOfSentence () returns True if the TextCursor is at the start of a sentence. isEndOfSentence () returns True if the TextCursor is at the end of a sentence. gotoStartOfParagraph (Expand) jumps to the start of the current paragraph.
87
Editing Text Documents gotoEndOfParagraph (Expand) jumps to the end of the current paragraph. gotoNextParagraph (Expand) jumps to the start of the next paragraph. gotoPreviousParagraph (Expand) jumps to the start of the previous paragraph. isStartOfParagraph () returns True if the TextCursor is at the start of a paragraph. isEndOfParagraph () returns True if the TextCursor is at the end of a paragraph. The text is divided into sentences on the basis of sentence symbols. Periods are, for example, interpreted as symbols indicating the end of sentences. The Expand parameter is a Boolean value which specifies whether the area passed over during navigation is to be highlighted. All navigation methods furthermore return a parameter which specifies whether the navigation was successful or whether the action was terminated for lack of text. The following is a list of several methods for editing highlighted areas using a TextCursor and which also support the com.sun.star.text.TextCursor service: collapseToStart () resets the highlighting and positions the TextCursor at the start of the previously highlighted area. collapseToEnd () resets the highlighting and positions the TextCursor at the end of the previously highlighted area. isCollapsed () returns True if the TextCursor does not cover any highlighting at present.
88
89
Doc = StarDesktop.CurrentComponent Cursor = Doc.Text.createTextCursor Do Cursor.gotoEndOfWord(True) Cursor.CharWeight = com.sun.star.awt.FontWeight.BOLD Proceed = Cursor.gotoNextSentence(False) Cursor.gotoNextWord(False) Loop While Proceed The example first creates a document object for the text that has just been opened. Then it iterates through the entire text, sentence by sentence, and highlights each of the first words and formats this in bold.
Editing Text Documents Cursor.gotoNextWord(False) Loop While Proceed If the TextCursor contains a highlighted area, an assignment to the String property replaces this with the new text. If there is no highlighted area, the text is inserted at the present TextCursor position.
90
91
Editing Text Documents SearchSimilarityExchange (Short) number of characters which may be replaced as part of a similarity search. SearchSimilarityRemove (Short) number of characters which may be removed as part of a similarity search. SearchSimilarityRelax (Boolean) takes all deviation rules into consideration at the same time for the search expression. Once the SearchDescriptor has been prepared as requested, it can be applied to the text document. The OpenOffice.org documents provide the findFirst and findNext methods for this purpose: Found = Doc.findFirst (SearchDesc) Do While Found ' Suchergebnis bearbeiten Found = Doc.findNext( Found.End, Search) Loop The example finds all matches in a loop and returns a TextRange object, which refers to the found text passage.
92
93
The basic idea of search and replace in OpenOffice.org is comparable to that used in VBA. Both interfaces provide you with an object, through which the properties for searching and replacing can be defined. This object is then applied to the required text area in order to perform the action. Whereas the responsible auxiliary object in VBA can be reached through the Find property of the Range object, in OpenOffice.org Basic it is created by the createSearchDescriptor or createReplaceDescriptor call of the document object. Even the search properties and methods available differ.
As in the old API from OpenOffice.org, searching and replacing text in the new API is also performed using the document object. Whereas previously there was an object called SearchSettings especially for defining the search options, in the new object searches are now performed using a SearchDescriptor or ReplaceDescriptor object for automatically replacing text. These objects cover not only the options, but also the current search text and, if necessary, the associated text replacement. The descriptor objects are created using the document object, completed in accordance with the relevant requests, and then transferred back to the document object as parameters for the search methods.
BritishWords() = Array("colour", "neighbour", "centre", "behaviour", _ "metre", "through") USWords() = Array("color", "neighbor", "center", "behavior", _ "meter", "thru") Doc = StarDesktop.CurrentComponent Replace = Doc.createReplaceDescriptor For O = 0 To 5 Replace.SearchString = BritishWords(I) Replace.ReplaceString = USWords(I) Doc.replaceAll(Replace)
Editing Text Documents Next n The expressions for searching and replacing are set using the SearchString and ReplaceString properties of the ReplaceDescriptors. The actual replacement process is finally implemented using the replaceAll method of the document object, which replaces all occurrences of the search expression.
94
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Editing_ Text_ Documents&oldid=91519 Principle Authors: Fpe, Ccornell
95
96
Tables
The following example creates a table with the help of the createInstance method described previously. Dim Doc As Object Dim Table As Object Dim Cursor As Object Doc = StarDesktop.CurrentComponent Cursor = Doc.Text.createTextCursor() Table = Doc.createInstance("com.sun.star.text.TextTable") Table.initialize(5, 4) Doc.Text.insertTextContent(Cursor, Table, False) Python samples: def inset_img(): # abstract the objects in varialbes, doc, text and img, note we used the XSCRIPTCONTEXT doc = XSCRIPTCONTEXT.getDocument() text = doc.getText() cursor = text.createTextCursor() # not sure Table = doc.createInstance(u'com.sun.star.text.TextTable') # Verify code Table.initialize(5, 4) #inser the image in the text area location text.insertTextContent(text.getEnd(), Table, False) Once created, the table is set to the number of rows and columns requested using an initialize call and then inserted in the text document using insertTextContent. As can be seen in the example, the insertTextContent method expects not only the Content object to be inserted, but two other parameters: a Cursor object which determines the insert position a Boolean variable which specifies whether the Content object is to replace the current selection of the cursor (True value) or is to be inserted before the current selection in the text (False)
When creating and inserting tables in a text document, objects similar to those available in VBA are used in OpenOffice.org Basic: The document object and a TextCursor object in OpenOffice.org Basic or the Range object as the VBA counterpart. Whereas the Document.Tables.Add method takes on the task of creating and setting the table in VBA, this is created in OpenOffice.org Basic in accordance with the previous example using createInstance, initialized and inserted in the document through insertTextContent.
More Than Just Text The tables inserted in a text document can be determined using a simple loop. The method of the getTextTables() of the text document object is used for this purpose: Dim Doc As Object Dim TextTables As Object Dim Table As Object Dim I As Integer Doc = StarDesktop.CurrentComponent TextTables = Doc.getTextTables() For I = 0 to TextTables.count - 1 Table = TextTables(I) ' Editing table Next I
97
Text tables are available in OpenOffice.org through the TextTables list of the document object. The previous example shows how a text table can be created. The options for accessing text tables are described in the following section.
Editing Tables
A table consists of individual rows. These in turn contain the various cells. Strictly speaking, there are no table columns in OpenOffice.org. These are produced implicitly by arranging the rows (one under another) next to one another. To simplify access to the tables, OpenOffice.org, however, provides some methods which operate using columns. These are useful if no cells have been merged in the table. Let us first take the properties of the table itself. These are defined in the com.sun.star.text.TextTable service. Here is an list of the most important properties of the table object: BackColor (Long) background color of table. BottomMargin (Long) bottom margin in 100ths of a millimeter. LeftMargin (Long) left margin in 100ths of a millimeter. RightMargin (Long) right margin in 100ths of a millimeter. TopMargin (Long) top margin in 100ths of a millimeter. RepeatHeadline (Boolean) table header is repeated on every page. Width (Long)
More Than Just Text absolute width of the table in 100ths of a millimeter.
98
Rows
A table consists of a list containing rows. The following example shows how the rows of a table can be retrieved and formatted. Dim Dim Dim Dim Dim Dim Doc As Object Table As Object Cursor As Object Rows As Object Row As Object I As Integer
Doc = StarDesktop.CurrentComponent Cursor = Doc.Text.createTextCursor() Table = Doc.createInstance("com.sun.star.text.TextTable") Table.initialize(5, 4) Doc.Text.insertTextContent(Cursor, Table, False) Rows = Table.getRows For I = 0 To Rows.getCount() - 1 Row = Rows.getByIndex(I) Row.BackColor = &HFF00FF Next The example first creates a list containing all rows using a Table.getRows call. The getCount and getByIndex methods allow the list to be further processed and belongs to the com.sun.star.table.XtableRows interface. The getByIndex method returns a row object, which supports the com.sun.star.text.TextTableRow service. Here are the central methods of the com.sun.star.table.XtableRows interface: getByIndex(Integer) returns a row object for the specified index. getCount() returns the number of row objects. insertByIndex(Index, Count) inserts Count rows in the table as of the Index position. removeByIndex(Index, Count) deletes Count rows from the table as of the Index position.
More Than Just Text Whereas the getByIndex and getCount methods are available in all tables, the insertByIndex and removeByIndex methods can only be used in tables that do not contain merged cells. The com.sun.star.text.TextTableRow service provides the following properties: BackColor (Long) background color of row. Height (Long) height of line in 100ths of a millimeter. IsAutoHeight (Boolean) table height is dynamically adapted to the content. VertOrient (const) vertical orientation of the text frame details on vertical orientation of the text within the table (values in accordance with com.sun.star.text.VertOrientation )
99
Columns
Columns are accessed in the same way as rows, using the getByIndex, getCount, insertByIndex, and removeByIndex methods on the Column object, which is reached through getColumns. They can, however, only be used in tables that do not contain merged table cells. Cells cannot be formatted by column in OpenOffice.org Basic. To do so, the method of formatting individual table cells must be used.
Cells
Each cell of a OpenOffice.org document has a unique name. If the cursor of OpenOffice.org is in a cell, then the name of that cell can be seen in the status bar. The top left cell is usually called A1 and the bottom right row is usually called Xn, where X stands for the letters of the top column and n for the numbers of the last row. The cell objects are available through the getCellByName() method of the table object. The following example shows a loop that passes through all the cells of a table and enters the corresponding row and column numbers into the cells. Dim Dim Dim Dim Dim Dim Dim Dim Doc As Object Table As Object Cursor As Object Rows As Object RowIndex As Integer Cols As Object ColIndex As Integer CellName As String
More Than Just Text Dim Cell As Object Doc = StarDesktop.CurrentComponent Cursor = Doc.Text.createTextCursor() Table = Doc.createInstance("com.sun.star.text.TextTable") Table.initialize(5, 4) Doc.Text.insertTextContent(Cursor, Table, False) Rows = Table.getRows Cols = Table.getColumns For RowIndex = 1 To Rows.getCount() For ColIndex = 1 To Cols.getCount() CellName = Chr(64 + ColIndex) & RowIndex Cell = Table.getCellByName(CellName) Cell.String = "row: " & CStr(RowIndex) + ", column: " & CStr(ColIndex) Next Next A table cell is comparable with a standard text. It supports the createTextCursor interface for creating an associated TextCursor object. CellCursor = Cell.createTextCursor() All formatting options for individual characters and paragraphs are therefore automatically available. The following example searches through all tables of a text document and applies the right-align format to all cells with numerical values by means of the corresponding paragraph property. Dim Dim Dim Dim Dim Dim Dim Dim Doc As Object TextTables As Object Table As Object CellNames Cell As Object CellCursor As Object I As Integer J As Integer
100
Doc = StarDesktop.CurrentComponent TextTables = Doc.getTextTables() For I = 0 to TextTables.count - 1 Table = TextTables(I) CellNames = Table.getCellNames()
101
For J = 0 to UBound(CellNames) Cell = Table.getCellByName(CellNames(J)) If IsNumeric(Cell.String) Then CellCursor = Cell.createTextCursor() CellCursor.paraAdjust = com.sun.star.style.ParagraphAdjust.RIGHT End If Next Next The example creates a TextTables list containing all tables of a text that are traversed in a loop. OpenOffice.org then creates a list of the associated cell names for each of these tables. There are passed through in turn in a loop. If a cell contains a numerical value, then the example changes the formatting correspondingly. To do this, it first creates a TextCursor object which makes reference to the content of the table cell and then adapts the paragraph properties of the table cell.
Text Frames
Text frames are considered to be TextContent objects, just like tables and graphs. They may essentially consist of standard text, but can be placed at any position on a page and are not included in the text flow. As with all TextContent objects, a distinction is also made with text frames between the actual creation and insertion in the document. Dim Dim Dim Dim Doc As Object TextTables As Object Cursor As Object Frame As Object
Doc = StarDesktop.CurrentComponent Cursor = Doc.Text.createTextCursor() Frame = Doc.createInstance("com.sun.star.text.TextFrame") Doc.Text.insertTextContent(Cursor, Frame, False) The text frame is created using the createInstance method of the document object. The text frame created in this way can then be inserted in the document using the insertTextContent method of the Text object. In so doing, the name of the proper com.sun.star.text.TextFrame service should be specified. The text frame's insert position is determined by a Cursor object, which is also executed when inserted.
Text frames are OpenOffice.org's counterpart to the position frame used in Word. Whereas VBA uses the Document.Frames.Add method for this purpose, creation in VBA is performed using the previous procedure with the aid of a TextCursor as well as the createInstance method of the document object.
More Than Just Text Text frame objects provide a range of properties with which the position and behavior of the frame can be influenced. The majority of these properties are defined in the com.sun.star.text.BaseFrameProperties service, which is also supported by each TextFrame service. The central properties are: BackColor (Long) background color of the text frame. BottomMargin (Long) bottom margin in 100ths of a millimeter. LeftMargin (Long) left margin in 100ths of a millimeter. RightMargin (Long) right margin in 100ths of a millimeter. TopMargin (Long) top margin in 100ths of a millimeter. Height (Long) height of text frame in 100ths of a millimeter. Width (Long) width of text frame in 100ths of a millimeter. HoriOrient (const) horizontal orientation of text frame (in accordance with com.sun.star.text.HoriOrientation ). VertOrient (const) vertical orientation of text frame (in accordance with com.sun.star.text.VertOrientation ). The following example creates a text frame using the properties described previously: Dim Dim Dim Dim Doc As Object TextTables As Object Cursor As Object Frame As Object
102
Doc = StarDesktop.CurrentComponent Cursor = Doc.Text.createTextCursor() Cursor.gotoNextWord(False) Frame = Doc.createInstance("com.sun.star.text.TextFrame") Frame.Width = 3000 Frame.Height = 1000
More Than Just Text Frame.AnchorType = com.sun.star.text.TextContentAnchorType.AS_CHARACTER Frame.TopMargin = 0 Frame.BottomMargin = 0 Frame.LeftMargin = 0 Frame.RightMargin = 0 Frame.BorderDistance = 0 Frame.HoriOrient = com.sun.star.text.HoriOrientation.NONE Frame.VertOrient = com.sun.star.text.VertOrientation.LINE_TOP Doc.Text.insertTextContent(Cursor, Frame, False) The example creates a TextCursor as the insertion mark for the text frame. This is positioned between the first and second word of the text. The text frame is created using Doc.createInstance. The properties of the text frame objects are set to the starting values required. The interaction between the AnchorType (from the TextContent Service) and VertOrient (from the BaseFrameProperties Service) properties should be noted here. AnchorType receives the AS_CHARACTER value. The text frame is therefore inserted directly in the text flow and behaves like a character. It can, for example, be moved into the next line if a line break occurs. The LINE_TOP value of the VertOrient property ensures that the upper edge of the text frame is at the same height as the upper edge of the character. Once initialization is complete, the text frame is finally inserted in the text document using a call from insertTextContent. To edit the content of a text frame, the user uses the TextCursor, which has already been mentioned numerous times and is also available for text frames. Dim Dim Dim Dim Dim Doc As Object TextTables As Object Cursor As Object Frame As Object FrameCursor As Object
103
Doc = StarDesktop.CurrentComponent Cursor = Doc.Text.createTextCursor() Frame = Doc.createInstance("com.sun.star.text.TextFrame") Frame.Width = 3000 Frame.Height = 1000 Doc.Text.insertTextContent(Cursor, Frame, False) FrameCursor = Frame.createTextCursor() FrameCursor.charWeight = com.sun.star.awt.FontWeight.BOLD FrameCursor.paraAdjust = com.sun.star.style.ParagraphAdjust.CENTER FrameCursor.String = "This is a small Test!"
More Than Just Text The example creates a text frame, inserts this in the current document and opens a TextCursor for the text frame. This cursor is used to set the frame font to bold type and to set the paragraph orientation to centered. The text frame is finally assigned the This is a small test! string.
104
Text Fields
Text fields are TextContent objects because they provide additional logic extending beyond pure text. Text fields can be inserted in a text document using the same methods as those used for other TextContent objects: Dim Doc As Object Dim DateTimeField As Object Dim Cursor As Object Doc = StarDesktop.CurrentComponent Cursor = Doc.Text.createTextCursor() DateTimeField = Doc.createInstance("com.sun.star.text.TextField.DateTime") DateTimeField.IsFixed = False DateTimeField.IsDate = True Doc.Text.insertTextContent(Cursor, DateTimeField, False) The example inserts a text field with the current date at the start of the current text document. The True value of the IsDate property results in only the date and not time being displayed. The False value for IsFixed ensures that the date is automatically updated when the document is opened.
While the type of a field in VBA is specified by a parameter of the Document.Fields.Add method, the name of the service that is responsible for the field type in question defines it in OpenOffice.org Basic.
In the past, text fields were accessed using a whole range of methods that OpenOffice.org made available in the old Selection object (for example InsertField, DeleteUserField, SetCurField). In OpenOffice.org 2.x, the fields are administered using an object-oriented concept. To create a text field, a text field of the type required should first be created and initialized using the properties required. The text field is then inserted in the document using the insertTextContent method. A corresponding source text can be seen in the previous example. The most important field types and their properties are described in the following sections. In addition to inserting text fields, searching a document for the fields can also be an important task. The following example shows how all text fields of a text document can be traversed in a loop and checked for their relevant type. Dim Dim Dim Dim Doc As Object TextFieldEnum As Object TextField As Object I As Integer
More Than Just Text Doc = StarDesktop.CurrentComponent TextFieldEnum = Doc.getTextFields.createEnumeration While TextFieldEnum.hasMoreElements() TextField = TextFieldEnum.nextElement() If TextField.supportsService("com.sun.star.text.TextField.DateTime") Then MsgBox "Date/time" ElseIf TextField.supportsService("com.sun.star.text.TextField.Annotation") Then MsgBox "Annotation" Else MsgBox "unknown" End If Wend The starting point for establishing the text fields present is the TextFields list of the document object. The example creates an Enumeration object on the basis of this list, with which all text fields can be queried in turn in a loop. The text fields found are checked for the service supported using the supportsService method. If the field proves to be a date/time field or an annotation, then the corresponding field type is displayed in an information box. If on the other hand, the example encounters another field, then it displays the information unknown. Below, you will find a list of the most important text fields and their associated properties. A complete list of all text fields is provided in the API reference in the com.sun.star.text.TextField module. (When listing the service name of a text field, uppercase and lowercase characters should be used in OpenOffice.org Basic, as in the previous example.)
105
More Than Just Text return the number of pages, words, or characters of a text. They support the following property: NumberingType (const) numbering format (guidelines in accordance with constants from com.sun.star.style.NumberingType ).
106
Current Page
The number of the current page can be inserted in a document using the com.sun.star.text.TextField.PageNumber text field. The following properties can be specified: NumberingType (const) number format (guidelines in accordance with constants from com.sun.star.style.NumberingType ). Offset (short) offset added to the number of pages (negative specification also possible). The following example shows how the number of pages can be inserted into the footer of a document. Dim Dim Dim Dim Dim Dim Doc As Object DateTimeField As Object PageStyles As Object StdPage As Object FooterCursor As Object PageNumber As Object
Doc = StarDesktop.CurrentComponent PageNumber = Doc.createInstance("com.sun.star.text.TextField.PageNumber") PageNumber.NumberingType = com.sun.star.style.NumberingType.ARABIC PageStyles = Doc.StyleFamilies.getByName("PageStyles") StdPage = PageStyles("Default") StdPage.FooterIsOn = True FooterCursor = StdPage.FooterTextLeft.Text.createTextCursor() StdPage.FooterTextLeft.Text.insertTextContent(FooterCursor, PageNumber, False)
More Than Just Text The example first creates a text field which supports the com.sun.star.text.TextField.PageNumber service. Since the header and footer lines are defined as part of the page templates of OpenOffice.org, this is initially established using the list of all PageStyles. To ensure that the footer line is visible, the FooterIsOn property is set to True. The text field is then inserted in the document using the associated text object of the left-hand footer line.
107
Annotations
Annotation fields ( com.sun.star.text.TextField.Annotation ) can be seen by means of a small yellow symbol in the text. Clicking on this symbol opens a text field, in which a comment on the current point in the text can be recorded. An annotation field has the following properties. Author (String) name of author. Content (String) comment text. Date (Date) date on which annotation is written.
Date /Time
A date / time field ( com.sun.star.text.TextField.DateTime ) represents the current date or the current time. It supports the following properties: IsFixed (Boolean) if True, the time details of the insertion remain unchanged, if False, these are updated each time the document is opened. IsDate (Boolean) if True, the field displays the current date, otherwise the current time. DateTimeValue (struct) current content of field ( com.sun.star.util.DateTime structure) NumberFormat (const) format in which the time or date is depicted.
108
Bookmarks
Bookmarks (Service com.sun.star.text.Bookmark ) are TextContent objects. Bookmarks are created and inserted using the concept already described previously: Dim Doc As Object Dim Bookmark As Object Dim Cursor As Object Doc = StarDesktop.CurrentComponent Cursor = Doc.Text.createTextCursor() Bookmark = Doc.createInstance("com.sun.star.text.Bookmark") Bookmark.Name = "My bookmarks" Doc.Text.insertTextContent(Cursor, Bookmark, True) The example creates a Cursor, which marks the insert position of the bookmark and then the actual bookmark object (Bookmark). The bookmark is then assigned a name and is inserted in the document through insertTextContent at the cursor position. The bookmarks of a text are accessed through a list called Bookmarks. The bookmarks can either be accessed by their number or their name. The following example shows how a bookmark can be found within a text, and a text inserted at its position. Dim Doc As Object Dim Bookmark As Object Dim Cursor As Object
109
Doc = StarDesktop.CurrentComponent Bookmark = Doc.Bookmarks.getByName("My bookmarks") Cursor = Doc.Text.createTextCursorByRange(Bookmark.Anchor) Cursor.String = "Here is the bookmark" In this example, the getByName method is used to find the bookmark required by means of its name. The createTextCursorByRange call then creates a Cursor, which is positioned at the anchor position of the bookmark. The cursor then inserts the text required at this point. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ More_ Than_ Text&oldid=91527 Principle Authors: Ccornell, Fpe, JZA, Timarandras
110
Spreadsheet Documents
Spreadsheet Documents
OpenOffice.org Basic provides an extensive interface for program-controlled creation and editing of spreadsheets. This chapter describes how to control the relevant services, methods and properties of spreadsheet documents: The Structure of Spreadsheets Editing Spreadsheet Documents The first section addresses the basic structure of spreadsheet documents and shows you how to access and to edit the contents of individual cells. The second section concentrates on how to edit spreadsheets efficiently by focusing on cell areas and the options for searching and replacing cell contents.
The Range object allows you to address any table area and has been extended in the new API.
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Spreadsheets&oldid=91528 Principle Authors: Fpe
111
Spreadsheets
You can access the individual sheets of a spreadsheet document through the Sheets list. The following examples show you how to access a sheet either through its number or its name. Example 1: access by means of the number (numbering begins with 0) Dim Doc As Object Dim Sheet As Object Doc = StarDesktop.CurrentComponent Sheet = Doc.Sheets (0) Example 2: access by means of the name Dim Doc As Object Dim Sheet As Object Doc = StarDesktop.CurrentComponent Sheet = Doc.Sheets.getByName("Sheet 1") In the first example, the sheet is accessed by its number (counting begins at 0). In the second example, the sheet is accessed by its name and the getByName method. The Sheet object that is obtained by the getByName method supports the com.sun.star.sheet.Spreadsheet service. In addition to providing several interfaces for editing the content, this service provides the following properties: IsVisible (Boolean) the spreadsheet is visible. PageStyle (String) name of the page template for the spreadsheet.
The Structure of Spreadsheets If Doc.Sheets.hasByName("MySheet") Then Sheet = Doc.Sheets.getByName("MySheet") Else Sheet = Doc.createInstance("com.sun.star.sheet.Spreadsheet") Doc.Sheets.insertByName("MySheet", Sheet) End If The getByName and insertByName methods are from the com.sun.star.container.XnameContainer interface as described in Introduction to the API. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Structure_ of_ Spreadsheets&oldid=91530 Principle Authors: Fpe, Ccornell, Sheanhoxie
112
Doc = StarDesktop.CurrentComponent Sheet = Doc.Sheets(0) FirstCol = Sheet.Columns(0) FirstRow = Sheet.Rows(0) The column objects support the com.sun.star.table.TableColumn service that has the following properties: Width (long)
Rows and Columns width of a column in hundredths of a millimeter. OptimalWidth (Boolean) sets a column to its optimum width. IsVisible (Boolean) displays a column. IsStartOfNewPage (Boolean) when printing, creates a page break before a column. The width of a column is only optimized when the OptimalWidth property is set to True. If the width of an individual cell is changed, the width of the column that contains the cell is not changed. In terms of functionality, OptimalWidth is more of a method than a property. The row objects are based on the com.sun.star.table.RowColumn service that has the following properties: Height (long) height of the row in 100ths of a millimeter. OptimalHeight (Boolean) sets the row to its optimum height. IsVisible (Boolean) displays the row. IsStartOfNewPage (Boolean) when printing, creates a page break before the row. If the OptimalHeight property of a row is set to the True, the row height changes automatically when the height of a cell in the row is changed. Automatic optimization continues until the row is assigned an absolute height through the Height property. The following example activates the automatic height optimization for the first five rows in the sheet and makes the second column invisible. Dim Dim Dim Dim Dim Doc As Object Sheet As Object Row As Object Col As Object I As Integer
113
Doc = StarDesktop.CurrentComponent Sheet = Doc.Sheets(0) For I = 0 To 4 Row = Sheet.Rows(I) Row.OptimalHeight = True Next I Col = Sheet.Columns(1) Col.IsVisible = False
114
The Rows and Columns lists can be accessed through an index in OpenOffice.org Basic. Unlike in VBA, the first column has the index 0 and not the index 1.
115
StarDesktop.CurrentComponent returns the current component. If you are working in the BASIC IDE when you run the macro, then the BASIC IDE is returned. A RunTime error is generated because the BASIC IDE does not have a spreadsheet component. Save the example code and run the macro from a spreadsheet document. See StarDesktop for more information.
In addition to numerical coordinates, each cell in a sheet has a name, for example, the top left cell (0,0) of a spreadsheet is called A1. The letter A stands for the column and the number 1 for the row. It is important that the name and position of a cell are not confused because row counting for names begins with 1 but the counting for position begins with 0. In OpenOffice.org, a table cell can be empty or contain text, numbers, or formulas. The cell type is not determined by the content that is saved in the cell, but rather the object property which was used for its entry. Numbers can be inserted and called up with the Value property, text with the String property, and formulas with the Formula property. Dim Doc As Object Dim Sheet As Object Dim Cell As Object Doc = StarDesktop.CurrentComponent Sheet = Doc.Sheets(0) Cell = Sheet.getCellByPosition(0, 0) Cell.Value = 100 Cell = Sheet.getCellByPosition(0, 1) Cell.String = "Test" Cell = Sheet.getCellByPosition(0, 2) Cell.Formula = "=A1" The example inserts one number, one text, and one formula in the fields A1 to A3.
The Value, String, and Formula properties supersede the PutCell method for setting the values of a table cell.
OpenOffice.org treats cell content that is entered using the String property as text, even if the content is a number. Numbers are left-aligned in the cell instead of right-aligned. You should also note the difference between text and numbers when you use formulas: Dim Doc As Object Dim Sheet As Object Dim Cell As Object Doc = StarDesktop.CurrentComponent Sheet = Doc.Sheets(0) Cell = Sheet.getCellByPosition(0, 0) Cell.Value = 100
116
Cell = Sheet.getCellByPosition(0, 1) Cell.String = 1000 Cell = Sheet.getCellByPosition(0, 2) Cell.Formula = "=A1+A2" MsgBox Cell.Value Although cell A1 contains the value 100 and cell A2 contains the value 1000, the A1+A2 formula returns the value 100. This is because the contents of cell A2 were entered as a string and not as a number. To check if the contents of a cell contains a number or a string, use the Type property: Dim Doc As Object Dim Sheet As Object Dim Cell As Object Doc = StarDesktop.CurrentComponent Sheet = Doc.Sheets(0) Cell = Sheet.getCellByPosition(1,1) Cell.Value = 1000 Select Case Cell.Type Case com.sun.star.table.CellContentType.EMPTY MsgBox "Content: Empty" Case com.sun.star.table.CellContentType.VALUE MsgBox "Content: Value" Case com.sun.star.table.CellContentType.TEXT MsgBox "Content: Text" Case com.sun.star.table.CellContentType.FORMULA MsgBox "Content: Formula" End Select The Cell.Type property returns a value for the com.sun.star.table.CellContentType enumeration which identifies the contents type of a cell. The possible values are: EMPTY no value VALUE number TEXT strings FORMULA
117
Cells and Ranges The completed CellRangeAddress structure must be passed as the first parameter to the insertCells method. The second parameter of insertCells contains a value of the com.sun.star.sheet.CellInsertMode enumeration and defines what is to be done with the values that are located in front of the insert position. The CellInsertMode enumeration recognizes the following values: NONE the current values remain in their present position. DOWN the cells at and under the insert position are moved downwards. RIGHT the cells at and to the right of the insert position are moved to the right. ROWS the rows after the insert position are moved downwards. COLUMNS the columns after the insert position are moved to the right. The removeRange method is the counterpart to the insertCells method. This method deletes the range that is defined in the CellRangeAddress structure from the sheet. Dim Doc As Object Dim Sheet As Object Dim CellRangeAddress As New com.sun.star.table.CellRangeAddress Doc = StarDesktop.CurrentComponent Sheet = Doc.Sheets(0) CellRangeAddress.Sheet = 0 CellRangeAddress.StartColumn = 1 CellRangeAddress.StartRow = 1 CellRangeAddress.EndColumn = 2 CellRangeAddress.EndRow = 2 Sheet.removeRange(CellRangeAddress, com.sun.star.sheet.CellDeleteMode.UP) This example removes the B2:C3 cell range from the sheet and then shifts the underlying cells up by two rows. The type of removal is defined by one of the following values from the com.sun.star.sheet.CellDeleteMode enumeration: NONE the current values remain in their current position. UP the cells at and below the insert position are moved upwards.
118
Cells and Ranges LEFT the cells at and to the right of the insert position are moved to the left. ROWS the rows after the insert position are moved upwards. COLUMNS the columns after the insert position are moved to the left. The XRangeMovement interface provides two additional methods for moving (moveRange) or copying (copyRange) cell ranges. The following example moves the B2:C3 range so that the range starts at position A6: Dim Dim Dim Dim Doc As Object Sheet As Object CellRangeAddress As New com.sun.star.table.CellRangeAddress CellAddress As New com.sun.star.table.CellAddress
119
Doc = StarDesktop.CurrentComponent Sheet = Doc.Sheets(0) CellRangeAddress.Sheet = 0 CellRangeAddress.StartColumn = 1 CellRangeAddress.StartRow = 1 CellRangeAddress.EndColumn = 2 CellRangeAddress.EndRow = 2 CellAddress.Sheet = 0 CellAddress.Column = 0 CellAddress.Row = 5 Sheet.moveRange(CellAddress, CellRangeAddress) In addition to the CellRangeAdress structure, the moveRange method expects a com.sun.star.table.CellAddress structure to define the origin of the move's target region. The CellAddress method provides the following values: Sheet (short) number of the spreadsheet (numbering begins with 0). Column (long) number of the addressed column (numbering begins with 0). Row (long) number of the addressed row (numbering begins with 0). The cell contents in the target range are always overwritten by the moveRange method. Unlike in the InsertCells method , a parameter for performing automatic moves is not provided in the removeRange method.
Cells and Ranges The copyRange method functions in the same way as the moveRange method, except that copyRange inserts a copy of the cell range instead of moving it.
In terms of their function, the OpenOffice.org Basic insertCell, removeRange, and copyRange methods are comparable with the VBA Range.Insert, Range.Delete ,and Range.Copy methods. Whereas in VBA, the methods are applied to the corresponding Range object, in OpenOffice.org Basic they are applied to the associated Sheet object.
120
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Cells_ and_ Ranges&oldid=91532 Principle Authors: Ccornell, Fpe
Cell Properties
There are numerous options for formatting cells, such as specifying the font type and size for text. Each cell supports the com.sun.star.style.CharacterProperties and com.sun.star.style.ParagraphProperties services, the main properties of which are described in Text Documents. Special cell formatting is handled by the com.sun.star.table.CellProperties service. The main properties of this service are described in the following sections. You can apply all of the named properties to individual cells and to cell ranges.
The CellProperties object in the OpenOffice.org API is comparable with the Interior object from VBA which also defines cell-specific properties.
Formatting Spreadsheet Documents ShadowFormat (struct) specifies the shadow for cells (structure in accordance with com.sun.star.table.ShadowFormat ) The com.sun.star.table.ShadowFormat structure and the detailed specifications for cell shadows have the following structure: Location (enum) position of shadow (value from the com.sun.star.table.ShadowLocation structure). ShadowWidth (Short) size of shadow in hundredths of a millimeter IsTransparent (Boolean) sets the shadow to transparent Color (Long) color of shadow The following example writes the number 1000 to the B2 cell, changes the background color to red using the CellBackColor property, and then creates a light gray shadow for the cell that is moved 1 mm to the left and down. Dim Dim Dim Dim Doc As Object Sheet As Object Cell As Object ShadowFormat As New com.sun.star.table.ShadowFormat
121
Doc = StarDesktop.CurrentComponent Sheet = Doc.Sheets(0) Cell = Sheet.getCellByPosition(1,1) Cell.Value = 1000 Cell.CellBackColor = RGB(255, 0, 0) ShadowFormat.Location = com.sun.star.table.ShadowLocation.BOTTOM_RIGHT ShadowFormat.ShadowWidth = 100 ShadowFormat.Color = RGB(160, 160, 160) Cell.ShadowFormat = ShadowFormat
122
Justification
OpenOffice.org provides various functions that allow you to change the justification of a text in a table cell. The following properties define the horizontal and vertical justification of a text: HoriJustify (enum) horizontal justification of the text (value from com.sun.star.table.CellHoriJustify ) VertJustify (enum) vertical justification of the text (value from com.sun.star.table.CellVertJustify ) Orientation (enum) orientation of text (value in accordance with com.sun.star.table.CellOrientation ) IsTextWrapped (Boolean) permits automatic line breaks within the cell RotateAngle (Long) angle of rotation of text in hundredths of a degree The following example shows how you can "stack" the contents of a cell so that the individual characters are printed one under another in the top left corner of the cell. The characters are not rotated. Dim Doc As Object Dim Sheet As Object Dim Cell As Object Doc = StarDesktop.CurrentComponent Sheet = Doc.Sheets(0) Cell = Sheet.getCellByPosition(1,1) Cell.Value = 1000 Cell.HoriJustify = com.sun.star.table.CellHoriJustify.LEFT Cell.VertJustify = com.sun.star.table.CellVertJustify.TOP Cell.Orientation = com.sun.star.table.CellOrientation.STACKED
123
Doc = StarDesktop.CurrentComponent Sheet = Doc.Sheets(0) Cell = Sheet.getCellByPosition(1,1) Cell.Value = 23400.3523565 LocalSettings.Language = "en" LocalSettings.Country = "us" NumberFormats = Doc.NumberFormats NumberFormatString = "#,##0.000" NumberFormatId = NumberFormats.queryKey(NumberFormatString, LocalSettings, True) If NumberFormatId = -1 Then NumberFormatId = NumberFormats.addNew(NumberFormatString, LocalSettings) End If MsgBox NumberFormatId Cell.NumberFormat = NumberFormatId
Formatting Spreadsheet Documents The Format Cells dialog in OpenOffice.org Calc provides an overview of the different formatting options for cells.
124
Page Properties
Page properties are the formatting options that position document content on a page as well as visual elements that are repeated page after page. These include Paper formats Page margins Headers and footers. The procedure for defining page formats differs from other forms of formatting. Whereas cell, paragraph, and character elements can be formatted directly, page formats can also be defined and indirectly applied using page styles. For example, headers or footers are added to the page style. The following sections describe the main formatting options for spreadsheet pages. Many of the styles that are described are also available for text documents. The page properties that are valid for both types of documents are defined in the com.sun.star.style.PageProperties service. The page properties that only apply to spreadsheet documents are defined in the com.sun.star.sheet.TablePageStyle service.
The page properties (page margins, borders, and so on) for a Microsoft Office document are defined by means of a PageSetup object at the Worksheet object (Excel) or Document object (Word) level. In OpenOffice.org, these properties are defined using a page style which in turn is linked to the associated document.
Page Background
The com.sun.star.style.PageProperties service defines the following properties of a pages background: BackColor (long) color of background BackGraphicURL (String) URL of the background graphics that you want to use BackGraphicFilter (String) name of the filter for interpreting the background graphics BackGraphicLocation (Enum) position of the background graphics (value according to enumeration) BackTransparent (Boolean) makes the background transparent
125
Page Format
The page format is defined using the following properties of the com.sun.star.style.PageProperties service: IsLandscape (Boolean) landscape format Width (long) width of page in hundredths of a millimeter Height (long) height of page in hundredths of a millimeter PrinterPaperTray (String) name of the printer paper tray that you want to use The following example sets the page size of the "Default" page style to the DIN A5 landscape format (height 14.8 cm, width 21 cm): Dim Dim Dim Dim Dim Doc As Object Sheet As Object StyleFamilies As Object PageStyles As Object DefPage As Object
Doc = StarDesktop.CurrentComponent StyleFamilies = Doc.StyleFamilies PageStyles = StyleFamilies.getByName("PageStyles") DefPage = PageStyles.getByName("Default") DefPage.IsLandscape = True DefPage.Width = 21000 DefPage.Height = 14800
Formatting Spreadsheet Documents BottomMargin (long) width of the bottom page margin in hundredths of a millimeter LeftBorder (struct) specifications for left-hand line of page border (com.sun.star.table.BorderLine structure) RightBorder (struct) specifications for right-hand line of page border ( com.sun.star.table.BorderLine structure) TopBorder (struct) specifications for top line of page border ( com.sun.star.table.BorderLine structure) BottomBorder (struct) specifications for bottom line of page border ( com.sun.star.table.BorderLine structure) LeftBorderDistance (long) distance between left-hand page border and page content in hundredths of a millimeter RightBorderDistance (long) distance between right-hand page border and page content in hundredths of a millimeter TopBorderDistance (long) distance between top page border and page content in hundredths of a millimeter BottomBorderDistance (long) distance between bottom page border and page content in hundredths of a millimeter ShadowFormat (struct) specifications for shadow of content area of page ( com.sun.star.table.ShadowFormat structure) The following example sets the left and right-hand borders of the "Default" page style to 1 centimeter. Dim Doc As Object Dim Sheet As Object
126
Formatting Spreadsheet Documents Dim StyleFamilies As Object Dim PageStyles As Object Dim DefPage As Object Doc = StarDesktop.CurrentComponent StyleFamilies = Doc.StyleFamilies PageStyles = StyleFamilies.getByName("PageStyles") DefPage = PageStyles.getByName("Default") DefPage.LeftMargin = 1000 DefPage.RightMargin = 1000
127
Formatting Spreadsheet Documents com.sun.star.table.BorderLine structure) HeaderBottomBorder (struct) details of the bottom line of the border around header ( com.sun.star.table.BorderLine structure) HeaderLeftBorderDistance (long) distance between left-hand border and content of header in hundredths of a millimeter HeaderRightBorderDistance (long) distance between right-hand border and content of header in hundredths of a millimeter HeaderTopBorderDistance (long) distance between top border and content of header in hundredths of a millimeter HeaderBottomBorderDistance (long) distance between bottom border and content of header in hundredths of a millimeter HeaderIsShared (Boolean) headers on even and odd pages have the same content (refer to HeaderText , HeaderTextLeft, and HeaderTextRight ) HeaderBackColor (long) background color of header HeaderBackGraphicURL (String) URL of the background graphics that you want to use HeaderBackGraphicFilter (String) name of the filter for interpreting the background graphics for the header HeaderBackGraphicLocation (Enum) position of the background graphics for the header (value according to com.sun.star.style.GraphicLocation enumeration) HeaderBackTransparent (Boolean) shows the background of the header as transparent HeaderShadowFormat (struct) details of shadow of header ( com.sun.star.table.ShadowFormat structure) The properties for formatting footers are: FooterIsOn (Boolean) footer is activated
128
Formatting Spreadsheet Documents FooterLeftMargin (long) distance between footer and left-hand page margin in hundredths of a millimeter FooterRightMargin (long) distance between footer and right-hand page margin in hundredths of a millimeter FooterBodyDistance (long) distance between footer and main body of document in hundredths of a millimeter FooterHeight (long) height of footer in hundredths of a millimeter FooterIsDynamicHeight (Boolean) height of footer is adapted automatically to the content FooterLeftBorder (struct) details of left-hand line of border around footer ( com.sun.star.table.BorderLine structure) FooterRightBorder (struct) details of right-hand line of border around footer ( com.sun.star.table.BorderLine structure) FooterTopBorder (struct) details of top line of border around footer ( com.sun.star.table.BorderLine structure) FooterBottomBorder (struct) details of bottom line of border around footer ( com.sun.star.table.BorderLine structure) FooterLeftBorderDistance (long) distance between left-hand border and content of footer in hundredths of a millimeter FooterRightBorderDistance (long) distance between right-hand border and content of footer in hundredths of a millimeter FooterTopBorderDistance (long) distance between top border and content of footer in hundredths of a millimeter FooterBottomBorderDistance (long) distance between bottom border and content of footer in hundredths of a millimeter FooterIsShared (Boolean)
129
Formatting Spreadsheet Documents the footers on the even and odd pages have the same content (refer to FooterText, FooterTextLeft, and FooterTextRight ) FooterBackColor (long) background color of footer FooterBackGraphicURL (String) URL of the background graphics that you want to use FooterBackGraphicFilter (String) name of the filter for interpreting the background graphics for the footer FooterBackGraphicLocation (Enum) position of background graphics for the footer (value according to com.sun.star.style.GraphicLocation enumeration) FooterBackTransparent (Boolean) shows the background of the footer as transparent FooterShadowFormat (struct) details of shadow of footer ( com.sun.star.table.ShadowFormat structure)
130
Formatting Spreadsheet Documents com.sun.star.sheet.HeaderFooterContent service) If you do not need to distinguish between headers or footers for odd and even pages (the FooterIsShared property is False), then set the properties for headers and footers on odd pages. All the named objects return an object that supports the com.sun.star.sheet.HeaderFooterContent service. By means of the (non-genuine) properties LeftText, CenterText, and RightText, this service provides three text elements for the headers and footers of OpenOffice.org Calc. The following example writes the "Just a Test." value in the left-hand text field of the header from the "Default" template. Dim Doc As Object Dim Sheet As Object Dim StyleFamilies As Object Dim PageStyles As Object Dim DefPage As Object Dim HText As Object Dim HContent As Object Doc = StarDesktop.CurrentComponent StyleFamilies = Doc.StyleFamilies PageStyles = StyleFamilies.getByName("PageStyles") DefPage = PageStyles.getByName("Default") DefPage.HeaderIsOn = True HContent = DefPage.RightPageHeaderContent HText = HContent.LeftText HText.String = "Just a Test." DefPage.RightPageHeaderContent = HContent Note the last line in the example: Once the text is changed, the TextContent object must be assigned to the header again so that the change is effective. Another mechanism for changing the text of headers and footers is available for text documents (OpenOffice.org Writer) because these consist of a single block of text. The following properties are defined in the com.sun.star.style.PageProperties service: HeaderText (Object) text object with content of the header ( com.sun.star.text.XText service)
131
Formatting Spreadsheet Documents HeaderTextLeft (Object) text object with content of headers on left-hand pages ( com.sun.star.text.XText service) HeaderTextRight (Object) text object with content of headers on right-hand pages ( com.sun.star.text.XText service) FooterText (Object) text object with content of the footer ( com.sun.star.text.XText service) FooterTextLeft (Object) text object with content of footers on left-hand pages ( com.sun.star.text.XText service) FooterTextRight (Object) text object with content of footers on right-hand pages ( com.sun.star.text.XText service) The following example creates a header in the "Default" page style for text documents and adds the text "Just a Test" to the header. Dim Dim Dim Dim Dim Dim Doc As Object Sheet As Object StyleFamilies As Object PageStyles As Object DefPage As Object HText As Object
132
Doc = StarDesktop.CurrentComponent StyleFamilies = Doc.StyleFamilies PageStyles = StyleFamilies.getByName("PageStyles") DefPage = PageStyles.getByName("Default") DefPage.HeaderIsOn = True HText = DefPage.HeaderText HText.String = "Just a Test."
Formatting Spreadsheet Documents In this instance, access is provided directly through the HeaderText property of the page style rather than the HeaderFooterContent object.
133
Formatting Spreadsheet Documents Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Formatting_ Spreadsheet_ Documents&oldid=91537 Principle Authors: Ccornell, Fpe, TJFrazier
134
Cell Ranges
In addition to an object for individual cells ( com.sun.star.table.Cell service), OpenOffice.org also provides objects that represent cell ranges. Such CellRange objects are created using the getCellRangeByName call of the spreadsheet object: Dim Doc As Object Dim Sheet As Object Dim CellRange As Object Doc = StarDesktop.CurrentComponent Sheet = Doc.Sheets.getByName("Sheet 1") CellRange = Sheet.getCellRangeByName("A1:C15") A colon (:) is used to specify a cell range in a spreadsheet document. For example, A1:C15 represents all the cells in rows 1 to 15 in columns A, B, and C. The location of individual cells in a cell range can be determined using the getCellByPosition method, where the coordinates of the top left cell in the cell range is (0, 0). The following example uses this method to create an object of cell C3. Dim Dim Dim Dim Doc As Object Sheet As Object CellRange As Object Cell As Object
135
136
Doc = StarDesktop.CurrentComponent Sheet = Doc.Sheets(0) CellRange = Sheet.getCellRangeByName("B2:C3") Flags = com.sun.star.sheet.CellFlags.STRING + _ com.sun.star.sheet.CellFlags.HARDATTR CellRange.clearContents(Flags) The flags specified in clearContents come from the com.sun.star.sheet.CellFlags constants list. This list provides the following elements: VALUE numerical values that are not formatted as date or time DATETIME numerical values that are formatted as date or time STRING strings ANNOTATION comments that are linked to cells FORMULA formulas HARDATTR direct formatting of cells
Editing Spreadsheet Documents STYLES indirect formatting OBJECTS drawing objects that are connected to cells EDITATTR character formatting that only applies to parts of the cells You can also add the constants together to delete different information using a call from clearContents.
137
Doc = StarDesktop.CurrentComponent Sheet = Doc.Sheets(0) ReplaceDescriptor = Sheet.createReplaceDescriptor() ReplaceDescriptor.SearchString = "is" ReplaceDescriptor.ReplaceString = "was" For I = 0 to Doc.Sheets.Count - 1 Sheet = Doc.Sheets(I) Sheet.ReplaceAll(ReplaceDescriptor) Next I This example uses the first page of the document to create a ReplaceDescriptor and then applies this to all pages in a loop. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Editing_ Spreadsheet_ Documents&oldid=91538 Principle Authors: Ccornell, Fpe, TJFrazier
138
Pages
The pages of a drawing document are available through the DrawPages list. You can access individual pages either through their number or their name. If a document has one page and this is called Slide 1, then the following examples are identical. Example 1: Dim Doc As Object Dim Page As Object Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) Example 2: Dim Doc As Object Dim Page As Object Doc = StarDesktop.CurrentComponent Page = Doc.drawPages.getByName("Slide 1")
The Structure of Drawings In Example 1, the page is addressed by its number (counting begins at 0). In the second example, the page is accessed by its name and the getByName method. Dim sUrl As String, sFilter As String Dim sOptions As String Dim oSheets As Object, oSheet As Object oSheets = oDocument.Sheets If oSheets.hasByName("Link") Then oSheet = oSheets.getByName("Link") Else oSheet = oDocument.createInstance("com.sun.star.sheet.Spreadsheet") oSheets.insertByName("Link", oSheet) oSheet.IsVisible = False End If The preceding call returns a page object that supports the com.sun.star.drawing.DrawPage service. The service recognizes the following properties: BorderLeft (Long) left-hand border in hundredths of a millimeter BorderRight (Long) right-hand border in hundredths of a millimeter BorderTop (Long) top border in hundredths of a millimeter BorderBottom (Long) bottom border in hundredths of a millimeter Width (Long) page width in hundredths of a millimeter Height (Long) page height in hundredths of a millimeter Number (Short) number of pages (numbering begins at 1), read-only Orientation (Enum) page orientation (in accordance with com.sun.star.view.PaperOrientation enumeration) If these settings are changed, then all of the pages in the document are affected. The following example sets the page size of a drawing document which has just been opened to 20 x 20 centimeters with a page margin of 0.5 centimeters: Dim Doc As Object Dim Page As Object Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0)
139
140
Page.BorderLeft = 500 Page.BorderRight = 500 Page.BorderTop = 500 Page.BorderBottom = 500 Page.Width = 20000 Page.Height = 20000
Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) Point.x = 1000 Point.y = 1000 Size.Width = 10000 Size.Height = 10000 RectangleShape = Doc.createInstance("com.sun.star.drawing.RectangleShape") RectangleShape.Size = Size RectangleShape.Position = Point Page.add(RectangleShape) This example uses the StarDesktop.CurrentComponent call to determine which document is open. The document object determined this way returns the first page of the drawing through the drawPages(0) call. The Point and Size structures with the point of origin (left hand corner) and the size of the drawing object are then initialized. The lengths are specified in hundredths of a millimeter.
The Structure of Drawings The program code then uses the Doc.createInstance call to create the rectangle drawing object as specified by the com.sun.star.drawing.RectangleShape service. At the end, the drawing object is assigned to a page using a Page.add call.
141
Fill Properties
This section describes four services and in each instance the sample program code uses a rectangle shape element that combines several types of formatting. Fill properties are combined in the com.sun.star.drawing.FillProperties service. OpenOffice.org recognizes four main types of formatting for a fill area. The simplest variant is a single-color fill. The options for defining color gradients and hatches let you create other colors into play. The fourth variant is the option of projecting existing graphics into the fill area. The fill mode of a drawing object is defined using the FillStyle property. The permissible values are defined in com.sun.star.drawing.FillStyle .
Point.x = 1000 Point.y = 1000 Size.Width = 10000 Size.Height = 10000 Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) RectangleShape =
The Structure of Drawings Doc.createInstance("com.sun.star.drawing.RectangleShape") RectangleShape.Size = Size RectangleShape.Position = Point RectangleShape.FillStyle = com.sun.star.drawing.FillStyle.SOLID RectangleShape.FillColor = RGB(255,0,0) Page.add(RectangleShape)
142
Color Gradient
If you set the FillStyle property to GRADIENT, you can apply a color gradient to any fill area of a OpenOffice.org document. If you want to apply a predefined color gradient, you can assign the associated name of the FillTransparenceGradientName property. To define your own color gradient, you need to complete a com.sun.star.awt.Gradient structure to assign the FillGradient property. This property provides the following options: Style (Enum) type of gradient, for example, linear or radial (default values in accordance with com.sun.star.awt.GradientStyle ) StartColor (Long) start color of color gradient EndColor (Long) end color of color gradient Angle (Short) angle of color gradient in tenths of a degree XOffset (Short) X-coordinate at which the color gradient starts, specified in hundredths of a millimeter YOffset (Short) Y-coordinate at which the color gradient begins, specified in hundredths of a millimeter StartIntensity (Short) intensity of StartColor as a percentage (in OpenOffice.org Basic, you can also specify values higher than 100 percent) EndIntensity (Short) intensity of EndColor as a percentage (in OpenOffice.org Basic, you can also specify values higher than 100 percent) StepCount (Short)
The Structure of Drawings number of color graduations which OpenOffice.org is to calculate for the gradients The following example demonstrates the use of color gradients with the aid of the com.sun.star.awt.Gradient structure: Dim Dim Dim Dim Dim Dim Doc As Object Page As Object RectangleShape As Object Point As New com.sun.star.awt.Point Size As New com.sun.star.awt.Size Gradient As New com.sun.star.awt.Gradient
143
Point.x = 1000 Point.y = 1000 Size.Width = 10000 Size.Height = 10000 Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) RectangleShape = Doc.createInstance("com.sun.star.drawing.RectangleShape") RectangleShape.Size = Size RectangleShape.Position = Point Gradient.Style = com.sun.star.awt.GradientStyle.LINEAR Gradient.StartColor = RGB(255,0,0) Gradient.EndColor = RGB(0,255,0) Gradient.StartIntensity = 150 Gradient.EndIntensity = 150 Gradient.Angle = 450 Gradient.StepCount = 100 RectangleShape.FillStyle = com.sun.star.drawing.FillStyle.GRADIENT RectangleShape.FillGradient = Gradient Page.add(RectangleShape) This example creates a linear color gradient (Style = LINEAR). The gradient starts with red (StartColor) in the top left corner, and extends at a 45 degree angle (Angle) to green (EndColor) in the bottom right corner. The color intensity of the start and end colors is 150 percent (StartIntensity and EndIntensity) which results in the colors seeming brighter than the values specified in the StartColor and EndColor properties. The color gradient is depicted using a hundred graduated individual colors (StepCount).
144
Hatches
To create a hatch fill, the FillStyle property must be set to HATCH. The program code for defining the hatch is very similar to the code for color gradients. Again an auxiliary structure, in this case com.sun.star.drawing.Hatch , is used to define the appearance of hatches. The structure for hatches has the following properties: Style (Enum) type of hatch: simple, squared, or squared with diagonals (default values in accordance with com.sun.star.awt.HatchStyle) Color (Long) color of lines Distance (Long) distance between lines in hundredths of a millimeter Angle (Short) angle of hatch in tenths of a degree The following example demonstrates the use of a hatch structure: Dim Dim Dim Dim Dim Dim Doc As Object Page As Object RectangleShape As Object Point As New com.sun.star.awt.Point Size As New com.sun.star.awt.Size Hatch As New com.sun.star.drawing.Hatch
Point.x = 1000 Point.y = 1000 Size.Width = 10000 Size.Height = 10000 Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) RectangleShape = Doc.createInstance("com.sun.star.drawing.RectangleShape") RectangleShape.Size = Size RectangleShape.Position = Point RectangleShape.FillStyle = com.sun.star.drawing.FillStyle.HATCH Hatch.Style = com.sun.star.drawing.HatchStyle.SINGLE Hatch.Color = RGB(64,64,64) Hatch.Distance = 20 Hatch.Angle = 450
145
RectangleShape.FillHatch = Hatch Page.add(RectangleShape) This code creates a simple hatch structure (HatchStyle = SINGLE) whose lines are rotated 45 degrees (Angle). The lines are dark gray (Color) and are spaced is 0.2 millimeters (Distance) apart.
Bitmaps
To use bitmap projection as a fill, you must set the FillStyle property to BITMAP. If the bitmap is already available in OpenOffice.org, you just need to specify its name in the FillBitMapName property and its display style (simple, tiled, or elongated) in the FillBitmapMode property (default values in accordance with com.sun.star.drawing.BitmapMode ). If you want to use an external bitmap file, you can specify its URL in the FillBitmapURL property. The following example creates a rectangle and tiles the Sky bitmap that is available in OpenOffice.org to fill the area of the rectangle: Dim Dim Dim Dim Dim Doc As Object Page As Object RectangleShape As Object Point As New com.sun.star.awt.Point Size As New com.sun.star.awt.Size
Point.x = 1000 Point.y = 1000 Size.Width = 10000 Size.Height = 10000 Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) RectangleShape = Doc.createInstance("com.sun.star.drawing.RectangleShape") RectangleShape.Size = Size RectangleShape.Position = Point RectangleShape.FillStyle = com.sun.star.drawing.FillStyle.BITMAP RectangleShape.FillBitmapName = "Sky" RectangleShape.FillBitmapMode = com.sun.star.drawing.BitmapMode.REPEAT Page.add(RectangleShape)
146
Transparency
You can adjust the transparency of any fill that you apply. The simplest way to change the transparency of a drawing element is to use the FillTransparence property. The following example creates a red rectangle with a transparency of 50 percent. Dim Dim Dim Dim Dim Doc As Object Page As Object RectangleShape As Object Point As New com.sun.star.awt.Point Size As New com.sun.star.awt.Size
Point.x = 1000 Point.y = 1000 Size.Width = 10000 Size.Height = 10000 Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) RectangleShape = Doc.createInstance("com.sun.star.drawing.RectangleShape") RectangleShape.Size = Size RectangleShape.Position = Point RectangleShape.FillStyle = com.sun.star.drawing.FillStyle.SOLID RectangleShape.FillTransparence = 50 RectangleShape.FillColor = RGB(255,0,0) Page.add(RectangleShape) To make the fill transparent, set the FillTransparence property to 100. In addition to the FillTransparence property, the com.sun.star.drawing.FillProperties service also provides the FillTransparenceGradient property. This is used to define a gradient that specifies the transparency of a fill area.
Line Properties
All drawing objects that can have a border line support the com.sun.star.drawing.LineStyle service. Some of the properties that this service provides are: LineStyle (Enum) line type (default values in accordance with com.sun.star.drawing.LineStyle
The Structure of Drawings ) LineColor (Long) line color LineTransparence (Short) line transparency LineWidth (Long) line thickness in hundredths of a millimeter LineJoint (Enum) transitions to connection points (default values in accordance with com.sun.star.drawing.LineJoint ) The following example creates a rectangle with a solid border (LineStyle = SOLID) that is 5 millimeters thick (LineWidth) and 50 percent transparent. The right and left-hand edges of the line extend to their points of intersect with each other (LineJoint = MITER) to form a right-angle. Dim Dim Dim Dim Dim Doc As Object Page As Object RectangleShape As Object Point As New com.sun.star.awt.Point Size As New com.sun.star.awt.Size
147
Point.x = 1000 Point.y = 1000 Size.Width = 10000 Size.Height = 10000 Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) RectangleShape = Doc.createInstance("com.sun.star.drawing.RectangleShape") RectangleShape.Size = Size RectangleShape.Position = Point RectangleShape.LineColor = RGB(128,128,128) RectangleShape.LineTransparence = 50 RectangleShape.LineWidth = 500 RectangleShape.LineJoint = com.sun.star.drawing.LineJoint.MITER RectangleShape.LineStyle = com.sun.star.drawing.LineStyle.SOLID Page.add(RectangleShape) In addition to the listed properties, the
The Structure of Drawings com.sun.star.drawing.LineStyle service provides options for drawing dotted and dashed lines. For more information, see the OpenOffice.org API reference.
148
The Structure of Drawings service to format the text font. The text can only be inserted after the drawing object has been added to the drawing page. You can also use the com.sun.star.drawing.Text service to position and format text in drawing object. The following are some of the important properties of this service: TextAutoGrowHeight (Boolean) adapts the height of the drawing element to the text it contains TextAutoGrowWidth (Boolean) adapts the width of the drawing element to the text it contains TextHorizontalAdjust (Enum) horizontal position of text within the drawing element (default values in accordance with com.sun.star.drawing.TextHorizontalAdjust ) TextVerticalAdjust (Enum) vertical position of text within the drawing element (default values in accordance with com.sun.star.drawing.TextVerticalAdjust ) TextLeftDistance (Long) left-hand distance between drawing element and text in hundredths of a millimeter TextRightDistance (Long) right-hand distance between drawing element and text in hundredths of a millimeter TextUpperDistance (Long) upper distance between drawing element and text in hundredths of a millimeter TextLowerDistance (Long) lower distance between drawing element and text in hundredths of a millimeter The following example demonstrates use of the named properties. Dim Dim Dim Dim Dim Doc As Object Page As Object RectangleShape As Object Point As New com.sun.star.awt.Point Size As New com.sun.star.awt.Size
149
The Structure of Drawings Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) RectangleShape = Doc.createInstance("com.sun.star.drawing.RectangleShape") RectangleShape.Size = Size RectangleShape.Position = Point Page.add(RectangleShape) RectangleShape.String = "This is a test" ' May only take place after Page.add! RectangleShape.TextVerticalAdjust = com.sun.star.drawing.TextVerticalAdjust.TOP RectangleShape.TextHorizontalAdjust = com.sun.star.drawing.TextHorizontalAdjust.LEFT RectangleShape.TextLeftDistance = 300 RectangleShape.TextRightDistance = 300 RectangleShape.TextUpperDistance = 300 RectangleShape.TextLowerDistance = 300 This code inserts a drawing element in a page and then adds text to the top left corner of the drawing object using the TextVerticalAdjust and TextHorizontalAdjust properties. The minimum distance between the text edge of the drawing object is set to three millimeters.
150
Shadow Properties
You can add a shadow to most drawing objects with the com.sun.star.drawing.ShadowProperties service. The properties of this service are: Shadow (Boolean) activates the shadow ShadowColor (Long) shadow color ShadowTransparence (Short) transparency of the shadow ShadowXDistance (Long) vertical distance of the shadow from the drawing object in hundredths of a millimeter ShadowYDistance (Long) horizontal distance of the shadow from the drawing object in hundredths of a millimeter
The Structure of Drawings The following example creates a rectangle with a shadow that is vertically and horizontally offset from the rectangle by 2 millimeters. The shadow is rendered in dark gray with 50 percent transparency. Dim Dim Dim Dim Dim Doc As Object Page As Object RectangleShape As Object Point As New com.sun.star.awt.Point Size As New com.sun.star.awt.Size
151
Point.x = 1000 Point.y = 1000 Size.Width = 10000 Size.Height = 10000 Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) RectangleShape = Doc.createInstance("com.sun.star.drawing.RectangleShape") RectangleShape.Size = Size RectangleShape.Position = Point RectangleShape.Shadow = True RectangleShape.ShadowColor = RGB(192,192,192) RectangleShape.ShadowTransparence = 50 RectangleShape.ShadowXDistance = 200 RectangleShape.ShadowYDistance = 200 Page.add(RectangleShape)
The Structure of Drawings com.sun.star.drawing.Text (with com.sun.star.style.CharacterProperties and com.sun.star.style.ParagraphProperties ) Shadow properties com.sun.star.drawing.ShadowProperties CornerRadius (Long) radius for rounding corners in hundredths of a millimeter
152
The Structure of Drawings com.sun.star.drawing.CircleKind ) CircleStartAngle (Long) start angle in tenths of a degree (only for circle or ellipse segments) CircleEndAngle (Long) end angle in tenths of a degree (only for circle or ellipse segments) The CircleKind property determines if an object is a complete circle, a circular slice, or a section of a circle. The following values are available: full circle or full ellipse section of circle (partial circle whose interfaces are linked directly to one another) circle slice angle (not including circle line) The following example creates a circular slice with a 70 degree angle (produced from difference between start angle of 20 degrees and end angle of 90 degrees) Dim Dim Dim Dim Dim Doc As Object Page As Object EllipseShape As Object Point As New com.sun.star.awt.Point Size As New com.sun.star.awt.Size
153
Point.x = 1000 Point.y = 1000 Size.Width = 10000 Size.Height = 10000 Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) EllipseShape = Doc.createInstance("com.sun.star.drawing.EllipseShape") EllipseShape.Size = Size EllipseShape.Position = Point EllipseShape.CircleStartAngle = 2000 EllipseShape.CircleEndAngle = 9000 EllipseShape.CircleKind = com.sun.star.drawing.CircleKind.SECTION Page.add(EllipseShape)
154
Lines
OpenOffice.org provides the com.sun.star.drawing.LineShape service for line objects. Line objects support all of the general formatting services with the exception of areas. The following are all of the properties that are associated with the LineShape service: Line properties com.sun.star.drawing.LineProperties Text properties com.sun.star.drawing.Text (with com.sun.star.style.CharacterProperties and com.sun.star.style.ParagraphProperties ) Shadow properties com.sun.star.drawing.ShadowProperties The following example creates and formats a line with the help of the named properties. The origin of the line is specified in the Location property, whereas the coordinates listed in the Size property specify the end point of the line. Dim Dim Dim Dim Dim Doc As Object Page As Object LineShape As Object Point As New com.sun.star.awt.Point Size As New com.sun.star.awt.Size
Point.x = 1000 Point.y = 1000 Size.Width = 10000 Size.Height = 10000 Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) LineShape = Doc.createInstance("com.sun.star.drawing.LineShape") LineShape.Size = Size LineShape.Position = Point
155
Polypolygon Shapes
OpenOffice.org also supports complex polygonal shapes through the com.sun.star.drawing.PolyPolygonShape service. Strictly speaking, a PolyPolygon is not a simple polygon but a multiple polygon. Several independent lists containing corner points can therefore be specified and combined to form a complete object. As with rectangle shapes, all the formatting properties of drawing objects are also provided for polypolygons: Fill properties com.sun.star.drawing.FillProperties Line properties com.sun.star.drawing.LineProperties Text properties com.sun.star.drawing.Text (with com.sun.star.style.CharacterProperties and com.sun.star.style.ParagraphProperties ) Shadow properties com.sun.star.drawing.ShadowProperties The PolyPolygonShape service also has a property that lets you define the coordinates of a polygon: PolyPolygon (Array) field containing the coordinates of the polygon (double array with points of the com.sun.star.awt.Point type) The following example shows how you can define a triangle with the PolyPolygonShape service. Dim Doc As Object Dim Page As Object Dim PolyPolygonShape As Object
The Structure of Drawings Dim PolyPolygon As Variant Dim Coordinates(2) As New com.sun.star.awt.Point Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) PolyPolygonShape = Doc.createInstance("com.sun.star.drawing.PolyPolygonShape") Page.add(PolyPolygonShape) ' Page.add must take place before the coordinates are set Coordinates(0).x Coordinates(1).x Coordinates(2).x Coordinates(0).y Coordinates(1).y Coordinates(2).y = = = = = = 1000 7500 10000 1000 7500 5000
156
PolyPolygonShape.PolyPolygon = Array(Coordinates()) Since the points of a polygon are defined as absolute values, you do not need to specify the size or the start position of a polygon. Instead, you need to create an array of the points, package this array in a second array (using the Array(Coordinates() call), and then assign this array to the polygon. Before the corresponding call can be made, the polygon must be inserted into the document. The double array in the definition allows you to create complex shapes by merging several polygons. For example, you can create a rectangle and then insert another rectangle inside it to create a hole in the original rectangle: Dim Dim Dim Dim Dim Dim Dim Doc As Object Page As Object PolyPolygonShape As Object PolyPolygon As Variant Square1(3) As New com.sun.star.awt.Point Square2(3) As New com.sun.star.awt.Point Square3(3) As New com.sun.star.awt.Point
Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) PolyPolygonShape = Doc.createInstance("com.sun.star.drawing.PolyPolygonShape") Page.add(PolyPolygonShape) ' Page.add must take place before the coordinates are set Square1(0).x = 5000 Square1(1).x = 10000
The Structure of Drawings Square1(2).x Square1(3).x Square1(0).y Square1(1).y Square1(2).y Square1(3).y Square2(0).x Square2(1).x Square2(2).x Square2(3).x Square2(0).y Square2(1).y Square2(2).y Square2(3).y Square3(0).x Square3(1).x Square3(2).x Square3(3).x Square3(0).y Square3(1).y Square3(2).y Square3(3).y = = = = = = = = = = = = = = = = = = = = = = 10000 5000 5000 5000 10000 10000 6500 8500 8500 6500 6500 6500 8500 8500 6500 8500 8500 6500 9000 9000 9500 9500
157
PolyPolygonShape.PolyPolygon = Array(Square1(), Square2(), Square3()) With respect as to which areas are filled and which areas are holes, OpenOffice.org applies a simple rule: the edge of the outer shape is always the outer border of the polypolygon. The next line inwards is the inner border of the shape and marks the transition to the first hole. If there is another line inwards, it marks the transition to a filled area.
Graphics
The last of the drawing elements presented here are graphic objects that are based on the com.sun.star.drawing.GraphicObjectShape service. These can be used with any graphic within OpenOffice.org whose appearance can be adapted using a whole range of properties. Graphic objects support two of the general formatting properties: Text properties com.sun.star.drawing.Text (with com.sun.star.style.CharacterProperties and
The Structure of Drawings com.sun.star.style.ParagraphProperties ) Shadow properties com.sun.star.drawing.ShadowProperties Additional properties that are supported by graphic objects are: GraphicURL (String) URL of the graphic AdjustLuminance (Short) luminance of the colors, as a percentage (negative values are also permitted) AdjustContrast (Short) contrast as a percentage (negative values are also permitted) AdjustRed (Short) red value as a percentage (negative values are also permitted) AdjustGreen (Short) green value as a percentage (negative values are also permitted) AdjustBlue (Short) blue value as a percentage (negative values are also permitted) Gamma (Short) gamma value of a graphic Transparency (Short) transparency of a graphic as a percentage GraphicColorMode (enum) color mode, for example, standard, gray stages, black and white (default value in accordance with com.sun.star.drawing.ColorMode ) The following example shows how to insert a page into a graphics object.Dim Doc As Object Dim Dim Dim Dim Page As Object GraphicObjectShape As Object Point As New com.sun.star.awt.Point Size As New com.sun.star.awt.Size ' specifications, insignificant because latter coordinates are binding
158
Doc = StarDesktop.CurrentComponent
The Structure of Drawings Page = Doc.drawPages(0) GraphicObjectShape = Doc.createInstance("com.sun.star.drawing.GraphicObjectShape") GraphicObjectShape.Size = Size GraphicObjectShape.Position = Point GraphicObjectShape.GraphicURL = "file:///c:/test.jpg" GraphicObjectShape.AdjustBlue = -50 GraphicObjectShape.AdjustGreen = 5 GraphicObjectShape.AdjustBlue = 10 GraphicObjectShape.AdjustContrast = 20 GraphicObjectShape.AdjustLuminance = 50 GraphicObjectShape.Transparency = 40 GraphicObjectShape.GraphicColorMode = com.sun.star.drawing.ColorMode.STANDARD Page.add(GraphicObjectShape) This code inserts the test.jpg graphic and adapts its appearance using the Adjust properties. In this example, the graphics are depicted as 40 percent transparent with no other color conversions do not take place (GraphicColorMode = STANDARD). Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Structure_ of_ Drawings&oldid=91544 Principle Authors: Ccornell, Fpe
159
160
Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) Point.x = 3000 Point.y = 3000 Size.Width = 3000 Size.Height = 3000 ' create square drawing element Square = Doc.createInstance("com.sun.star.drawing.RectangleShape") Square.Size = Size Square.Position = Point Square.FillColor = RGB(255,128,128) Page.add(Square) ' create circle drawing element Circle = Doc.createInstance("com.sun.star.drawing.EllipseShape") Circle.Size = Size Circle.Position = Point Circle.FillColor = RGB(255,128,128) Circle.FillColor = RGB(0,255,0) Page.add(Circle) ' combine square and circle drawing elements Shapes = createUnoService("com.sun.star.drawing.ShapeCollection") Shapes.add(Square) Shapes.add(Circle) Group = Page.group(Shapes)
Editing Drawing Objects ' centre combined drawing elements Height = Page.Height Width = Page.Width NewPos.X = Width / 2 NewPos.Y = Height / 2 Height = Group.Size.Height Width = Group.Size.Width NewPos.X = NewPos.X - Width / 2 NewPos.Y = NewPos.Y - Height / 2 Group.Position = NewPos This code creates a rectangle and a circle and inserts them into a page. It then creates an object that supports the com.sun.star.drawing.ShapeCollection service and uses the Add method to add the rectangle and the circle to this object. The ShapeCollection is added to the page using the Group method and returns the actual Group object that can be edited like an individual Shape. If you want to format the individual objects of a group, apply the formatting before you add them to the group. You cannot modify the objects once they are in the group.
161
162
Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) RectangleShape = Doc.createInstance("com.sun.star.drawing.RectangleShape") RectangleShape.Size = Size RectangleShape.Position = Point RectangleShape.RotateAngle = 3000 Page.add(RectangleShape) The next example creates the same rectangle as in the previous example, but instead shears it through 30 degrees using the ShearAngle property. Dim Dim Dim Dim Dim Doc As Object Page As Object RectangleShape As Object Point As New com.sun.star.awt.Point Size As New com.sun.star.awt.Size
Point.x = 1000 Point.y = 1000 Size.Width = 10000 Size.Height = 10000 Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) RectangleShape = Doc.createInstance("com.sun.star.drawing.RectangleShape") RectangleShape.Size = Size RectangleShape.Position = Point RectangleShape.ShearAngle = 3000 Page.add(RectangleShape)
Editing Drawing Objects Dim ReplaceDescriptor As Object Dim I As Integer Doc = StarDesktop.CurrentComponent Page = Doc.drawPages(0) ReplaceDescriptor = Page.createReplaceDescriptor() ReplaceDescriptor.SearchString = "is" ReplaceDescriptor.ReplaceString = "was" For I = 0 to Doc.drawPages.Count - 1 Page = Doc.drawPages(I) Page.ReplaceAll(ReplaceDescriptor) Next I This code uses the first DrawPage of the document to create a ReplaceDescriptor and then applies this descriptor in a loop to all of the pages in the drawing document. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Editing_ Drawing_ Objects&oldid=91545 Principle Authors: Ccornell, Fpe
163
Presentations
OpenOffice.org presentations are based on drawing documents. Each page in the presentation is a slide. You can access slides in the same way as a standard drawing is accessed through the DrawPages list of the document object. The com.sun.star.presentation.PresentationDocument service, responsible for presentation documents, also provides the complete com.sun.star.drawing.DrawingDocument service.
Presentations
164
Presentations the amount of time that a blank screen is displayed at the end of the presentation StartWithNavigator (Boolean) displays the navigator window when the presentation starts UsePn (Boolean) displays the pointer during the presentation Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Presentations&oldid=91546 Principle Authors: Ccornell, Fpe
165
Presentations
166
Charts (Diagrams)
Charts (Diagrams)
OpenOffice.org can display data as a chart, which creates graphical representations of numerical data in the form of bars, pie charts, lines or other elements. Data can either be displayed as 2D or 3D graphics, and the appearance of the chart elements can be individually adapted in a way similar to the process used for drawing elements. Charts are not treated as independent documents in OpenOffice.org, but as objects that are embedded in an existing document. A chart may contain its own data or may display data from the container document. For example charts in spreadsheets can display data obtained from the cell ranges and charts in text documents can display data obtained from writer tables. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Charts&oldid=91547 Principle Authors: Ccornell, Fpe, Iha
167
Doc = StarDesktop.CurrentComponent Charts = Doc.Sheets(0).Charts Rect.X = 8000 Rect.Y = 1000 Rect.Width = 10000 Rect.Height = 7000 RangeAddress(0).Sheet = 0 RangeAddress(0).StartColumn = 0 RangeAddress(0).StartRow = 0 RangeAddress(0).EndColumn = 2 RangeAddress(0).EndRow = 12 Charts.addNewByName("MyChart", Rect, RangeAddress(), True, True) Although the code used in the example may appear to be complex, the central processes are limited to three lines. The first central line creates the Doc document variable, which references the current spreadsheet document (Doc line = StarDesktop.CurrentComponent). The code used in the example then creates a list containing all charts of the first spreadsheet (Charts line = Doc.Sheets(0).Charts). Finally, in the last line, a new chart is added to this list using the addNewByName method. This new chart is then visible to the user. The variable RangeAddress determines the assigned cell range whose data will be displayed within the chart. The variable Rect determines the position and size of the chart within the first sheet in the spreadsheet document. The previous example creates a bar chart. If a different chart type is needed, then the bar chart must be explicitly replaced: Chart = Charts.getByName("MyChart").embeddedObject Chart.Diagram = Chart.createInstance("com.sun.star.chart.LineDiagram") The first line defines the corresponding chart object. The second line replaces the current chart with a new one in this example, a line chart.
168
In Microsoft Excel, a distinction is made between charts which have been inserted as a separate page in a Microsoft Excel document and charts which are embedded in a table page. Correspondingly, two different access methods are defined there for charts. This distinction is not made in OpenOffice.org Basic, because charts in OpenOffice.org Calc are always created as embedded objects of a table page. The charts are always accessed using the Charts list of the associated Sheet object.
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Charts_ in_ Spreadsheets&oldid=91549 Principle Authors: Ccornell, Fpe, Iha
The Structure of Charts Both services com.sun.star.chart.ChartTitle and com.sun.star.chart.ChartLegend do support the service com.sun.star.drawing.Shape. This allows to determine the position and size of the elements using the Position and Size properties. As the size of the legend and the titles is calculated automatically based on the current content and the character height for example, the size property provides read access only. Fill and line properties ( com.sun.star.drawing.FillProperties and com.sun.star.drawing.LineProperties services) as well as the character properties ( com.sun.star.style.CharacterProperties service) are provided for further formatting of the elements. com.sun.star.chart.ChartTitle contains not only the listed formatting properties, but also two other properties: String (String) text which to be displayed as the title or subtitle TextRotation (Long) angle of rotation of text in 100ths of a degree The legend ( com.sun.star.chart.ChartLegend ) contains the following additional property: Alignment (Enum) position at which the legend appears (value of type com.sun.star.chart.ChartLegendPosition ) The following example creates a chart with a title "Main Title String", a subtitle "Subtitle String" and a legend. The legend has a gray background color, is placed at the bottom of the chart, and has a character size of 7 points. Dim Dim Dim Dim Dim Doc As Object Charts As Object Chart as Object Rect As New com.sun.star.awt.Rectangle RangeAddress(0) As New com.sun.star.table.CellRangeAddress
169
The Structure of Charts Rect.Width = 10000 Rect.Height = 7000 RangeAddress(0).Sheet = 0 RangeAddress(0).StartColumn = 0 RangeAddress(0).StartRow = 0 RangeAddress(0).EndColumn = 2 RangeAddress(0).EndRow = 12 Doc = StarDesktop.CurrentComponent Charts = Doc.Sheets(0).Charts Charts.addNewByName("MyChart", Rect, RangeAddress(), True, True) Chart = Charts.getByName("MyChart").EmbeddedObject Chart.HasMainTitle = True Chart.Title.String = "Main Title String" Chart.HasSubTitle = True Chart.Subtitle.String = "Subtitle String" Chart.HasLegend = True Chart.Legend.Alignment = com.sun.star.chart.ChartLegendPosition.BOTTOM Chart.Legend.FillStyle = com.sun.star.drawing.FillStyle.SOLID Chart.Legend.FillColor = RGB(210, 210, 210) Chart.Legend.CharHeight = 7
170
Background
Every chart has a background area. The Chart object provides the property Area to format the background: Area (Object) background area of the chart (supports com.sun.star.chart.ChartArea service) The background of a chart covers its complete area, including the area under the title, subtitle and legend. The associated com.sun.star.chart.ChartArea service supports line and fill properties.
Diagram
The Chart object provides the property Diagram which forms the coordinate system with axes and grids, where the data finally is displayed: Diagram (Object) object forming the coordinate system where the data is plotted. It supports com.sun.star.chart.Diagram
The Structure of Charts service and: com.sun.star.chart.StackableDiagram com.sun.star.chart.ChartAxisXSupplier com.sun.star.chart.ChartAxisYSupplier com.sun.star.chart.ChartAxisZSupplier com.sun.star.chart.ChartTwoAxisXSupplier com.sun.star.chart.ChartTwoAxisYSupplier Different services are supported depending on the chart type (see Chart Types).
171
The Structure of Charts com.sun.star.drawing.LineProperties services, refer to Drawings and Presentations). The following example shows how graphics (named Sky) already contained in OpenOffice.org can be used as a background for a chart. The wall is set to be blue. Dim Dim Dim Dim Dim Doc As Object Charts As Object Chart as Object Rect As New com.sun.star.awt.Rectangle RangeAddress(0) As New com.sun.star.table.CellRangeAddress
172
Rect.X = 8000 Rect.Y = 1000 Rect.Width = 10000 Rect.Height = 7000 RangeAddress(0).Sheet = 0 RangeAddress(0).StartColumn = 0 RangeAddress(0).StartRow = 0 RangeAddress(0).EndColumn = 2 RangeAddress(0).EndRow = 12 Doc = StarDesktop.CurrentComponent Charts = Doc.Sheets(0).Charts Charts.addNewByName("MyChart", Rect, RangeAddress(), True, True) Chart = Charts.getByName("MyChart").EmbeddedObject Chart.Area.FillStyle = com.sun.star.drawing.FillStyle.BITMAP Chart.Area.FillBitmapName = "Sky" Chart.Area.FillBitmapMode = com.sun.star.drawing.BitmapMode.REPEAT Chart.Diagram.Wall.FillStyle = com.sun.star.drawing.FillStyle.SOLID Chart.Diagram.Wall.FillColor = RGB(00,132,209)
Axes
OpenOffice.org recognizes five different axes that can be used in a chart. In the simplest scenario, these are the X and Y-axes. When working with 3D charts, a Z-axis is also sometimes provided. For charts in which the values of the various rows of data deviate significantly from one another, OpenOffice.org provides a second X and Y-axis for second scaling operations. The Diagram object provides the following properties to access the axes: HasXAxis (Boolean) activates the X-axis XAxis (Object) object with detailed information about the X-axis (supports com.sun.star.chart.ChartAxis
The Structure of Charts service) HasXAxisDescription (Boolean) activates the labels for the interval marks for the X-axis HasYAxis (Boolean) activates the Y-axis YAxis (Object) object with detailed information about the Y-axis (supports com.sun.star.chart.ChartAxis service) HasYAxisDescription (Boolean) activates the labels for the interval marks for the Y-axis HasZAxis (Boolean) activates the Z-axis ZAxis (Object) object with detailed information about the Z-axis (supports com.sun.star.chart.ChartAxis service) HasZAxisDescription (Boolean) activates the labels for the interval marks for the Z-axis HasSecondaryXAxis (Boolean) activates the secondary X-axis SecondaryXAxis (Object) object with detailed information about the secondary X-axis (supports com.sun.star.chart.ChartAxis service) HasSecondaryXAxisDescription (Boolean) activates the labels for the interval marks for the secondary X-axis HasSecondaryYAxis (Boolean) activates the secondary Y-axis SecondaryYAxis (Object) object with detailed information about the secondary Y-axis (supports com.sun.star.chart.ChartAxis service) HasSecondaryYAxisDescription (Boolean) activates the labels for the interval marks for the secondary Y-axis
173
174
Properties of Axes
The axis objects of a OpenOffice.org chart support the com.sun.star.chart.ChartAxis service. In addition to the properties for characters (com.sun.star.style.CharacterProperties service, refer to Text Documents) and lines (com.sun.star.drawing.LineStyle service, refer to Drawings and Presentations), it provides the following properties:
Scaling properties:
Max (Double) maximum value for axis Min (Double) minimum value for axis Origin (Double) point of intersect for crossing axes StepMain (Double) distance between the major interval marks StepHelp (Double) distance between the minor interval marks (deprecated since OpenOffice.org 3.0; Use property StepHelpCount instead) StepHelpCount (Long) Contains the number of minor intervals within a major interval. E.g. a StepHelpCount of 5 divides the major interval into 5 pieces and thus produces 4 minor tick marks. (available since OpenOffice.org 3.0) AutoMax (Boolean) the maximum value for the axis is calculated automatically when set to true AutoMin (Boolean) the minimum value for the axis is calculated automatically when set to true AutoOrigin (Boolean) the origin is determines automatically when set to true AutoStepMain (Boolean) StepMain is determines automatically when set to true AutoStepHelp (Boolean) StepHelpCount is determines automatically when set to true Logarithmic (Boolean) scales the axes in logarithmic manner (rather than linear) ReverseDirection (Boolean)
The Structure of Charts determines if the axis orientation is mathematical or reversed. (available since OpenOffice.org 2.4)
175
Label properties:
DisplayLabels (Boolean) activates the text label at the interval marks TextRotation (Long) angle of rotation of text label in 100ths of a degree ArrangeOrder (enum) the label may be staggered, thus they are positioned alternately over two lines (values according to com.sun.star.chart.ChartAxisArrangeOrderType ) TextBreak (Boolean) permits line breaks within the axes labels TextCanOverlap (Boolean) permits an overlap of the axes labels NumberFormat (Long) number format to be used with the axes labels LinkNumberFormatToSource (Boolean) determines whether to use the number format given by the container document, or from the property NumberFormat. (since OpenOffice.org 2.3)
The Structure of Charts percentage which specifies the distance there may be between the different groups of bars of a chart (at 100%, there is a distance corresponding to the width of one bar)
176
Grids
For the primary axes grids and sub grids can be displayed, matching to the major and minor intervals. The Diagram object provides the following properties to access the grids: HasXAxisGrid (Boolean) activates major grid for X-axis XMainGrid (Object) object with detailed information about the major grid for X-axis (supports com.sun.star.chart.ChartGrid service) HasXAxisHelpGrid (Boolean) activates minor grid for X-axis XHelpGrid (Object) object with detailed information about the minor grid for X-axis (supports com.sun.star.chart.ChartGrid service) the same for y and z: HasYAxisGrid (Boolean) activates major grid for Y-axis YMainGrid (Object) object with detailed information about the major grid for Y-axis (supports com.sun.star.chart.ChartGrid service) HasYAxisHelpGrid (Boolean) activates minor grid for Y-axis YHelpGrid (Object) object with detailed information about the minor grid for Y-axis (supports com.sun.star.chart.ChartGrid service) HasZAxisGrid (Boolean) activates major grid for Z-axis ZMainGrid (Object) object with detailed information about the major grid for Z-axis (supports com.sun.star.chart.ChartGrid
The Structure of Charts service) HasZAxisHelpGrid (Boolean) activates minor grid for Z-axis ZHelpGrid (Object) object with detailed information about the minor grid for Z-axis (supports com.sun.star.chart.ChartGrid service) The grid object is based on the com.sun.star.chart.ChartGrid service, which in turn supports the line properties of the com.sun.star.drawing.LineStyle support service (refer to Drawings and Presentations).
177
Axes Title
For all axes an additional title can be displayed. The Diagram object provides the following properties to access the axes title: HasXAxisTitle (Boolean) activates title of X-axis XAxisTitle (Object) object with detailed information about title of the X-axis (supports com.sun.star.chart.ChartTitle service) same y and z: HasYAxisTitle (Boolean) activates title of Y-axis YAxisTitle (Object) object with detailed information about title of the Y-axis (supports com.sun.star.chart.ChartTitle service) HasZAxisTitle (Boolean) activates title of Z-axis ZAxisTitle (Object) object with detailed information about title of the Z-axis (supports com.sun.star.chart.ChartTitle service)
The Structure of Charts and for the secondary axes (available since OpenOffice.org 3.0): HasSecondaryXAxisTitle (Boolean) activates title of the secondary X-axis. SecondXAxisTitle (Object) object with detailed information about title of the secondary X-axis (supports com.sun.star.chart.ChartTitle service) HasSecondaryYAxisTitle (Boolean) activates title of the secondary Y-axis. SecondYAxisTitle (Object) object with detailed information about title of the secondary Y-axis (supports com.sun.star.chart.ChartTitle service) The objects for formatting the axes title are based on the com.sun.star.chart.ChartTitle service, which is also used for chart titles.
178
Example
The following example creates a line chart. The color for the rear wall of the chart is set to white. Both the X and Y-axes have a gray grid for visual orientation. The minimum value of the Y-axis is fixed to 0 and the maximum value is fixed to 100 so that the resolution of the chart is retained even if the values are changed. The X-axis points in reverse direction from right to left. And a title for the X-axis was added. Dim Dim Dim Dim Dim Doc As Object Charts As Object Chart as Object Rect As New com.sun.star.awt.Rectangle RangeAddress(0) As New com.sun.star.table.CellRangeAddress
Doc = StarDesktop.CurrentComponent Charts = Doc.Sheets(0).Charts Rect.X = 8000 Rect.Y = 1000 Rect.Width = 10000 Rect.Height = 7000 RangeAddress(0).Sheet = 0 RangeAddress(0).StartColumn = 0 RangeAddress(0).StartRow = 0 RangeAddress(0).EndColumn = 2
The Structure of Charts RangeAddress(0).EndRow = 12 Charts.addNewByName("MyChart", Rect, RangeAddress(), True, True) Chart = Charts.getByName("MyChart").embeddedObject Chart.Diagram = Chart.createInstance("com.sun.star.chart.LineDiagram") Chart.Diagram.Wall.FillColor = RGB(255, 255, 255) Chart.Diagram.HasXAxisGrid = True Chart.Diagram.XMainGrid.LineColor = RGB(192, 192, 192) Chart.Diagram.HasYAxisGrid = True Chart.Diagram.YMainGrid.LineColor = RGB(192, 192, 192) Chart.Diagram.YAxis.Min = 0 Chart.Diagram.YAxis.Max = 100 Chart.Diagram.XAxis.ReverseDirection = true 'needs OpenOffice.org 2.4 or newer Chart.Diagram.HasXAxisTitle = true Chart.Diagram.XAxisTitle.String = "Reversed X Axis Example"
179
3D Charts
Most charts in OpenOffice.org can also be displayed with 3D graphics. The following properties are provided for 3D charts at the Diagram object: Dim3D (Boolean) activates 3D display Deep (Boolean) the series will be arranged behind each other in z-direction RightAngledAxes (Boolean) activates a 3D display mode where X- and Y-axes form a right angle within the projection. (available since OpenOffice.org 2.3) D3DScenePerspective (Enum) defines whether the 3D objects are to be drawn in perspective or parallel projection.(values according to com.sun.star.drawing.ProjectionMode ) Perspective (Long) Perspective of 3D charts ( [0,100] ) (available since OpenOffice.org 2.4.1) RotationHorizontal (Long) Horizontal rotation of 3D charts in degrees ( [-180,180] ) (available since OpenOffice.org 2.4.1) RotationVertical (Long) Vertical rotation of 3D charts in degrees ( [-180,180] ) (available since OpenOffice.org 2.4.1) The following example creates a 3D area chart.
The Structure of Charts Dim Dim Dim Dim Dim Doc As Object Charts As Object Chart as Object Rect As New com.sun.star.awt.Rectangle RangeAddress(0) As New com.sun.star.table.CellRangeAddress
180
Doc = StarDesktop.CurrentComponent Charts = Doc.Sheets(0).Charts Rect.X = 8000 Rect.Y = 1000 Rect.Width = 10000 Rect.Height = 7000 RangeAddress(0).Sheet = 0 RangeAddress(0).StartColumn = 0 RangeAddress(0).StartRow = 0 RangeAddress(0).EndColumn = 2 RangeAddress(0).EndRow = 12 Charts.addNewByName("MyChart", Rect, RangeAddress(), True, True) Chart = Charts.getByName("MyChart").embeddedObject Chart.Diagram = Chart.createInstance("com.sun.star.chart.AreaDiagram") Chart.Diagram.Dim3D = true Chart.Diagram.Deep = true Chart.Diagram.RightAngledAxes = true 'needs OpenOffice.org 2.3 or newer Chart.Diagram.D3DScenePerspective = com.sun.star.drawing.ProjectionMode.PERSPECTIVE Chart.Diagram.Perspective = 100 'needs OpenOffice.org 2.4.1 or newer Chart.Diagram.RotationHorizontal = 60 'needs OpenOffice.org 2.4.1 or newer Chart.Diagram.RotationVertical = 30 'needs OpenOffice.org 2.4.1 or newer
Stacked Charts
Stacked charts are charts that are arranged with several individual values on top of one another to produce a total value. This view shows not only the individual values, but also an overview of all the values. In OpenOffice.org, various types of charts can be displayed in a stacked form. All of these charts support the com.sun.star.chart.StackableDiagram service, which in turn provides the following properties: Stacked (Boolean) activates the stacked viewing mode Percent (Boolean)
The Structure of Charts rather than absolute values, displays their percentage distribution Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Structure_ of_ Charts&oldid=91560 Principle Authors: Ccornell, Iha, Fpe
181
Chart Types
Line Charts
Line charts ( com.sun.star.chart.LineDiagram ) support two X-axes, two Y-axes and one Z-axis. They can be displayed as 2D or 3D graphics ( com.sun.star.chart.Dim3Ddiagram service). The lines can be stacked ( com.sun.star.chart.StackableDiagram ). Line charts provide the following properties: SymbolType (const) symbol for displaying the data points (constant in accordance with com.sun.star.chart.ChartSymbolType ) SymbolSize (Long) size of symbol for displaying the data points in 100ths of a millimeter SymbolBitmapURL (String) file name of graphics for displaying the data points Lines (Boolean) links the data points by means of lines SplineType (Long) spline function for smoothing the lines (0: no spline function, 1: cubic splines, 2: B splines) SplineOrder (Long) polynomial weight for splines (only for B splines) SplineResolution (Long) number of support points for spline calculation
Chart Types
182
Area Charts
Area charts ( com.sun.star.chart.AreaDiagram service) support two X-axes, two Y-axes and one Z-axis. They can be displayed as 2D or 3D graphics ( com.sun.star.chart.Dim3Ddiagram service). The areas can be stacked ( com.sun.star.chart.StackableDiagram ).
Bar Charts
Bar charts ( com.sun.star.chart.BarDiagram ) support two X-axes, two Y-axes and one Z-axis. They can be displayed as 2D or 3D graphics ( com.sun.star.chart.Dim3Ddiagram service). The bars can be stacked ( com.sun.star.chart.StackableDiagram ). They provide the following properties: Vertical (Boolean) displays the bars vertically, otherwise they are depicted horizontally Deep (Boolean) in 3D viewing mode, positions the bars behind one another rather than next to one another StackedBarsConnected (Boolean) links the associated bars in a stacked chart by means of lines (only available with horizontal charts) NumberOfLines (Long) number of lines to be displayed in a stacked chart as lines rather than bars GroupBarsPerAxis (Boolean) displays bars attached to different axes behind or next to each other (available since OpenOffice.org 2.4)
Chart Types
183
Pie Charts
Pie charts ( com.sun.star.chart.PieDiagram ) do not contain any axes and cannot be stacked. They can be displayed as 2D or 3D graphics ( com.sun.star.chart.Dim3DDiagram service). The following properties are provided for pie and donut charts with the Diagram object: StartingAngle (Long) angle of the first piece of a pie in degrees (available since OpenOffice.org 3.0) Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Chart_ Types&oldid=91562 Principle Authors: Ccornell, Iha, Fpe
Chart Types
184
Databases
Databases
OpenOffice.org has an integrated database interface (independent of any systems) called Star Database Connectivity (SDBC). The objective of developing this interface was to provide access to as many different data sources as possible. To make this possible, data sources are accessed by drivers. The sources from which the drivers take their data is irrelevant to a SDBC user. Some drivers access file-based databases and take the data directly from them. Others use standard interfaces such as JDBC or ODBC. There are, however, also special drivers which access the MAPI address book, LDAP directories or OpenOffice.org spreadsheets as data sources. Since the drivers are based on UNO components, other drivers can be developed and therefore open up new data sources. You will find details about this in the OpenOffice.org Developer's Guide.
In terms of its concept, SDBC is comparable with the ADO and DAO libraries available in VBA. It permits high level access to databases, regardless of the underlying database backends.
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Database&oldid=91563 Principle Authors: Ccornell, Fpe, DrewJensen
185
Data Sources
A database is incorporated into OpenOffice.org by creating what is commonly referred to as a data source. The user interface provides a corresponding option for creating data sources in the Extras menu. You can also create data sources and work with them using OpenOffice.org Basic. A database context object that is created using the createUnoService function serves as the starting point for accessing a data source. This based on the com.sun.star.sdb.DatabaseContext service and is the root object for all database operations. The following example shows how a database context can be created and then used to determine the names of all data sources available. It displays the names in a message box. Dim DatabaseContext As Object Dim Names Dim I As Integer DatabaseContext = createUnoService("com.sun.star.sdb.DatabaseContext")
Data Sources
186
Names = DatabaseContext.getElementNames() For I = 0 To UBound(Names()) MsgBox Names(I) Next I The individual data sources are based on the com.sun.star.sdb.DataSource service and can be determined from the database context using the getByName method: Dim DatabaseContext As Object Dim DataSource As Object DatabaseContext = createUnoService("com.sun.star.sdb.DatabaseContext") DataSource = DatabaseContext.getByName("Customers") The example creates a DataSource object for a data source called Customers. Data sources provide a range of properties, which in turn provide general information about the origin of the data and information about access methods. The properties are: Name (String) name of data source URL (String) URL of data source in the form of jdbc: subprotocol : subname or sdbc: subprotocol : subname Settings (Array) array containing PropertyValue-pairs with connection parameters (usually at least user name and password) User (String) user name Password (String) user password (is not saved) IsPasswordRequired (Boolean) the password is needed and is interactively requested from user. IsReadOnly (Boolean) permits read-only access to the database NumberFormatsSupplier (Object) object containing the number formats available for the database (supports the com.sun.star.util.XNumberFormatsSupplier interface) TableFilter (Array)
Data Sources list of table names to be displayed TableTypeFilter (Array) list of table types to be displayed. Values available are TABLE, VIEW and SYSTEM TABLE SuppressVersionColumns (Boolean) suppresses the display of columns that are used for version administration
The data sources from OpenOffice.org are not 1:1 comparable with the data sources in ODBC. Whereas an ODBC data source only covers information about the origin of the data, a data source in OpenOffice.org also includes a range of information about how the data is displayed within the database windows of OpenOffice.org.
187
Queries
Predefined queries can be assigned to a data source. OpenOffice.org notes the SQL commands of queries so that they are available at all times. Queries are used to simplify working with databases because they can be opened with a simple mouse click and also provide users without any knowledge of SQL with the option of issuing SQL commands. An object which supports the com.sun.star.sdb.QueryDefinition service is concealed behind a query. The queries are accessed by means of the QueryDefinitions method of the data source. The following example lists the names of data source queries can be established in a message box. Dim Dim Dim Dim Dim DatabaseContext As Object DataSource As Object QueryDefinitions As Object QueryDefinition As Object I As Integer
DatabaseContext = createUnoService("com.sun.star.sdb.DatabaseContext") DataSource = DatabaseContext.getByName("Customers") QueryDefinitions = DataSource.getQueryDefinitions() For I = 0 To QueryDefinitions.Count() - 1 QueryDefinition = QueryDefinitions(I) MsgBox QueryDefinition.Name Next I In addition to the Name property used in the example, the com.sun.star.sdb.QueryDefinition provides a whole range of other properties. These are: Name (String) query name
Data Sources Command (String) SQL command (typically a SELECT command) The following example shows how a query object can be created in a program-controlled manner and can be assigned to a data source. Dim Dim Dim Dim Dim DatabaseContext As Object DataSource As Object QueryDefinitions As Object QueryDefinition As Object I As Integer
188
DatabaseContext = createUnoService("com.sun.star.sdb.DatabaseContext") DataSource = DatabaseContext.getByName("Customers") QueryDefinitions = DataSource.getQueryDefinitions() QueryDefinition = createUnoService("com.sun.star.sdb.QueryDefinition") QueryDefinition.Command = "SELECT * FROM Customer" QueryDefinitions.insertByName("NewQuery", QueryDefinition) The query object is first created using the createUnoService call, then initialized, and then inserted into the QueryDefinitions object by means of insertByName. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Data_ Sources&oldid=91568 Principle Authors: Ccornell, Fpe
Database Access
A database connection is needed for access to a database. This is a transfer channel which permits direct communication with the database. Unlike the data sources presented in the previous section, the database connection must therefore be re-established every time the program is restarted. OpenOffice.org provides various ways of establishing database connections. This example shows how to connect to an existing data source. Dim Dim Dim Dim DatabaseContext As Object DataSource As Object Connection As Object InteractionHandler as Object
DatabaseContext = createUnoService("com.sun.star.sdb.DatabaseContext") DataSource = DatabaseContext.getByName("Customers") If Not DataSource.IsPasswordRequired Then Connection = DataSource.GetConnection("","") Else InteractionHandler =
Database Access createUnoService("com.sun.star.sdb.InteractionHandler") Connection = DataSource.ConnectWithCompletion(InteractionHandler) End If The code used in the example first checks whether the database is password protected. If not, it creates the database connection required using the GetConnection call. The two empty strings in the command line stand for the user name and password. If the database is password protected, the example creates an InteractionHandler and opens the database connection using the ConnectWithCompletion method. The InteractionHandler ensures that OpenOffice.org asks the user for the required login data.
189
Iteration of Tables
A table is usually accessed in OpenOffice.org through the ResultSet object. A ResultSet is a type of marker that indicates a current set of data within a volume of results obtained using the SELECT command. This example shows how a ResultSet can be used to query values from a database table. Dim Dim Dim Dim Dim Dim DatabaseContext As Object DataSource As Object Connection As Object InteractionHandler as Object Statement As Object ResultSet As Object
DatabaseContext = createUnoService("com.sun.star.sdb.DatabaseContext") DataSource = DatabaseContext.getByName("Customers") If Not DataSource.IsPasswordRequired Then Connection = DataSource.GetConnection("","") Else InteractionHandler = createUnoService("com.sun.star.sdb.InteractionHandler") Connection = DataSource.ConnectWithCompletion(InteractionHandler) End If Statement = Connection.createStatement() ResultSet = Statement.executeQuery("SELECT ""CustomerNumber"" FROM ""Customer""") If Not IsNull(ResultSet) Then While ResultSet.next MsgBox ResultSet.getString(1) Wend End If Once the database connection has been established, the code used in the example first uses the Connection.createObject call to create a Statement object. This Statement object
Database Access then uses the executeQuery call to return the actual ResultSet. The program now checks whether the ResultSet actually exists and traverses the data records using a loop. The values required (in the example, those from the CustomerNumber field) returns the ResultSet using the getString method, whereby the parameter 1 determines that the call relates to the values of the first column.
The ResultSet object from SDBC is comparable with the Recordset object from DAO and ADO, since this also provides iterative access to a database.
190
The database is actually accessed in OpenOffice.org through a ResultSet object. This reflects the content of a table or the result of a SQL-SELECT command. In the past, the ResultSet object provided the resident methods in the Application object for navigation within the data, for example, DataNextRecord ).
Database Access getCharacterStream() supports the SQL data types for numbers, strings and binary values getUnicodeStream() supports the SQL data types for numbers, strings and binary values getBinaryStream() binary values getObject() supports all SQL data types In all instances, the number of columns should be listed as a parameter whose values should be queried.
191
Database Access com.sun.star.sdbc.ResultSetConcurrency group of constants provides the following specifications: FORWARD_ONLY ResultSet only permits forward navigation SCROLL_INSENSITIVE ResultSet permits any type of navigation, changes to the original data are, however, not noted SCROLL_SENSITIVE ResultSet permits any type of navigation, changes to the original data impact on the ResultSet
A ResultSet containing the READ_ONLY and SCROLL_INSENSITIVE properties corresponds to a record set of the Snapshot type in ADO and DAO.
192
When using the ResultSet's UPDATEABLE and SCROLL_SENSITIVE properties, the scope of function of a ResultSet is comparable with a Dynaset type Recordset from ADO and DAO.
Database Access ResultSet is the first data record isLast() ResultSet is the last data record
193
Database Access
194
Dialogs
Dialogs
You can add custom dialog windows and forms to OpenOffice.org documents. These in turn can be linked to OpenOffice.org Basic macros to considerably extend the usage range of OpenOffice.org Basic. Dialogs can, for example, display database information or guide users through a step-by-step process of creating a new document in the form of a Wizard. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Dialogs&oldid=91573 Principle Authors: Fpe, Ccornell
Creating Dialogs
You can create and structure dialogs using the OpenOffice.org dialog editor: You can drag the control elements from the design pallet (right) into the dialog area, and define their position and size. The example shows a dialog that contains a label and a list box.
195
You can open a dialog with the following code: Dim Dlg As Object DialogLibraries.LoadLibrary("Standard") Dlg = CreateUnoDialog(DialogLibraries.Standard.DlgDef) Dlg.Execute() Dlg.dispose() CreateUnoDialog creates an object called Dlg that references the associated dialog. Before you can create the dialog, you must ensure that the library it uses (in this example, the Standard library) is loaded. The LoadLibrary method performs this task.
Once the Dlg dialog object has been initialized, you can use the Execute method to display the dialog. Dialogs such as this one are described as modal because they do not permit any other program action until they are closed. While this dialog is open, the program remains in the Execute call. The dispose method at the end of the code approves the resources used by the dialog once the program ends.
Closing Dialogs
Closing With OK or Cancel
If a dialog contains an OK or a Cancel button, the dialog is automatically closed when you click one of these buttons. More information about working with these buttons is discussed in Dialog Control Elements in Detail. If you close a dialog by clicking the OK button, the Execute-method returns a return value of 1, otherwise a value of 0 is returned. Dim Dlg As Object DialogLibraries.LoadLibrary("Standard") Dlg = CreateUnoDialog(DialogLibraries.Standard.MyDialog) Select Case Dlg.Execute() Case 1 MsgBox "Ok pressed" Case 0 MsgBox "Cancel pressed" End Select
196
Working With Dialogs Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Working_ With_ Dialogs&oldid=91575 Principle Authors: Ccornell, Fpe
197
Properties
Name and Title
Every control element has its own name that can be queried using the following model property: Model.Name (String) control element name You can specify the title that appears in the title bar of a dialog with the following model property: Model.Title (String) dialog title (only applies to dialogs)
Properties
198
Multi-Page Dialogs
A dialog in OpenOffice.org can have more than one tab page. The Step property of a dialog defines the current tab page of the dialog whereas the Step property for a control element specifies the tab page where the control element is to be displayed. The Step-value of 0 is a special case. If you set this value to zero in a dialog, all of the control elements are visible regardless of their Step value. Similarly, if you set this value to zero for a control element, the element is displayed on all of the tab pages in a dialog. In the preceding example, you can also assign the Step value of 0 to the dividing line as well as the Cancel, Prev, Next, and Done buttons to display these elements on all pages. You can also assign the elements to an individual tab page (for example page 1). The following program code shows how the Step value in event handlers of the Next and Prev buttons can be increased or reduced and changes the status of the buttons. Sub cmdNext_Initiated Dim cmdNext As Object Dim cmdPrev As Object cmdPrev = Dlg.getControl("cmdPrev")
Designing Page 1 of the dialog
Properties cmdNext = Dlg.getControl("cmdNext") cmdPrev.Model.Enabled = Not cmdPrev.Model.Enabled cmdNext.Model.Enabled = False Dlg.Model.Step = Dlg.Model.Step + 1 End Sub Sub cmdPrev_Initiated Dim cmdNext As Object Dim cmdPrev As Object cmdPrev = Dlg.getControl("cmdPrev") cmdNext = Dlg.getControl("cmdNext") cmdPrev.Model.Enabled = False cmdNext.Model.Enabled = True Dlg.Model.Step = Dlg.Model.Step - 1 End Sub A global Dlg variable that references an open dialog must be included to make this example possible. The dialog then changes its appearance as follows:
199
Page 1
Page 2
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Properties&oldid=91577 Principle Authors: Ccornell, Fpe
Events
200
Events
OpenOffice.org dialogs and forms are based on an event-oriented programming model where you can assign event handlers to the control elements. An event handler runs a predefined procedure when a particular action occurs. You can also edit documents or open databases with event handling as well as access other control elements. OpenOffice.org control elements recognize different types of events that can be triggered in different situations. These event types can be divided into four groups: Mouse control: Events that correspond to mouse actions (for example, simple mouse movements or a click on a particular screen location). Keyboard control: Events that are triggered by keyboard strokes. Focus modification: Events that OpenOffice.org performs when control elements are activated or deactivated. Control element-specific events: Events that only occur in relation to certain control elements. When you work with events, make sure that you create the associated dialog in the OpenOffice.org development environment and that it contains the required control elements or documents (if you apply the events to a form). The figure above shows the OpenOffice.org Basic development environment with a dialog window that contains two list boxes. You can move the data from one list to the other using the buttons between the two list boxes. If you want to display the layout on screen, then you should create the associated OpenOffice.org Basic procedures so that they can be called up by the event handlers. Even though you can use these procedures in any module, it is best to limit their use to two modules. To make your code easier to read, you should The OpenOffice.org Basic development environment assign meaningful names to these procedures. Jumping directly to a general program procedure from a macro can result in unclear code. Instead, to simplify code maintenance and troubleshooting, you should create another procedure to serve as an entry point for event handling - even if it only executes a single call to the target procedure. The code in the following example moves an entry from the left to the right list box of a dialog. Sub cmdSelect_Initiated Dim objList As Object lstEntries = Dlg.getControl("lstEntries")
Events lstSelection = Dlg.getControl("lstSelection") If lstEntries.SelectedItem > 0 Then lstSelection.AddItem(lstEntries.SelectedItem, 0) lstEntries.removeItems(lstEntries.SelectItemPos, 1) Else Beep End If End Sub If this procedure was created in OpenOffice.org Basic, you can assign it to an event required using the property window of the dialog editor. The assignment dialog lists all of the OpenOffice.org Basic procedures. To assign a procedure to an event, select the procedure, and then click Assign.
201
Parameters
The occurrence of a particular event is not always enough for an appropriate response. Additional The Assign Macro dialog information may be required. For example, to process a mouse click, you may need the screen position where the mouse button was pressed. In OpenOffice.org Basic, you can use object parameters to provide more information about an event to a procedure, for example: Sub ProcessEvent(Event As Object) End Sub The structure and properties of the Event object depend on the type of event that triggers the procedure call. Regardless of the type of event, all objects provide access to the relevant control element and its model. The control element can be reached using Event.Source and its model using Event.Source.Model. You can use these properties to trigger an event within an event handler.
Mouse Events
OpenOffice.org Basic recognizes the following mouse events: Mouse moved user moves mouse Mouse moved while key pressed user drags mouse while holding down a key
Events Mouse button pressed user presses a mouse button Mouse button released user releases a mouse button Mouse outside user moves mouse outside of the current window The structure of the associated event objects is defined in the com.sun.star.awt.MouseEvent structure which provides the following information: Buttons (short) button pressed (one or more constants in accordance with com.sun.star.awt.MouseButton ) X (long) X-coordinate of mouse, measured in pixels from the top left corner of the control element Y (long) Y-coordinate of mouse, measured in pixels from the top left corner of the control element ClickCount (long) number of clicks associated with the mouse event (if OpenOffice.org can respond fast enough, ClickCount is also 1 for a double-click because only an individual event is initiated) The constants defined in com.sun.star.awt.MouseButton for the mouse buttons are: LEFT left mouse button RIGHT right mouse button MIDDLE middle mouse button The following example outputs the mouse position as well as the mouse button that was pressed: Sub MouseUp(Event As Object) Dim Msg As String
202
Events Msg = "Keys: " If Event.Buttons AND com.sun.star.awt.MouseButton.LEFT Then Msg = Msg & "LEFT " End If If Event.Buttons AND com.sun.star.awt.MouseButton.RIGHT Then Msg = Msg & "RIGHT " End If If Event.Buttons AND com.sun.star.awt.MouseButton.MIDDLE Then Msg = Msg & "MIDDLE " End If Msg = Msg & Chr(13) & "Position: " Msg = Msg & Event.X & "/" & Event.Y MsgBox Msg End Sub
203
The VBA Click and Doubleclick events are not available in OpenOffice.org Basic. Instead use the OpenOffice.org Basic MouseUp event for the click event and imitate the Doubleclick event by changing the application logic.
Keyboard Events
The following keyboard events are available in OpenOffice.org Basic: Key pressed user presses a key. Key released user releases a key Both events relate to logical key actions and not to physical actions. If the user presses several keys to output a single character (for example, to add an accent to a character), then OpenOffice.org Basic only creates one event. A single key action on a modification key, such as the Shift key or the Alt key does not create an independent event. Information about a pressed key is provided by the event object that OpenOffice.org Basic supplies to the procedure for event handling. It contains the following properties: KeyCode (short) code of the pressed key (default values in accordance with com.sun.star.awt.Key ) KeyChar (String) character that is entered (taking the modification keys into consideration)
Events The following example uses the KeyCode property to establish if the Enter key, the Tab key, or one of the other control keys has been pressed. If one of these keys has been pressed, the name of the key is returned, otherwise the character that was typed is returned: Sub KeyPressed(Event As Object) Dim Msg As String Select Case Event.KeyCode Case com.sun.star.awt.Key.RETURN Msg = "Return pressed" Case com.sun.star.awt.Key.TAB Msg = "Tab pressed" Case com.sun.star.awt.Key.DELETE Msg = "Delete pressed" Case com.sun.star.awt.Key.ESCAPE Msg = "Escape pressed" Case com.sun.star.awt.Key.DOWN Msg = "Down pressed" Case com.sun.star.awt.Key.UP Msg = "Up pressed" Case com.sun.star.awt.Key.LEFT Msg = "Left pressed" Case com.sun.star.awt.Key.RIGHT Msg = "Right pressed" Case Else Msg = "Character " & Event.KeyChar & " entered" End Select MsgBox Msg End Sub Information about other keyboard constants can be found in the API Reference under the com.sun.star.awt.Key group of constants.
204
Focus Events
Focus events indicate if a control element receives or loses focus. You can use these events to, for example, determine if a user has finished processing a control element so that you can update other elements of a dialog. The following focus events are available: When receiving focus element receives focus When losing focus element loses focus The Event objects for the focus events are structured as follows:
Events FocusFlags (short) cause of focus change (default value in accordance with com.sun.star.awt.FocusChangeReason ) NextFocus (Object) object that receives focus (only for the When losing focus event) Temporary (Boolean) the focus is temporarily lost
205
206
Text fields Date fields Time fields Numerical fields Currency fields Fields adopting any format
Buttons
A button performs an action when you click it. The simplest scenario is for the button to trigger a When Initiating event when it is clicked by a user. You can also link another action to the button to open a dialog using the PushButtonType property. When you click a button that has this property set to the value of 0, the dialog remains unaffected. If you click a button that has this property set to the value of 1, the dialog is closed, and the Execute method of the dialog returns the value 1 (dialog sequence has been ended correctly). If the PushButtonType has the value of 2, the dialog is closed and the Execute method of the dialog returns the value 0 (dialog closed). The following are all of the properties that are available through the button model: Model.BackgroundColor (long) color of background Model.DefaultButton (Boolean) The button is used as the default value and responds to the Enter key if it has no focus Model.FontDescriptor (struct) structure that specifies the details of the font to be used (in accordance with com.sun.star.awt.FontDescriptor structure) Model.Label (String) label that is displayed on the button Model.Printable (Boolean) the control element can be printed Model.TextColor (Long) text color of the control element Model.HelpText (String) help text that is displayed when you move the mouse cursor over the control element Model.HelpURL (String)
Dialog Control Elements URL of the online help for the corresponding control element PushButtonType (short) action that is linked to the button (0: no action, 1: OK, 2: Cancel)
207
Option Buttons
These buttons are generally used in groups and allow you to select from one of several options. When you select an option, all of the other options in the group are deactivated. This ensures that at any one time, only one option button is set. An option button control element provides two properties: State (Boolean) activates the button Label (String) label that is displayed on the button You can also use the following properties from the model of the option buttons: Model.FontDescriptor (struct) structure with details of the font to be used (in accordance with com.sun.star.awt.FontDescriptor ) Model.Label (String) label that is displayed on the control element Model.Printable (Boolean) control element can be printed Model.State (Short) if this property is equal to 1, the option is activated, otherwise it is deactivated Model.TextColor (Long) text color of control element Model.HelpText (String) help text that is displayed when the mouse cursor rests over the control element Model.HelpURL (String) URL of online help for the corresponding control element To combine several option buttons in a group, you must position them one after another in the activation sequence without any gaps (Model.TabIndex property, described as Order in the dialog editor). If the activation sequence is interrupted by another control element, then OpenOffice.org automatically starts with a new control element group that can be activated regardless of the first group of control elements.
Unlike VBA, you cannot insert option buttons in a group of control elements in OpenOffice.org Basic. The grouping of control elements in OpenOffice.org Basic is only used to ensure a visual division by drawing a frame around the control elements.
208
Checkboxes
Checkboxes are used to record a Yes or No value and depending on the mode, they can adopt two or three states. In addition to the Yes and No states, a check box can have an in-between state if the corresponding Yes or No status has more than one meaning or is unclear. Checkboxes provide the following properties: State (Short) state of the checkbox (0: no, 1: yes, 2: in-between state) Label (String) label for the control element enableTriState (Boolean) in addition to the activated and deactivated states, you can also use the in-between state The model object of a checkbox provides the following properties: Model.FontDescriptor (struct) structure with details of the font used (in accordance with com.sun.star.awt.FontDescriptor structure) Model.Label (String) label for the control element Model.Printable (Boolean) the control element can be printed Model.State (Short) state of the checkbox (0: no, 1: yes, 2: in-between state) Model.Tabstop (Boolean) the control element can be reached with the Tab key Model.TextColor (Long) text color of control element Model.HelpText (String) help text that is displayed when you rest the mouse cursor over the control element Model.HelpURL (String) URL of online help for the corresponding control element
209
Text Fields
Text fields allow users to type numbers and text. The com.sun.star.awt.UnoControlEdit. service forms the basis for text fields. A text field can contain one or more lines and can be edited or blocked for user entries. Text fields can also be used as special currency and numerical fields as well as screen fields for special tasks. As these control elements are based on the UnoControlEdit Uno service, their program-controlled handling is similar. Text fields provide the following properties: Text (String) current text SelectedText (String) currently highlighted text Selection (Struct) read-only highlighting of details (structure in accordance with com.sun.star.awt.Selection , with the Min and Max properties to specify the start and end of the current highlighting) MaxTextLen (short) maximum number of characters that you can type in the field Editable (Boolean) True activates the option for entering text, False blocks the entry option (the property cannot be called up directly but only through IsEditable) IsEditable (Boolean) the content of the control element can be changed, read-only The following properties are provided through the associated model object: Model.Align (short) orientation of text (0: left-aligned, 1: centered, 2: right-aligned) Model.BackgroundColor (long) color of the background of the control element Model.Border (short) type of border (0: no border, 1: 3D border, 2: simple border) Model.EchoChar (String) echo character for password fields Model.FontDescriptor (struct) structure with details of font used (in accordance with com.sun.star.awt.FontDescriptor structure)
Dialog Control Elements Model.HardLineBreaks (Boolean) automatic line breaks are permanently inserted in the control element text Model.HScroll (Boolean) the text has a horizontal scrollbar Model.MaxTextLen (Short) maximum length of text, where 0 corresponds to no length limit Model.MultiLine (Boolean) permits entry to spans several lines Model.Printable (Boolean) the control element can be printed Model.ReadOnly (Boolean) the content of the control element is read-only Model.Tabstop (Boolean) the control element can be reached with the Tab key Model.Text (String) text associate with the control element Model.TextColor (Long) text color of control element Model.VScroll (Boolean) the text has a vertical scrollbar Model.HelpText (String) help text that is displayed when the mouse cursor rests over the control element Model.HelpURL (String) URL of online help for the corresponding control element
210
List Boxes
List boxes ( com.sun.star.awt.UnoControlListBox service) support the following properties: ItemCount (Short) number of elements, read-only SelectedItem (String) text of highlighted entry, read-only SelectedItems (Array Of Strings) data field with highlighted entries, read-only SelectItemPos (Short) number of the entry highlighted at present, read-only SelectItemsPos (Array of Short)
Dialog Control Elements data field with the number of highlighted entries (for lists which support multiple selection), read-only MultipleMode (Boolean) True activates the option for multiple selection of entries, False blocks multiple selections (the property cannot be called up directly but only through IsMultipleMode) IsMultipleMode (Boolean) permits multiple selection within lists, read-only List boxes provide the following methods: addItem (Item, Pos) enters the string specified in the Item into the list at the Pos position addItems (ItemArray, Pos) enters the entries listed in the string's ItemArray data field into the list at the Pos position removeItems (Pos, Count) removes Count entries as of the Pos position selectItem (Item, SelectMode) activates or deactivates highlighting for the element specified in the string Item depending on the SelectMode Boolean variable makeVisible (Pos) scrolls through the list field so that the entry specified with Pos is visible The model object of the list boxes provides the following properties: Model.BackgroundColor (long) background color of control element Model.Border (short) type of border (0: no border, 1: 3D border, 2: simple border) Model.FontDescriptor (struct) structure with details of font used (in accordance with com.sun.star.awt.FontDescriptor structure) Model.LineCount (Short) number of lines in control element Model.MultiSelection (Boolean) permits multiple selection of entries Model.SelectedItems (Array of Strings) list of highlighted entries Model.StringItemList (Array of Strings) list of all entries Model.Printable (Boolean)
211
Dialog Control Elements the control element can be printed Model.ReadOnly (Boolean) the content of the control element is read-only Model.Tabstop (Boolean) the control element can be reached with the Tab key Model.TextColor (Long) text color of control element Model.HelpText (String) automatically displayed help text which is displayed if the mouse cursor is above the control element Model.HelpURL (String) URL of online help for the corresponding control element
The VBA option for issuing list entries with a numerical additional value (ItemData) does not exist in OpenOffice.org Basic. If you want to administer a numerical value (for example a database ID) in addition to the natural language text, you must create an auxiliary data field that administers in parallel to the list box.
212
Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Control_ Elements&oldid=91590 Principle Authors: Ccornell, Fpe, TJFrazier, DrewJensen
213
Forms
Forms
In many respects, the structure of OpenOffice.org forms corresponds to the dialogs. There are, however, a few key differences: Dialogs appear in the form of one single dialog window, which is displayed over the document and does not permit any actions other than dialog processing until the dialog is ended. Forms, on the other hand, are displayed directly in the document, just like drawing elements. A dialog editor is provided for creating dialogs, and this can be found in the OpenOffice.org Basic development environment. Forms are created using the Form Controls and the Form Design Toolbar directly within the document. Whereas the dialog functions are available in all OpenOffice.org documents, the full scope of the form functions are only available in text and spreadsheets. The control elements of a form can be linked with an external database table. This function is not available in dialogs. The control elements of dialogs and forms differ in several aspects. Users who want to provide their forms with their own methods for event handling, should refer to the Dialogs chapter. The mechanisms explained there are identical to those for forms. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Forms&oldid=91591 Principle Authors: Ccornell, Fpe
214
Doc = StarDesktop.CurrentComponent Sheet = Doc.Sheets.GetByIndex(0) DrawPage = Sheet.DrawPage Form = DrawPage.Forms.GetByIndex(0) As is already suggested by the GetByIndex method name, a document may contain several forms. This is useful, for example, if the contents of different databases are displayed within one document, or if a 1:n database relationship is displayed within a form. The option of creating sub-forms is also provided for this purpose.
215
Doc = StarDesktop.CurrentComponent Forms = Doc.Drawpage.Forms For I = 0 To Forms.Count - 1 Form = Forms.GetbyIndex(I) If Form.HasByName("MyListBox") Then Ctl = Form.GetbyName("MyListBox") Exit Function End If Next I The example uses the HasByName method to check all forms of a text document to determine whether they contain a control element model called MyListBox. If a corresponding model is found, then a reference to this is saved in the Ctl variable and the search is terminated.
216
Doc = StarDesktop.CurrentComponent DocCrl = Doc.getCurrentControler() Forms = Doc.Drawpage.Forms For I = 0 To Forms.Count - 1 Form = Forms.GetbyIndex(I) If Form.HasByName("MyListBox") Then Ctl = Form.GetbyName("MyListBox") CtlView = DocCrl.GetControl(Ctl) Exit Function End If Next I The code listed in the example is very similar to the code listed in the previous example for determining a control element model. It uses not only the Doc document object but also the DocCrl document controller object which makes reference to the current document window. With the help of this controller object and the model of the control element, it then uses the GetControl method to determine the view (CtlView variable) of the control element form.
217
Working With Forms Dim Shape As Object Point.x = 1000 Point.y = 1000 Size.Width = 10000 Size.Height = 10000 Shape.Size = Size Shape.Position = Point The shape object of the control element must already be known if the code is to function. If this is not the case, it must be determined using the preceding code. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Working_ With_ Forms&oldid=91594 Principle Authors: Ccornell, Fpe
218
Buttons
The model object of a form button provides the following properties: BackgroundColor (long) background color DefaultButton (Boolean) the button serves as a default value. In this case, it also responds to the entry button if it has no focus Enabled (Boolean) the control element can be activated Tabstop (Boolean) the control element can be reached through the tabulator button TabIndex (Long) position of control element in activation sequence FontName (String) name of font type FontHeight (Single)
Control Element Forms height of character in points (pt) Tag (String) string containing additional information, which can be saved in the button for program-controlled access TargetURL (String) target URL for buttons of the URL type TargetFrame (String) name of window (or frame) in which TargetURL is to be opened when activating the button (for buttons of the URL type) Label (String) button label TextColor (Long) text color of control element HelpText (String) automatically displayed help text which is displayed if the mouse cursor is above the control element HelpURL (String) URL of online help for the corresponding control element ButtonType (Enum) action that is linked with the button (default value from com.sun.star.form.FormButtonType ) Through the ButtonType property, you have the opportunity to define an action that is automatically performed when the button is pressed. The associated com.sun.star.form.FormButtonType group of constants provides the following values: PUSH standard button SUBMIT end of form entry (particularly relevant for HTML forms) RESET resets all values within the form to their original values URL call of the URL defined in TargetURL (is opened within the window which was specified through TargetFrame) The OK and Cancel button types provided in dialogs are not supported in forms.
219
220
Option Buttons
The following properties of an option button are available through its model object: Enabled (Boolean) the control element can be activated Tabstop (Boolean) the control element can be reached through the tab key TabIndex (Long) position of control element in the activation sequence FontName (String) name of font type FontHeight (Single) height of character in points (pt) Tag (String) string containing additional information, which can be saved in the button for program-controlled access Label (String) inscription of button Printable (Boolean) the control element can be printed State (Short) if 1, the option is activated, otherwise it is deactivated RefValue (String) string for saving additional information (for example, for administering data record IDs) TextColor (Long) text color of control element HelpText (String) automatically displayed help text, which is displayed if the mouse cursor is above the control element HelpURL (String) URL of online help for the corresponding control element The mechanism for grouping option buttons distinguishes between the control elements for dialogs and forms. Whereas control elements appearing one after another in dialogs are automatically combined to form a group, grouping in forms is performed on the basis of names. To do this, all option buttons of a group must contain the same name. OpenOffice.org combines the grouped control elements into an array so that the individual buttons of a OpenOffice.org Basic program can be reached in the same way. The following example shows how the model of a control element group can be determined. Dim Doc As Object Dim Forms As Object Dim Form As Object
Control Element Forms Dim Ctl As Object Dim I as Integer Doc = StarDesktop.CurrentComponent Forms = Doc.Drawpage.Forms For I = 0 To Forms.Count - 1 Form = Forms.GetbyIndex(I) If Form.HasByName("MyOptions") Then Ctl = Form. GetGroupbyName("MyOptions") Exit Function End If Next I The code corresponds to the previous example for determining a simple control element model. It searches through all forms in the current text document in a loop and uses the HasByName method to check whether the corresponding form contains an element with the MyOptions name it is searching for. If this is the case, then the model array is accessed using the GetGroupByName method (rather than the GetByName method to determine simple models).
221
Checkboxes
The model object of a checkbox form provides the following properties: Enabled (Boolean) the control element can be activated Tabstop (Boolean) the control element can be reached through the tab key TabIndex (Long) position of control element in the activation sequence FontName (String) name of font type FontHeight (Single) height of character in points (pt) Tag (String) string containing additional information, which can be saved in the button for program-controlled access Label (String) button label Printable (Boolean) the control element can be printed State (Short) if 1, the option is activated, otherwise it is deactivated RefValue (String)
Control Element Forms string for saving additional information (for example, for administrating data record IDs) TextColor (Long) text color of control element HelpText (String) automatically displayed help text, which is displayed if the mouse cursor is above the control element HelpURL (String) URL of online help for the corresponding control element
222
Text Fields
The model objects of text field forms offer the following properties: Align (short) orientation of text (0: left-aligned, 1: centered, 2: right-aligned) BackgroundColor (long) background color of control element Border (short) type of border (0: no border, 1: 3D border, 2: simple border) EchoChar (String) echo character for password field FontName (String) name of font type FontHeight (Single) height of character in points (pt) HardLineBreaks (Boolean) the automatic line breaks are permanently inserted in the text of the control element HScroll (Boolean) the text has a horizontal scrollbar MaxTextLen (Short) maximum length of text; if 0 is specified, there are no limits MultiLine (Boolean) permits multi-line entries Printable (Boolean) the control element can be printed ReadOnly (Boolean) the content of the control element is read-only Enabled (Boolean) the control element can be activated Tabstop (Boolean) the control element can be reached through the tab key
Control Element Forms TabIndex (Long) position of the control element in the activation sequence FontName (String) name of font type FontHeight (Single) height of character in points (pt) Text (String) text of control element TextColor (Long) text color of control element VScroll (Boolean) the text has a vertical scrollbar HelpText (String) automatically displayed help text, which is displayed if the mouse cursor is above the control element HelpURL (String) URL of online help for the corresponding control element
223
List Boxes
The model object of the list box forms provides the following properties: BackgroundColor (long) background color of control element Border (short) type of border (0: no border, 1: 3D frame, 2: simple frame) FontDescriptor (struct) structure with details of font to be used (in accordance with com.sun.star.awt.FontDescriptor structure) LineCount (Short) number of lines of control element MultiSelection (Boolean) permits multiple selection of entries SelectedItems (Array of Strings) list of highlighted entries StringItemList (Array of Strings) list of all entries ValueItemList (Array of Variant) list containing additional information for each entry (for example, for administrating data record IDs)
Control Element Forms Printable (Boolean) the control element can be printed ReadOnly (Boolean) the content of the control element is read-only Enabled (Boolean) the control element can be activated Tabstop (Boolean) the control element can be reached through the tab key TabIndex (Long) position of control element in the activation sequence FontName (String) name of font type FontHeight (Single) height of character in points (pt) Tag (String) string containing additional information which can be saved in the button for program-controlled access TextColor (Long) text color of control element HelpText (String) automatically displayed help text, which is displayed if the mouse cursor is above the control element HelpURL (String) URL of online help for the corresponding control element
Through their ValueItemList property, list box forms provide a counterpart to the VBA property, ItemData, through which you can administer additional information for individual list entries.
224
Furthermore, the following methods are provided though the view object of the list box: addItem (Item, Pos) inserts the string specified in the Item at the Pos position in the list addItems (ItemArray, Pos) inserts the entries listed in the string's ItemArray data field in the list at the Pos position removeItems (Pos, Count) removes Count entries as of the Pos position selectItem (Item, SelectMode) activates or deactivates the highlighting for the element specified in the string Item depending on the SelectMode variable makeVisible (Pos) scrolls through the list field so that the entry specified by Pos is visible
Control Element Forms Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Control_ Element_ Forms&oldid=91596 Principle Authors: Ccornell, Fpe
225
Database Forms
OpenOffice.org forms can be directly linked to a database. The forms created in this way provide all the functions of a full database front end without requiring independent programming work. You can page through and search in the selected tables and queries, as well as change data records and insert new data records. OpenOffice.org automatically ensures that the relevant data is retrieved from the database, and that any changes made are written back to the database. A database form corresponds to a standard OpenOffice.org form. In addition to the standard properties, the following database-specific properties must also be set in the form: DataSourceName (String) name of data source (refer to Database Access; the data source must be globally created in OpenOffice.org) Command (String) name of table, query, or the SQL select command to which a link is to be made CommandType (Const) specifies whether the Command is a table, a query or a SQL command (value from com.sun.star.sdb.CommandType enumeration) The com.sun.star.sdb.CommandType enumeration covers the following values: TABLE Table QUERY Query COMMAND SQL command The database fields are assigned to the individual control elements through this property: DataField (String) name of linked database field
Database Forms
226
Tables
Another control element is provided for work with databases, the table control element. This represents the content of a complete database table or query. In the simplest scenario, a table control element is linked to a database using the autopilot form, which links all columns with the relevant database fields in accordance with the user specifications. Source: http:/ / wiki. services. openoffice. org/ w/ index. php? title=Documentation/ BASIC_ Guide/ Database_ Forms&oldid=91601 Principle Authors: Ccornell, Fpe