Basic Programmer's Guide > The Language of StarOffice Basic

StarOffice(tm) 7 Office Suite

Basic Programmer's Guide |

## The Language of StarOffice Basic

Previous · Start · Next

StarOffice Basic belongs to the family of Basic languages. Many parts of StarOffice Basic are identical to Microsoft Visual Basic for Applications and Microsoft Visual Basic. Anyone who has already worked with these languages can quickly become accustomed to StarOffice Basic.

Programmers of other languages – such as Java, C++, or Delphi – should also find it easy to familiarize themselves with StarOffice Basic. StarOffice Basic is a fully-developed procedural programming language and no longer uses rudimentary control structures, such as GoTo and GoSub.

You can also benefit from the advantages of object-oriented programming since an interface in StarOffice Basic enables you to use external object libraries. The entire StarOffice API is based on these interfaces, which are described in more detail in the following chapters of this document.

This chapter provides an overview of the key elements and constructs of the StarOffice Basic language, as well as the framework in which applications and libraries are oriented to StarOffice Basic.

## An Overview of a StarOffice Basic Program

StarOffice Basic is an interpreter language. Unlike C++ or Turbo Pascal, the StarOffice compiler does not create executable or self-extracting files that are capable of running automatically. Instead, you can execute a StarOffice Basic program by pressing a button. The code is first checked for obvious errors and then executed line by line.

### 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.

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 = (Expression1 * Expression2) + _

(Expression3 * Expression4) + _

(Expression5 * Expression6) + _

(Expression7 * 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, StarOffice 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, a StarOffice 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.

StarOffice 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. StarOffice 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 StarOffice 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 character s. The One TestVariable marker, for example, define s the same variable as onetestVariable and ONE TESTVARIABLE.

  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 Chapter 4.)

The rules for constructing markers are different in StarOffice Basic than in VBA. Dor example, StarOffice Basic does not allow special characters in markers, since they can cause problems in international projects.

Here are a few examples of correct and incorrect markers:

Surname' Correct

Surname5' Correct (number 5 is not the first digit)

First Name' Incorrect (spaces are not permitted)

DéjàVu' Incorrect (letters such as é, à are not permitted)

5Surnames' Incorrect (the first character must not be a number)

First,Name' Incorrect (commas and full stops are not permitted)

## Working With Variables

### Implicit Variable Declaration

Basic languages are designed to be easy to use. As a result, StarOffice Basic enables the creation of a variable through simple usage and without an explicit declaration. In other words, a variable exists from the moment that you include it in your code. Depending on the variables that are already present, the following example declares up to three new variables:

a = b + c

Declaring variables implicitly is not good programming practice because it can result in the inadvertent introduction of a new variable through, for example, a typing error. Instead of producing an error message, the interpreter initializes the typing error as a new variable with a value of 0. It can be very difficult to locate errors of this kind in your code.

### Explicit Variable Declaration

To prevent errors caused by an implicit declaration of variables, StarOffice Basic provides a switch called:

Option Explicit

This must be listed in the first program line of each module and ensures that an error message is issued if one of the variables used is not declared. The Option Explicit switch should be included in all Basic modules.

In its simplest form, the command for an explicit declaration of a variable is as follows:

Dim MyVar

This example declares a variable with the name MyVar and the type variant. A variant is a universal variable that can record all conceivable values, including strings, whole numbers, floating point figures, and Boolean values. Here are a few examples of Variant variables:

MyVar = "Hello World"' Assignment of a string

MyVar = 1' Assignment of a whole number

MyVar = 1.0' Assignment of a floating point number

MyVar = True' Assignment of a Boolean value

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 StarOffice 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, StarOffice 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

The following sections list the variable types that are available in StarOffice Basic and describe how they can be used and declared.

## Strings

Strings, together with numbers, form the most important basic types of StarOffice 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.

### From a Set of ASCII Characters to Unicode

Character sets match characters in a string with a corresponding code (numbers and characters) in a table that describes how the computer is to display the string.

The ASCII Character Set

The ASCII character set is a set of codes that represent numbers, characters, and special symbols by one byte. The 0 to 127 ASCII codes correspond to the alphabet and to common symbols (such as periods, brackets, and commas), as well as some special screen and printer control codes. The ASCII character set is commonly used as a standard format for transferring text data between computers.

However, this character set does not include a range of special characters used in Europe, such as â, ä and î, as well as other character formats, such as the Cyrillic alphabet.

The ANSI Character Set

Microsoft based its Windows product on the American National Standards Institute (ANSI) character set, which was gradually extended to include characters that are missing from the ASCII character set.

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.

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 StarOffice and StarOffice Basic.

### String Variables

StarOffice Basic saves strings as string variables in Unicode. A string variable can store up to 65535 characters. Internally, StarOffice 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 StarOffice Basic is observed (65535 characters).

### Specification of Explicit Strings

To assign an explicit string to a string variable, enclose the string in quotation marks (").

Dim MyString As String

MyString = " This is a test"

To split a string across two lines, add a plus sign at the end of the first line:

Dim MyString As String

MyString ="This string is so long that it" + _

"has been split over two lines."

To include a quotation mark (") in a string, enter it twice at the relevant point:

Dim MyString As String

MyString = "a ""-quotation mark." ' produces a "-quotation mark

## Numbers

StarOffice Basic supports five basic types for processing numbers:

- Integer

- Long Integer

- Float

- 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%

### Long Integer Variables

Long integer variables can store any whole number between 2147483648 and 2147483647. A long integer variable can takes up to four bytes of memory. The type declaration symbol for a long integer is &. Calculations with long integer variables are very fast and are particularly useful for loop counters. If you assign a floating point number to a long integer variable, the number is rounded up or down to the next whole number.

Example declarations for long integer variables:

Dim Variable as Long

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!

### 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@

### Specification of Explicit Numbers

Numbers can be presented in several ways, for example, in decimal format or in scientific notation, or even with a different base than the decimal system. The following rules apply to numerical characters in StarOffice Basic:

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

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

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, StarOffice Basic rounds the figure up or down.

Exponential Writing Style

StarOffice Basic allows numbers to be specified in the exponential writing style, for example, you can write 1.5e-10 for the number 1.5 × 10-10 (0.00000000015). The letter "e" can be lowercase or uppercase with or without a plus sign (+) as a prefix.

Here are a few correct and incorrect examples of numbers in exponential format:

Dim A As Double

A = 1.43E2' Correct

A = + 1.43E2' Correct (space between plus and basic number)

A = - 1.43E2 ' Correct (space between minus and basic number)

A = 1.43E-2' Correct (negative exponent)

A = 1.43E -2' Incorrect (spaces not permitted within the number)

A = 1,43E-2' Incorrect (commas not permitted as decimal points)

A = 1.43E2.2' Incorrect (exponent must be a whole number)

Note that in the first and third incorrect examples that no error message is generated even though the variables return incorrect values. The expression

A = 1.43E -2

is interpreted as 1.43 minus 2, which corresponds to the value –0.57. However, the value 1.43 * 102 (corresponding to 0.0143) was the intended value. With the value

A = 1.43E2.2

StarOffice Basic ignores the part of the exponent after the decimal point and interprets the expression as

A = 1.43E2

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. StarOffice 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

StarOffice 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

## True and False

### Boolean Variables

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:

Dim Variable As Boolean

## Date and Time Details

### Date Variables

Date variables can contain date and time values. When saving date values, StarOffice Basic uses an internal format that permits comparisons and mathematical operations on date and time values. There is no type declaration symbol for date variables. The declaration can only be made using the supplement As Date.

Example declaration of a date variable:

Dim Variable As Date

## Data Fields

In addition to simple variables (scalars), StarOffice Basic also supports data fields (arrays). 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 brackets 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:

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.

### Specified Value for Start Index

The start index of a data field usually begins with the value 0. Alternatively, you can change the start index for all data field declarations to the value 1 by using the call:

Option Base 1

The call must be included in the header of a module if you want it to apply to all array declarations in the module. However, this call does not affect the UNO sequences that are defined through the StarOffice API whose index always begins with 0. To improve clarity, you should avoid using Option Base 1.

The number of elements in an array is not affected if you use Option Base 1, only the start index changes. The declaration

Option Base 1

' ...

Dim MyInteger(3)

creates 4 integer variables which can be described with the expressions MyInteger(1), MyInteger(2), MyInteger(3) and MyInteger(4).

In StarOffice Basic, the expression Option Base 1 does not affect the number of elements in an array as it does in VBA. It is, rather, the start index which moves in StarOffice Basic. While the declaration MyInteger(3) creates three integer values in VBA with the indexes 1 to 3, the same declaration in StarOffice Basic creates four integer values with the indexes 1 to 4.

### Multi-Dimensional Data Fields

In addition to single dimensional data fields, StarOffice Basic also supports work with multi-dimensional data fields. The corresponding dimensions are separated from one another by commas. The example

Dim MyIntArray(5, 5)

defines an integer array with two dimensions, each with 6 indexes (can be addressed through the indexes 0 to 5). The entire array can record a total of 6 × 6 = 36 integer values.

Although you can define hundreds of dimensions in StarOffice Basic Arrays; however, the amount of available memory limits the number of dimensions you can have.

### Dynamic Changes in the Dimensions of Data Fields

The previous examples are based on data fields of a specified dimension. You can also define arrays in which the dimension of the data fields dynamically changes. For example, you can define an array to contain all of the words in a text that begin with the letter A. As the number of these words is initially unknown, you need to be able to subsequently change the field limits. To do this in StarOffice Basic, use the following call:

ReDim MyArray(10)

Unlike VBA, where you can only dimension dynamic arrays by using Dim MyArray(), StarOffice 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.

Unlike VBA, where only the upper limit of the last dimension of a data field can be changed through Preserve, StarOffice 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.

## Scope and Life Span of Variables

A variable in StarOffice Basic has a limited life span and a limited scope from which it can be read and used in other program fragments. The amount of time that a variable is retained, as well as where it can be accessed from, depends on its specified location and type.

### Local Variables

Variable 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, StarOffice 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 StarOffice Basic, you must change any duplicate variable names.

### Public Domain Variables

Public domain variables are defined in the header section of a module by the keyword Dim. These variables are available to all of the modules in their library:

Module A:

Dim A As Integer

Sub Test

Flip

Flop

End Sub

Sub Flip

A = A + 1

End Sub

Module B:

Sub Flop

A = A - 1

End Sub

The value of variable A is not changed by the Test function, but is increased by one in the Flip function and decreased by one in the Flop function. Both of these changes to the variable are global.

You can also use the keyword Public instead of Dim to declare a public domain variable:

Public A As Integer

A public domain variable is only available so long as the associated macro is executing and then the variable is reset.

### 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, StarOffice 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.

Module A:

Private C As Integer

Sub Test

SetModuleA' Sets the variable C from module A

SetModuleB' Sets the variable C from module B

ShowVarA' Shows the variable C from module A (= 10)

ShowVarB' Shows the variable C from module B (= 20)

End Sub

Sub SetmoduleeA

A = 10

End Sub

Sub ShowVarA

MsgBox C' Shows the variable C from module A.

End Sub

Module B:

Private C As Integer

Sub SetModuleB

A = 20

End Sub

Sub ShowVarB

MsgBox C' Shows the variable C from module B.

End Sub

## Constants

In StarOffice 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

## Operators

StarOffice 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.

+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

MODmodule 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.

ANDAnd linking

OROr linking

XORExclusive or linking

NOTNegation

EQVEquivalent test (both parts True or False)

IMPImplication (if the first expression is true, then the second must also be true)

### 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

StarOffice Basic does not support the VBA Like comparison operator.

## Branching

Use branching statements to restrict the execution of a code block until a particular condition is satisfied.

### If...Then...Else

The most common branching statement is the If statement as shown in the following example:

If A > 3 Then

B = 2

End If

The B = 2 assignment only occurs when value of variable A is greater than three. A variation of the If statement is the If/Else clause:

If A > 3 Then

B = 2

Else

B = 0

End If

In this example, the variable B is assigned the value of 2 when A is greater than 3, otherwise B is assigned the value of 0.

For more complex statements, you can cascade the If statement, for example:

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.

### 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

End Select

## 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,

Dim I

For I = 1 To 10

' ... Inner part of loop

Next I

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.

If you want to increment the loop counter by a value other than 1 at the end of each pass, use the 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

If I = 5 Then

Exit For

End If

' ... Inner part of loop

Next I

The For Each...Next loop variant in VBA is not supported in StarOffice Basic.

### 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 variants of the Do...Loop (in the following examples, A > 10 represents any condition):

1. The Do While...Loop variant

   Do While A > 10

   ' ... loop body

   Loop

   checks whether the condition is still satisfied before every pass and only then executes the loop.

2. The Do Until...Loop variant

Do Until A > 10

' ... loop body

Loop

executes the loop until the condition is no longer satisfied.

3. The Do...Loop While variant

Do

' ... loop body

Loop While A > 10

only checks the condition after the first loop pass and terminates if this condition is satisfied.

4. The Do...Loop Until variant

Do

' ... loop body

Loop Until A > 10

also checks its condition after the first pass, but undertakes the loop until the condition is no longer satisfied.

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

While A > 10

### Programming Example: Sorting With Embedded Loops

There are many ways to use loops, for example, to search lists, return values, or execute complex mathematical tasks. The following example is an algorithm that uses to loops to sort a list by names.

Sub Sort

Dim Entry(1 To 10) As String

Dim Count As Integer

Dim Count2 As Integer

Dim Temp As String

Entry(1) = "Patty"

Entry(2) = "Kurt"

Entry(3) = "Thomas"

Entry(4) = "Michael"

Entry(5) = "David"

Entry(6) = "Cathy"

Entry(7) = "Susie"

Entry(8) = "Edward"

Entry(9) = "Christine"

Entry(10) = "Jerry"

For Count = 1 To 10

For Count2 = Count + 1 To 10

If Entry(Count) > Entry(Count2) Then

Temp = Entry(Count)

Entry(Count) = Entry(Count2)

Entry(Count2) = Temp

End If

Next Count2

Next Count

For Count = 1 To 10

Print Entry(Count)

Next Count

End Sub

The values are interchanged as pairs several times until they are finally sorted in ascending order. Like bubbles, the variables gradually migrate to the right position. For this reason, this algorithm is also known as a Bubble Sort.

## Procedures and Functions

Procedures and functions form pivotal points in the structure of a program. They provide the framework for dividing a complex problem into various sub-tasks.

### 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:

Test

### 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

' ...

Test = 123

End Function

In this example, the return value of the function is 123.

If an assignment is stopped, 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

If the specification of an explicit value is stopped, the type of the return value is assigned as variant.

### Terminating Procedures and Functions Prematurely

In StarOffice Basic, you can use the Exit Sub and Exit Function commands to terminate a procedure or function prematurely, for example, for error handling. These commands stop the procedure or function and return the program to the point at which the procedure and/or function was called up.

The following example shows a procedure which terminates implementation when the
ErrorOccured variable has the value True.

Sub Test

Dim ErrorOccured As Boolean

' ...

If ErrorOccured Then

Exit Sub

End If

' ...

End Sub

### Passing Parameters

Functions and procedures can receive one or more parameters. Essential parameters must be enclosed in brackets after the function or procedure names. The example

Sub Test (A As Integer, B As String)

End Sub

defines a procedure that expects an integer value A and a string B as parameters.

Parameters are normally passed by Reference in StarOffice 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

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 with the

Sub ChangeValue(ByVal TheValue As Integer)

TheValue = 20

End Sub

function, then the superordinate variable A remains unaffected by this change. After the call for the ChangeValue function, variable A retains the value 10.

The method for passing parameters to procedures and functions in StarOffice 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. StarOffice Basic does not support this keyword because this is already the default procedure in StarOffice Basic.

As a rule, functions and procedures in StarOffice Basic are Public. The Public and Private keywords used in VBA are not supported in StarOffice Basic.

### Optional Parameters

Functions and procedures can only be called up if all the necessary parameters are passed during the call.

StarOffice Basic lets you define parameters as optional , that is, if the corresponding values are not included in a call, StarOffice Basic passes an empty parameter. In the example

Sub Test(A As Integer, Optional B As Integer)

End Sub

the A parameter is obligatory, whereas the B parameter is optional.

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

' ... 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 option provided in VBA for defining default values for optional parameters is not supported in StarOffice Basic.

The ParamArray keyword present in VBA is not supported in StarOffice Basic.

### Recursion

Recursion is now possible in StarOffice Basic. 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.

Note that the recursion level in StarOffice Basic is limited at this time to 500.

## Error Handling

Correct handling of error situations is one of the most time-consuming tasks of programming. StarOffice Basic provides a range of tools for simplifying error handling.

### The On Error Instruction

The On Error instruction is the key to any error handling:

Sub Test

On Error Goto ErrorHandler

' ... undertake task during which an error may occur

Exit Sub

ErrorHandler:

' ... individual code for error handling

End Sub

The On Error Goto ErrorHandler line defines how StarOffice Basic proceeds in the event of an error. The Goto ErrorHandler ensures that StarOffice Basic exits the current program line and then executes the ErrorHandler: code.

### The Resume Command

The Resume Next command continues the program from the line that follows where the error occurred in the program after the code in the error handler has been executed:

ErrorHandler:

' ... individual code for error handling

Resume Next

Use the Resume Proceed command to specify a jump point for continuing the program after error handling:

ErrorHandler:

' ... individual code for error handling

Resume Proceed

Proceed:

' ... the program continues here after the error

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. For more information, see Tips for Structured Error Handling.

### Queries Regarding Error Information

In error handling, it is useful to have a description of the error and to know where and why the error occurred:

- The Err variable contains the number of errors that has occurred.

- The Error$ variable contains a description of the error.

- The Erl variable contains the line number where the error occurred.

The call

MsgBox "Error " & Err & ": " & Error$ & " (line : " & Erl & ")"

shows how the error information can be displayed in a message window.

Whereas VBA summarizes the error messages in a statistical object called Err, StarOffice Basic provides the Err, Error$, and Erl variables.

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 StarOffice Basic, this is accomplished with the On Error or Resume commands.

### Tips for Structured Error Handling

Both the definition command, On Error, and the return command, Resume, are variants of the Goto construct.

If you want to cleanly structure your code to prevent generating errors when you use this construct, you should not use jump commands without monitoring them.

Care should be taken when you use the On Error Resume Next command as this dismisses all open error messages.

The best solution is to use only one approach for error handling within a program - keep error handling separate from the actual program code and do not jump back to the original code after the error occurs.

The following is an example of an error handling procedure:

Sub Example

' Define error handler at the start of the function

On Error Goto ErrorHandler

' ... Here is the actual program code

' Deactivate error handling

On Error Goto 0

' 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 however be clearly recognized.

© 2003 Sun Microsystems, Inc.