包含在查找更多文档专项支持资源 | 以 PDF 格式下载本书 (1223 KB)
Chapter 3 The Runtime Library of StarOffice BasicThe following sections present the central functions of the runtime library. Conversion FunctionsIn many situations, circumstances arise in which a variable of one type has to be changed into a variable of another type. Implicit and Explicit Type ConversionsThe easiest way to change a variable from one type to another is to use an assignment. Dim A As String Dim B As Integer B = 101 A = B In this example, variable A is a string, and variable B is an integer. StarOffice Basic ensures that variable B is converted to a string during assignment to variable A. This conversion is much more elaborate than it appears: the integer B remains in the working memory in the form of a two-byte long number. A, on the other hand, is a string, and the computer saves a one- or two-byte long value for each character (each number). Therefore, before copying the content from B to A, B has to be converted into A's internal format. Unlike most other programming languages, Basic performs type conversion automatically. However, this may have fatal consequences. Upon closer inspection, the following code sequence 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, StarOffice Basic offers a range of conversion functions, which you can use to define when the data type of an operation should be converted: You can use these conversion functions to define how StarOffice 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) ' B and C are added together first, then
' converted (produces the number 2)
A = CStr(B) + CStr(C) ' B and C are converted into a string,then
' combined (produces string "11")
During the first addition in the example, StarOffice 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) ' Is converted correctly regardless of the
' country-specific settings
Checking the Content of VariablesIn some instances, the date cannot be converted: Dim A As String Dim B As Date A = "test" B = A ' Creates error message 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 A = "test" B = A ' Creates error message 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. StarOffice Basic provides the following test functions for this purpose: 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 StarOffice 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 error. Note – If a string in StarOffice Basic contains a non-numerical value and if this is assigned to a number, StarOffice Basic does not produce an error message, but transfers the value 0 to the variable. This procedure differs from VBA. There, an error is triggered and program implementation terminated if a corresponding assignment is executed. StringsWorking with Sets of CharactersWhen administering strings, StarOffice 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. Accessing Parts of a StringStarOffice Basic provides four functions that return partial strings:
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) ' Provides the string "This " MyResult = Right(MyString, 5) ' Provides the string " test" MyResult = Mid(MyString, 8, 5) ' Provides the string " a sm" MyLen = Len(MyString) ' Provides the value 21 Search and ReplaceStarOffice Basic provides the InStr function for searching for a partial string within another string: ResultString = InStr (SearchString, MyString) The SearchString parameter specifies the string to be searched for within MyString. The function returns a number that contains the position at which the SearchString first appears within MyString. If you want to find other matches for the string, the function also provides the opportunity to specify an optional start position from which StarOffice Basic begins the search. In this case, the syntax of the function is: ResultString = InStr(StartPosition, MyString, SearchString) In the previous examples, InStr ignores uppercase and lowercase characters. To change the search so that InStr is case sensitive, add the parameter 0, as shown in the following example: ResultString = InStr(MyString, SearchString, 0) Using the previous functions for editing strings, programmers can search for and replace one string in another string: Function Replace(Source As String, Search As String, NewPart As String)
Dim Result As String
Dim StartPos As Long
Dim CurrentPos As Long
Result = ""
StartPos = 1
CurrentPos = 1
If Search = "" Then
Result = Source
Else
Do While CurrentPos <> 0
CurrentPos = InStr(StartPos, Search, Source)
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 StarOffice Basic has been extended so that this task is performed automatically. The following example Dim MyString As String MyString = "This was my text" Mid(MyString, 6, 3, "is") replaces three characters with the string is from the sixth position of the MyString string. Formatting StringsThe 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 zero 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 period stands for the decimal point symbol defined by the operating system in the country-specific settings. The example below shows how the zero and period characters can define the digits after the decimal point in an expression: MyFormat = "0.00" MyString = Format(-1579.8, MyFormat) ' Provides "-1579,80" MyString = Format(1579.8, MyFormat) ' Provides "1579,80" MyString = Format(0.4, MyFormat) ' Provides "0,40" MyString = Format(0.434, MyFormat) ' Provides "0,43" In the same way, zeros can be added in front of a number to achieve the desired length: MyFormat = "0000.00" MyString = Format(-1579.8, MyFormat) ' Provides "-1579,80" MyString = Format(1579.8, MyFormat) ' Provides "1579,80" MyString = Format(0.4, MyFormat) ' Provides "0000,40" MyString = Format(0.434, MyFormat) ' Provides "0000,43" A comma represents the character that the operating system uses for a thousands separator, and the pound sign stands for a digit or place that is only displayed if it is required by the input string. MyFormat = "#,##0.00" MyString = Format(-1579.8, MyFormat) ' Provides "-1.579,80" MyString = Format(1579.8, MyFormat) ' Provides "1.579,80" MyString = Format(0.4, MyFormat) ' Provides "0,40" MyString = Format(0.434, MyFormat) ' Provides "0,43" In place of the dollar sign place holder, the Format function displays the relevant currency symbol defined by the system: MyFormat = "#,##0.00 $"
MyString = Format(-1579.8, MyFormat) ' Provides "-1.579,80 —"
MyString = Format(1579.8, MyFormat) ' Provides "1.579,80 —"
MyString = Format(0.4, MyFormat) ' Provides "0,40 —"
MyString = Format(0.434, MyFormat) ' Provides "0,43 —"
Note – The format instructions used in VBA for formatting date and time details are not supported in StarOffice Basic. Date and TimeStarOffice Basic provides the Date data type, which saves the date and time details in binary format. Specification of Date and Time Details within the Program CodeYou can assign a date to a date variable through the assignment of a simple string: Dim MyDate As Date MyDate = "1.1.2002" This assignment can function properly because StarOffice Basic automatically converts the date value defined as a string into a date variable. This type of assignment, however, can cause errors, date and time values are defined and displayed differently in different countries. Since StarOffice Basic uses the country-specific settings of the operating system when converting a string into a date value, the expression shown previously only functions correctly if the country-specific settings match the string expression. To avoid this problem, the DateSerial function should be used to assign a fixed value to a date variable: Dim MyVar As Date MyDate = DateSerial (2001, 1, 1) The function parameter must be in the sequence: year, month, day. The function ensures that the variable is actually assigned the correct value regardless of the country-specific settings The TimeSerial function formats time details in the same way that the DateSerial function formats dates: Dim MyVar As Date MyDate = TimeSerial(11, 23, 45) Their parameters should be specified in the sequence: hours, minutes, seconds. Extracting Date and Time DetailsThe following functions form the counterpart to the DateSerial and TimeSerial functions: These functions extract the date or time sections from a specified Date variable. The example Dim MyDate As Date ' ... Initialization of MyDate If Year(MyDate) = 2003 Then ' ... Specified date is in the year 2003 End If checks whether the date saved in MyDate is in the year 2003. In the same way, the example 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 checks whether MyTime is between 12 and 14 hours. 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" case 7 MyWeekday = "Saturday" End Select Note – Sunday is considered the first day of the week. Retrieving System Date and TimeThe following functions are available in StarOffice Basic to retrieve the system time and system date: Files and directoriesWorking with files is one of the basic tasks of an application. The StarOffice API provides you with a whole range of objects with which you can create, open and modify Office documents. These are presented in detail in Chapter 4, Introduction to the StarOffice API. Regardless of this, in some instances you will have to directly access the file system, search through directories or edit text files. The runtime library from StarOffice Basic provides several fundamental functions for these tasks. Note – Some DOS-specific file and directory functions are no longer provided in StarOffice 8, or their function is only limited. For example, support for the ChDir, ChDrive and CurDir functions is not provided. Some DOS-specific properties are no longer used in functions that expect file properties as parameters (for example, to differentiate from concealed files and system files). This change became necessary to ensure the greatest possible level of platform independence for StarOffice. Administering FilesSearching Through DirectoriesThe Dir function in StarOffice 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. StarOffice 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
NextFile = Dir
Wend
MsgBox AllFiles
End Sub
The 0 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:
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) & NextDir
NextDir = Dir
Wend
MsgBox AllDirs
End Sub
Note – When requested in StarOffice 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, StarOffice Basic behaves like VBA and the Dir function, using parameter 16, returns sub-directories and standard files. Note – 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 StarOffice Basic because the corresponding file system functions are not available on all operating systems. Note – The path specifications listed in Dir may use the * and ? place holders in both VBA and StarOffice Basic. In StarOffice 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. Creating and Deleting DirectoriesStarOffice Basic provides the MkDir function for creating directories. MkDir ("C:\SubDir1") This function creates directories and sub-directories. All directories needed within a hierarchy are also created, if required. For example, if only the C:\SubDir1 directory exists, then a call MkDir ("C:\SubDir1\SubDir2\SubDir3\")
creates both the C:\SubDir1\SubDir2 directory and the C:\SubDir1\SubDir2\SubDir3 directory. The RmDir function deletes directories. RmDir ("C:\SubDir1\SubDir2\SubDir3\") If the directory contains sub-directories or files, these are also deleted. You should therefore be careful when using RmDir. Note – In VBA, the MkDir and RmDir functions only relate to the current directory. In StarOffice Basic on the other hand, MkDir and RmDir can be used to create or delete levels of directories. Note – In VBA, RmDir produces an error message if a directory contains a file. In StarOffice Basic, the directory and all its files are deleted. If you use the CompatibilityMode ( true ) function, StarOffice Basic will behave like VBA. Copying, Renaming, Deleting and Checking the Existence of FilesFileCopy(Source, Destination) creates a copy of the Source file under the name of Destination. Name OldName As NewName you can rename the OldName file with NewName. The As keyword syntax, and the fact that a comma is not used, goes back to the roots of the Basic language. Kill(Filename) deletes the Filename file. If you want to delete directory (including its files) use the RmDir function. The FileExists function can be used to check whether a file exists: If FileExists(Filename) Then MsgBox "file exists." End If Reading and Changing File PropertiesWhen working with files, it is sometimes important to be able to establish the file properties, the time the file was last changed and the length of the file. Dim Attr As Integer Attr = GetAttr(Filename) returns some properties about a file. The return value is provided as a bit mask in which the following values are possible:
The example Dim FileMask As Integer
Dim FileDescription As String
FileMask = GetAttr("test.txt")
If (FileMask AND 1) > 0 Then
FileDescription = FileDescription & " read-only "
End IF
If (FileMask AND 16) > 0 Then
FileDescription = FileDescription & " directory "
End IF
If FileDescription = "" Then
FileDescription = " normal "
End IF
MsgBox FileDescription
determines the bit mask of the test.txt file and checks whether this is read-only whether it is a directory. If neither of these apply, FileDescription is assigned the "normal" string. Note – The flags used in VBA for querying the concealed, system file,archived and volume name file properties are not supported in StarOffice 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 call SetAttr("test.txt", 1)
can therefore be used to provide a file with read-only status. 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
Writing and Reading Text FilesStarOffice Basic provides a whole range of methods for reading and writing files. The following explanations relate to working with text files (not text documents). Writing Text FilesBefore a text file is accessed, it must first be opened. To do this, a free file handle is needed, which clearly identifies the file for subsequent file access. The FreeFile function is used to create a free file handle. The handle is used as a parameter for the Open instruction, which opens the file. To open a file so that it can be specified as a text file, the Open call is: Open Filename For Output As #FileNo Filename is a string containing the name of the file. FileNo is the handle created by the FreeFile function. Once the file is opened, the Print instruction can be described line by line: Print #FileNo, "This is a test line." 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" ' Define file name FileNo = Freefile ' Establish free file handle 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 Reading Text FilesText files are read in the same way that they are written. The Open instruction used to open the file contains the For Input expression in place of the For Output expression and, rather than the Print command for writing data, the Line Input instruction should be used to read the data. Finally, when calling up a text file, the instruction eof(FileNo) is used to check whether the end of the file has been reached. The following example shows how a text file can be read in: Dim FileNo As Integer
Dim CurrentLine As String
Dim File As String
Dim Msg as String
' 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
Do While not eof(FileNo)
' Read line
Line Input #FileNo, CurrentLine
If CurrentLine <>"" then
Msg = Msg & CurrentLine & Chr(13)
end if
Loop
' 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. Message and Input BoxesStarOffice Basic provides the MsgBox and InputBox functions for basic user communication. Displaying MessagesMsgBox displays a basic information box, which can have one or more buttons. In its simplest variant MsgBox "This is a piece of information!" the MsgBox only contains text and an OK button. 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:
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.
Finally, the following information symbols are available and can also be displayed by adding the relevant parameter values:
The call MsgBox "Do you want to continue?", 292 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 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:
In the previous example, checking the return values could be as follows: If MsgBox ("Do you want to continue?", 292) = 6 Then
' Yes button pressed
Else
' No button pressed
End IF
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" If no box title is specified, the default is “soffice”. Input Box For Querying Simple StringsThe InputBox function queries simple strings from the user. It is therefore a simple alternative to configuring dialogs. InputBox receives three standard parameters:
InputVal = InputBox("Please enter value:", "Test", "default value")
As a return value, the InputBox provides the string typed by the user. Other functionsBeepThe 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 ShellExternal 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:
The third parameter, Param, permits command line parameters to be transferred to the program to be started. WaitThe 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). EnvironThe Environ function returns the environmental variables of the operating system. Depending on the system and configuration, various types of data are saved here. The call Dim TempDir
TempDir=Environ ("TEMP")
determines the environment variables of temporary directory of the operating system. |