You are on page 1of 2

LibORef no2

LibreOffe RefCard
Empty, Null And Nothing
LibreOfice Basic Empty Uninitialized variable yet. Empty assignation possible.

Overview Null
Nothing
Invalid contents. Null assignation possible.
(objects only) No (more) reference to the object. Assignation possible.
Functions
Beginner
IsEmpty(SomeVar) Variable is empty.
v. 2.0 – 04/20/2019
IsNull(SomeObject) Unusable data.
Writen using LibreOffe v. 5.3.3 – Platform: All Operators
Booleans
Overview
Not Not And And Or Or (inclusive) Xor Exclusive or
☞ Development time: Coding 20% – Maintaining 80% Comparisons (return True Or False)
Entities Naming = Strictly equal < Strictly lower <= Lower or equal
Variables, constants, subs, functions, modules and libraries must be identified. <> Different > Strictly upper >= Upper or equal
Allowed chars: unaccented chars, numbers, underscore (_).  Beware to floating numbers comparisons!
☞ An identifier can’t start with a number nor contain a space. Numerical
 Do not use any Basic keyword to name an entity! + Addition * Multiplication \ Integer division
Easy to read names CamelCase, Name_with_separators - Subtraction / Division Mod Modulo (remainder of
Explicit names IsCell(), SaveSpreadsheet() integer division)
Comments ^ Raising to the power
' (apostrophe) or REM. What follows is a comment. Text
☞ Comments are as important as code! They apply to the current line only. & Strings concatenation (fusion) (“ + ” is possible ; better not use).
Code Indent Constants
Indented code is easier to read. Indent each block level with Space / Tabulation . Constant: a memory place; fixed value (immutable during execution).
Several Instructions On The Same Line Declaring Constants
Use the “:” character (semicolon) to separate instructions on the same line: Const SOME_CONSTANT = SomeValue
Dim MyVar As Integer : MyVar = 123 ☞ SomeValue must be a simple type: no array, no object.
Continuing An Instruction On The Next Line Naming Constants
Last two chars or the first line: _ (space + underscore). It is frequent to name constants in all UPPERCASE.
Variables Constants Visibility
Variable : a memory place. A variable contents may be modified at run-time. Declaring… gives visibility…
Const MYCONST = SomeValue In the current subprogram or module.
 By default, variable declares are not mandatory but this is dangerous (typos lead to
double declares). Public MYCONST = SomeValue In the current library.
Adding Option Explicit on top of a module forces variable declaration. Global MYCONST = SomeValue In all libraries.
Declaring Variables File Paths
Simple Variables To ensure multi-platform compliance, file paths are often expressed using the URL for-
Dim MyVar As AType Ex : Dim MyText As String mat : file:///support/path/to/afile.txt instead of the native OS format.
Dim A As Byte, B As String (multiple declares) Two functions allow to switch from one to the other representation:
Dim MaVar As Integer : MaVar = 123 (declare + initialize) From OS native to URL URLname = ConvertToURL(NativeName)
Array Variables From URL to OS native NativeName = ConvertFromURL(URLname)
☞ See RefCard #9 “Structured Types” Example (Windows)
Setting Non-Object Variables Native name: C:\MyDir\File.odt
MyVar = SomeValue URL name: file:///C:/MyDir/File.odt
☞ Basic often automatically typecasts when SomeValue is not of the same type as ☞ The URL format
MyVar. Prefer explicit typecasts using the CXxx() functions (RefCard #5). An URL (Uniform Resource Locator) stores a document or an internet server address.
The URL structure is: service://host_name:port/path/to/page#mark
Creating/Setting Object Variables (some items could be omitted). An URL could be a FTP address, internet address
☞ See RefCard #9 “Structured Types” (HTTP), file address or email address.
Variables Visibility Subprograms
Declaring… gives visibility…  Ensure arguments ↔ parameters correspondence, in number and type.
Dim MyVar As AType In the current subprogram or module. ☞ Premature subprogram exit: Exit Sub, Exit Function
Static MyVar As AType In the current subprogram.
☞ Persistent value between calls. Sub
Private MyVar As AType In the current module. Executes an action.
Public MyVar As AType In the current library.  Naming hint: verb at the infinitive: DoXxx(), etc.
Global MyVar As AType In all libraries. Declaration Sub SubName(parameters)
 Persistent value between programs! Structure Sub SubName(parameters)
'instructions
Types End Sub
Specifies the value set a variable can carry or a function return. Use SubName(arguments). If no argument: SubName()
Predefined Simple Types Function
Returns a value.
Type name Description Initzed to
 Naming hint: verb at the indicative: IsXxx(), etc.
Boolean Logical values True / False. False
Declaration Function FuncName(parameters) As SomeType
☞ Can be seen as False = 0 ; True = other integers (-1). Function FuncName(parameters) As SomeType
Byte 0
Structure
Integer numbers (8 bits), from 0 to 255. 'instructions
Currency Currency numbers (4 decimals). 0.0000 'somewhere, define the return value:
(Decimal) Variant subtype, returned by CDec(string) n/a FuncName = SomeValue
End Function
28 digits (int. part + dec. part). From 1 x 10-28 to 7,9 x 1028
Use SomeVar = FuncName(arguments)
(max precision 28 decimals).
If no argument: SomeVar = FuncName()
☞ Used with API functions that use 64bits integers.
☞ A Function may be called like a Sub (without caring of the return value).
 Overflow does not create any runtime error.
Date Dates and hours. In fact, doubles. 0.0
Parameters
Reference date (0.0) is 12/30/1899 at 00:00. Parameter a value the subprogram declaration specifies.
Double Floating numbers (64 bits). 0.0 Argument the actual value the caller passes to the subprogram.
Integer Integer numbers (16 bits), from -32 768 to +32 767. 0 Usage
Long 32bits int numbers, -2 147 483 648 to +2 147 483 647. 0 Ex : MySub(ByRef AParam as Long, ByVal OtherParam As String, _
Object Objects. Allow to manipulate LibreOffice API objects. Null Optional ByRef SomeParam As Object)
Single Floating numbers (32 bits). 0.0 ByRef By reference (default). The parameter points to the argument passed by the
String Text (0 to 65 545 characters). "" (null caller.
In code, strings are delimited with " (double quotes). length)  Any modification of a ByRef item is propagated to the caller on exit.
Variant Any type, incl. object. Empty ByVal By value. The parameter is a copy of the argument passed by the caller.
See also the Main types compatibility chart. ☞ Value modifications are local to the called and not propagated to the caller.
☞ Every time a type is unspecified, Variant is implicit. Optional Optional parameter.
☞ Integer values may be specified in hexadecimal base. ☞ Test the parameter absence using If IsMissing(SomeParam) Then …
Prefix these values using &H. Ex : &HFF (decimal 255). Useful for colors. The identifier is always available in the subprogram.
☞ Always set initial values rather than rely upon implicit settings.  Giving a default value to an optional parameter:
 Beware to rounding errors when using floating numbers! If IsMissing(SomeParam) Then SomeParam = SomeValue
Arrays, Custom Types, Collections And Objects
☞ See RefCard #9 “Structured Types”

LibOBasic_02_Overview_Flat_A4_EN_v200.odt
Control Structures Error Management
Loops In Basic, error management relies upon:
Repeat a sequence of instructions. • On Error Xxx (and On Local Error Xxx) instructions for error interception.
☞ Premature exit possible using Exit For or Exit Do according to situation. • the Err, Erl and Error functions to get information about the last error met.
For … Next Error Information Functions
For each index value … You must know the counter bounds. Err The error code.
For i = Start To End [Step By default, increment Step is 1. ☞ An error code of 0 (zero) means “no error”.
Increment] Use If Err Then … to check for error presence.
'instructions ☞ Indices are often named as i, j, k, etc.
Error The message that describes the error.
Next i  Never set the counter in the loop instructions!
Erl The line number where the error occurred.
For Each … Next
On Error – Globally Intercepting Errors
For each item … The number of items is unknown.
For Each item In SomeObject item must be of a compatible type.  Error interception using OnError is active as long as it has not been canceled.
'do smthg with item On Error Goto MyLabel Activates error interception. If an error occurs, the
Next execution continues to MyLabel.
Do While … Loop ☞ In the program body, you must define the label
Do While Condition Condition is evaluated first. MyLabel: (beware to the semicolon character).
'instructions  Infinite loops (Condition never met)!
Loop On Error Resume Next Activates error interception. If an error occurs, the
or… execution continues to the next instruction.
While Condition ☞ Older syntax, for compatibility only. Doesn’t sup- On Error Goto 0 Cancels error interception.
'instructions port Exit. On Local Error – Locally Intercepting Errors
Wend Do not use! In a subprogram, you might prefer the On Local Error Xxx syntax. This doesn’t re-
Do Loop ... Until quires calling On Error Goto 0 to cancel error interception: canceling is automatically
Do Condition is evaluated last.
'instructions performed when leaving the Sub or Function.
Loop Until Condition
 Infinite loops (Condition never met)! ☞ On Local Error Goto Xxx has precedence upon an existing On Error Goto Xxx.
Conditional Tests Different Ways Of Running A Macro
A branch that allows to take action according to a given state/situation.
▼ Method LibreOffice Document Type Current Document
If (alone)
If Condition Then SomeInstruction Using a toolbar button ● ●
Using a menu ● ●
If Then [Else] Using a shortcut ● ●
If Condition Then The Else condition is not mandatory.
'InstructionsThen Through an event ● ●
Else Main Types Compatibility Chart
'InstructionsElse
End If

Currency

Boolean
Decimal
Target ▶

Double
Integer

Variant
If ElseIf

Object
Single

String
Long

Date
If Condition Then Instead of nested Ifs.
'InstructionsThen1 Source ▼
ElseIf OtherCondition Then
'InstructionsThen2
Else Integer ● ● ● ● ● ● ● ● x ● ●
'InstructionsElse
End If Long ! ● ● ● ● ● ● ● x ● ●
Select
Select Case SomeVariable Choose among several possibilities, Single ○! ○! ● ● ● ● ● ● x ! ●
Case Value : DoThat() according to SomeVariable actual
Case Value1, Value2 Double ○! ○! ○! ● ● ● ● ● x ! ●
'instructions for SomeValue value.
Case Value3 To Value4 Currency ○! ○! ! ● ● ● ○ ● x ! ●
'instructions for OtherValue
Case Else Decimal ○! ○! ○! ○ ○! ● ○ ● x ○! ●
'instructions for other situations
End Select Date ○! ○! ! ● ● ○! ● ● x ! ●
Loading A Code Library
String ○! ○! ○! ○! ○! ● ○! ● x ○! ●
For readability and maintainability, organize your code in several libraries (RefCard #1).
☞ The Standard code library is the only loaded library at document opening. Other li- Object x x x x x x x x ● x ●
braries must be explicitly loaded to gain access to their code.
 Library names are case sensitive! Boolean ● ● ● ● ● ● ● ● x ● ●
Loading From The Local Container (document) Variant ○! ○! ○! ○! ○! ● ○! ○! ● ○! ●
Checking existence LibExists = BasicLibraries.hasByName("MyLib")
Loading BasicLibraries.loadLibrary("MyLib") Compatibility
Loading From A Global Container ● compatible ○ possible loss ! possible overflow x not compatible
Reading The Chart
Same as above but BasicLibraries is replaced with GlobalScope.BasicLibraries.
• You may assign a source variable contents of type Double to a target variable of any
 Mind to identifiers collisions between libraries! You may qualify names using:
container.library.module.name (all or part). of the Double, Currency, Date, and Variant types, without data loss.
Ex: GlobalScope.Tools.Strings.ClearMultiDimArray(MyArray, 3) • A target variable of type Double may lossless receive values of types Integer, Long,
Single, Double, Date and Byte.
Calling A Command Associated With A LibreOffice Menu
101
Use the Dispatcher, and pass it the wanted UNO menu command.
Knowing UNO Menus Commands
UNO menu commands: see the menubar.xml files in the LibreOffice installation directory
(OS specific), under share/config/soffice.cfg/modules. Subdir menubar of the
wanted module (eg: sglobal/menubar/menubar.xml, etc.).
All commands start with .uno:
Credits
Ex : ".uno:Open" (File > Open), ".uno:OptionsTreeDialog" (Tools > Options), etc.
Author : Jean-François Nifenecker – jean-francois.nifenecker@laposte.net
Program Skeleton We are like dwarves perched on the shoulders of giants, and thus we are able to see more and farther than the
latter. And this is not at all because of the acuteness of our sight or the stature of our body, but because we are
Dim Frame As Variant
carried aloft and elevated by the magnitude of the giants (Bernard de Chartres [attr.])
Dim Dispatch As Object
Dim Args() As Variant 'contents depends upon context History
Dim UnoCmd As String Version Date Comments
Frame = ThisComponent.CurrentController.Frame
UnoCmd = 'UNO command to run (above) 2.0 04/20/2019 Restructure (some types moved to new RefCard #9)
Dispatch = createUnoService("com.sun.star.frame.DispatchHelper")
Dispatch.executeDispatch(Frame, UnoCmd, "", 0, Args())
where UnoCmd is the command found in the files above.
Exemples
(only modified parts are shown)
Ex1. Calling Print Preview
Dispatch.executeDispatch(Frame, ".uno:PrintPreview", "", 0, Args())
Ex2. Showing/Hiding The Sidebar License
Dim Args(0) As New com.sun.star.beans.PropertyValue This refcard is placed under the
Args(0).Name = "Sidebar" CreativeCommons BY-SA v4 (intl) license.
Args(0).Value = True 'or False depending on aim
Dispatch.executeDispatch(Frame, ".uno:Sidebar", "", 0, Args()) More information:
https://creativecommons.org/licenses/by-sa/4.0/

You might also like