0% found this document useful (0 votes)
135 views2 pages

Libreofice Basic: Libreoffe Refcard

LibreOffice offers many classes (aka services) to manipulate documents and their components. An object is an instance of a service that contains properties (state) and methods (actions). Variables can be simple types like strings and numbers, arrays which allow multiple values in a single variable, or custom types defined with a Type statement. Comments are important for documenting code and applying to a single line using an apostrophe or REM.

Uploaded by

Eugene Step
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
135 views2 pages

Libreofice Basic: Libreoffe Refcard

LibreOffice offers many classes (aka services) to manipulate documents and their components. An object is an instance of a service that contains properties (state) and methods (actions). Variables can be simple types like strings and numbers, arrays which allow multiple values in a single variable, or custom types defined with a Type statement. Comments are important for documenting code and applying to a single line using an apostrophe or REM.

Uploaded by

Eugene Step
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

LibORef no2

LibreOffe RefCard
Type name Description Initialized to
LibreOfice Basic Object
Single
Objects. Allow to manipulate LibreOffice API objects.
Floating numbers (32 bits).
Null
0.0

Overview String Text (0 to 65 545 characters).


In code, strings are delimited with " (double quotes).
"" (null
length)
Variant Any type, incl. object. Empty
Beginner ☞ Every time a type is unspecified, Variant is implicit.
v. 1.10 – February 11, 2018
☞ Always set initial values rather than rely upon implicit settings.
Writen using LibreOffe v. 5.3.3 – Platform: All Custom Types
Type MyType where AType can be any simple or custom
member1 As AType
Overview member2 As AType type.
☞ Development time: Coding 20% – Maintaining 80% 'etc.
End Type
Entities Naming ☞ A custom type may only be referenced in the module where it is declared. This code is
Variables, constants, subs and functions must be identified. not possible elsewhere: Dim MyVar As New MyType
Allowed chars: unaccented chars, numbers, underscore ( _). To create a var of this type in any other module, create a function that realizes the cre-
ation, within the same module as the type declaration. You then call that creation func-
☞ An identifier can’t start with a number nor contain a space. tion in order to create an instance of that type:
 Do not use any Basic keyword to name an entity! Function CreateMyType() As MyType
Easy to read names CamelCase, Name_with_separators Dim Result As New MyType
Explicit names IsCell(), SaveSpreadsheet() CreateMyType = Result
Comments End Function
Usage elsewhere (other modules):
' (apostrophe) or REM. What follows is a comment. Dim MyVar As Object
☞ Comments are as important as code! They apply to the current line only. MyVar = CreateMyType()
Code Indent Objects
Indented code is easier to read. Indent each code level with Space / Tabulation . LibreOffice offers many classes (aka services) to manipulate documents and their com-
Continuing An Instruction On The Next Line ponents. Service = Properties + Methods. An object is an instance of a service.
Last two chars or the first line: _ (space + underscore). Property State (≈ variable) Method Action (≈ subprogram)
Syntax: object.SomeProperty or object.SomeMethod.
Variables
 By default, variable declares are not mandatory but this is dangerous (typos lead to
Empty, Null And Nothing
double declares). Empty Uninitialized variable yet. Empty assignation possible.
Adding Option Explicit on top of a module forces variable declaration. Null Invalid contents. Null assignation possible.
Declaring Variables Nothing (objects only) No (more) reference to the object. Assignation possible.
Variable : a memory place. A variable contents may be modified at run-time. Functions
Simple Variables IsEmpty(SomeVar) Variable is empty.
Dim MyVar As AType Ex : Dim MyText As String IsNull(SomeObject) Unusable data.
Arrays Operators
 Array indices are zero-based!
Booleans
Dim MyArray(NumDim) As AType Number of dimensions : any.
Not Not And And
Dim MyArray(2,4) : 2 dimensions. 3 items for
Or Or (inclusive) Xor Exclusive or
the 1st, 5 for the 2nd (base 0).
Dim MyArray(9) As AType Declares a 1-dim array with 10 items (base 0). Comparisons (return True Or False)
Declares an array of unknown dimension. Calling = Strictly equal < Strictly lower <= Lower or equal
Dim MyArray() As AType
Dim MyArray As Variant } ReDim will be required. <> Different > Strictly upper >= Upper or equal
Accessing Arrays Items  Mind to floating numbers comparisons!
MyArray(1, 3) = Value Sets Value to item 1, 3. Numerical
Inf = LBound(MyArray()[, n]) Lower bound [for dimension n]. + Addition * Multiplication \ Integer division
Sup = UBound(MyArray()[, n]) Upper bound [for dimension n]. - Subtraction / Division Mod Modulo (remainder of
Redimensioning integer division)
ReDim MyArray(NewDim) With data loss. ^ Raising to the power
ReDim Preserve MyArray(NewDim) Without data loss. Text
Emptying Erase(MyArray) or use ReDim with data loss. & Strings concatenation (fusion) (“ + ” is possible ; better not use because of its
Test If Empty IsEmpty = (LBound(MyArray) = 0) And (UBound(MyArray) = -1) ambiguity).
Test If Exists Exists = Not IsNull(MyArray) And Not IsEmpty(MyArray)
Setting Non-Object Variables Constants
MyVar = SomeValue Constant: a memory place; fixed value (immutable during execution).
☞ Basic often automatically typecasts when SomeValue is not of the same type as Declaring Constants
MyVar. Prefer typecasting explicitly using dedicated functions ( CXxx(), RefCard #5).
Const SOME_CONSTANT = SomeValue
Creating/Setting Object Variables ☞ SomeValue must be a simple type: no array, no object.
Dim MyObject As New AClass Naming Constants
MyObject = New AClass }Initialization differed to the 1st setting. It is frequent to name constants in all UPPERCASE.
Set MyObjet = AClass Initialization is immediate
Variables Visibility Constants Visibility
Declaring… gives visibility… Declaring… gives visibility…
Const MYCONST = SomeValue In the current subprogram or module.
Dim MyVar As AType In the current subprogram or module.
Static MyVar As AType Public MYCONST = SomeValue In the current library.
In the current subprogram.
Global MYCONST = SomeValue In all libraries.
☞ Persistent value between calls.
Private MyVar As AType In the current module. File Paths
Public MyVar As AType In the current library. To ensure multi-platform compliance, file paths are often expressed using the URL for-
Global MyVar As AType In all libraries. mat : file:///support/path/to/afile.txt instead of the native OS format.
 Persistent value between programs!
Two functions allow to switch from one to the other representation:
Type From OS native to URL URLname = ConvertToURL(NativeName)
From URL to OS native NativeName = ConvertFromURL(URLname)
Specifies the value set a variable can carry or a function return.
Predefined Types Subprograms
Type name Description Initialized to  Ensure arguments ↔ parameters correspondence, in number and type.
Boolean Logical values True / False. False ☞ Premature subprogram exit: Exit Sub, Exit Function
☞ Can be seen as False = 0 ; True = other integers (-1). Sub
Byte Integer numbers (8 bits), from 0 to 255. 0 Executes an action.
Currency Currency numbers (4 decimals). 0.0000  Naming hint: verb at the infinitive: DoXxx(), etc.
Date Dates and hours. In fact, doubles. 0.0 Declaration Sub SubName(parameters)
Reference date (0.0) is 12/30/1899 at 00:00. Sub SubName(parameters)
Double Floating numbers (64 bits). 0.0 Structure
'instructions
Integer Integer numbers (16 bits), from -32 768 to +32 767. 0 End Sub
Long 32bits int numbers, -2 147 483 648 to +2 147 483 647. 0 Use SubName(arguments). If no argument: SubName()

LibOBasic-2-Overview-Flat-Letter-EN-v110.odt
Function Calling A Command Associated With A LibreOffice Menu
Executes an action and returns a value. 101
 Naming hint: verb at the indicative: IsXxx(), etc.
Use the Dispatcher, and pass it the wanted UNO menu command.
Declaration Function FuncName(parameters) As SomeType
Function FuncName(parameters) As SomeType Knowing UNO Menus Commands
Structure
'instructions UNO menu commands: see the menubar.xml files in the LibreOffice installation directory
'somewhere, define the return value: (OS specific), under share/config/soffice.cfg/modules. Subdir menubar of the
FuncName = SomeValue
End Function wanted module (eg: sglobal/menubar/menubar.xml, etc.).
Use SomeVar = FuncName(arguments) All commands start with .uno:
If no argument: SomeVar = FuncName() Ex : ".uno:Open" (File > Open), ".uno:OptionsTreeDialog" (Tools > Options), etc.
☞ A Function may be called like a Sub (without caring of the return value). Program Skeleton
Parameters Dim Frame As Variant
Parameter : a value the subprogram declaration specifies. Dim Dispatch As Object
Argument : the actual value the caller passes to the subprogram. Dim Args() As Variant 'contents depends from context
Dim UnoCmd As String
Ex : MySub(ByRef AParam as Long, ByVal OtherParam As String, _ Frame = ThisComponent.CurrentController.Frame
Optional ByRef SomeParam As String) UnoCmd = 'UNO command to run (above)
ByRef By reference (default). The parameter points to the argument passed by the Dispatch = createUnoService("com.sun.star.frame.DispatchHelper")
Dispatch.executeDispatch(Frame, UnoCmd, "", 0, Args())
caller.
☞ Any modification of a ByRef item is propagated to the caller at return time. where UnoCmd is the command found in the files above.
ByVal By value. The parameter is a copy of the argument passed by the caller. Exemples
☞ Value modifications are local to the called and not propagated to the caller. (only modified parts are shown)
Optional Optional parameter.
Ex1. Calling Print Preview
 Giving a default value to an optional parameter:
If IsMissing(SomeParam) Then SomeParam = SomeValue Dispatch.executeDispatch(Frame, ".uno:PrintPreview", "", 0, Args())
☞ The identifier is always available in the subprogram.
Ex2. Showing/Hiding The Sidebar
Control Structures Dim Args(0) As New com.sun.star.beans.PropertyValue
Loops Args(0).Name = "Sidebar"
Args(0).Value = True 'or False depending on aim
Repeat a sequence of instructions. Dispatch.executeDispatch(Frame, ".uno:Sidebar", "", 0, Args())
☞ Premature exit possible using Exit For or Exit Do according to situation.
For … Next Error Management
For each counter value … You must know the counter bounds. In Basic, error management is available using:
For i = Start To End [Step By default, increment Step is 1. • On Error Xxx : instructions for error interception;
Increment]
'instructions ☞ Counters are often named as i, j, k, etc. • Err, Erl and Error : functions to get information about the last error met.
Next  Never set the counter in the loop instructions! Error Information Functions
For Each … Next Err The error code.
For each item … The number of items is unknown. ☞ An error code of 0 (zero) means “no error”.
For Each item In SomeObject item must be of a compatible type. Use If Err Then … to check error presence.
'do smthg with item Error
Next The message that describes the error.
Erl The line number where the error occurred.
Do While … Loop
☞ You may create custom errors by setting a value to Err :
Do While Condition Condition is evaluated first. Err = 1234 generates error 1234.
'instructions  Infinite loops (Condition never met)!
Loop On Error – Intercepting Errors
or…  Error interception is active as long as it has not been canceled.
While Condition ☞ Older syntax, for compatibility only. Doesn’t sup- On Error Goto MyLabel Activates error interception. If an error occurs, the
'instructions port Exit.
Wend execution continues to MyLabel.
Do not use!
☞ In the program body, you must define the label
Do Loop ... Until MyLabel: (beware to the semicolon character).
Do Condition is evaluated last. On Error Resume Next Activates error interception. If an error occurs, the
'instructions  Infinite loops (Condition never met)! execution continues to the next instruction.
Loop Until Condition On Error Goto 0 Cancels error interception.
Conditional Tests ☞ In a Sub or Function, you might prefer the On Local Error Xxx syntax. This doesn’t
A branch that allows to take action according to a given situation. requires calling On Error Goto 0 to cancel error interception: canceling is automati-
If (alone) cally performed when leaving the Sub or Function.
☞ On Local Error Goto Xxx has precedence on any preexisting On Error Goto
If Condition Then SomeInstruction
Xxx.
If Then Else
If Condition Then Different Ways Of Running A Macro
'InstructionsThen ▼ Method LibreOffice Document Type Current Document
Else
'InstructionsElse Using a toolbar button ● ●
End If Using a menu ● ●
If ElseIf Using a shortcut ● ●
If Condition Then Instead of nested Ifs. Through an event ● ●
'InstructionsThen1
ElseIf OtherCondition Then
'InstructionsThen2
Else
'InstructionsElse
End If Credits
Select Author : Jean-François Nifenecker – [email protected]
Select Case SomeVariable Choose among several possibilities, We are like dwarves perched on the shoulders of giants, and thus we are able to see more and farther than the
Case Value1, Value2 according to SomeVariable actual latter. And this is not at all because of the acuteness of our sight or the stature of our body, but because we are
'instructions for SomeValue carried aloft and elevated by the magnitude of the giants (Bernard de Chartres [attr.])
Case Value3 To Value4 value.
History
'instructions for OtherValue
Case Else Version Date Comments
'instructions for other situations
End Select 1.10 02/11/2018 First EN version
Loading A Code Library
For readability and maintainability, organize your code in several libraries (RefCard #1).
☞ The Standard code library is the only loaded library at document opening. Others must
be explicitly loaded to gain access to their code.
 Library names are case sensitive!
Loading From The Local Container (document)
Checking existence LibExists = BasicLibraries.hasByName("MyLib")
Loading BasicLibraries.loadLibrary("MyLib")
License
Loading From A Global Container This refcard is placed under the
Same as above but BasicLibraries is replaced with GlobalScope.BasicLibraries. CreativeCommons BY-SA v4 (intl) license.
 Mind to identifiers collisions between libraries! You may qualify names using: More information:
container.library.module.name (all or part). https://creativecommons.org/licenses/by-sa/4.0/
Ex: GlobalScope.Tools.Strings.ClearMultiDimArray(MyArray, 3)

You might also like