LibORef no2

LibreOffe RefCardEmpty, Null And Nothing

LibreOfice BasicEmpty
NullNothingOverview
v. 2.0 – 04/20/2019

Beginner

Writen using LibreOffe v. 5.3.3 – Platform: All

Uninitialized variable yet. Empty assignation possible.
Invalid contents. Null assignation possible.
(objects only) No (more) reference to the object. Assignation possible.

Functions
IsEmpty(SomeVar)
IsNull(SomeObject)

Variable is empty.
Unusable data.

Operators
Booleans

Overview☞ Development time: Coding 20% – Maintaining 80%

Entities Naming
Variables, constants, subs, functions, modules and libraries must be identified.
Allowed chars: unaccented chars, numbers, underscore (_).
☞ An identifier can’t start with a number nor contain a space.
 Do not use any Basic keyword to name an entity!
CamelCase, Name_with_separators
Easy to read names
IsCell(), SaveSpreadsheet()
Explicit names

CommentsNot Not

Or Or (inclusive) Xor Exclusive or
And AndComparisons (return True Or False)= Strictly equal< Strictly lower<= Lower or equal<> Different> Strictly upper>= Upper or equal Beware to floating numbers comparisons!

Numerical+-Addition
Subtraction*/^

Raising to the power

MultiplicationDivision\ModInteger division
Modulo (remainder ofinteger division)' (apostrophe) or REM. What follows is a comment.

Text☞ Comments are as important as code! They apply to the current line only.

&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
Use the “:” character (semicolon) to separate instructions on the same line:

Strings concatenation (fusion) (“ + ” is possible ; better not use).

Declaring Constants

Dim MyVar As Integer : MyVar = 123

Const SOME_CONSTANT = SomeValue☞ 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.
 By default, variable declares are not mandatory but this is dangerous (typos lead todouble declares).
Adding Option Explicit on top of a module forces variable declaration.

Const MYCONST = SomeValue
Public MYCONST = SomeValue
Global MYCONST = SomeValue

Dim MyVar As AType
Dim A As Byte, B As String
Dim MaVar As Integer : MaVar = 123

Ex : Dim MyText As String(multiple declares)(declare + initialize)

Array Variables☞ See RefCard #9 “Structured Types”

Setting Non-Object Variables
MyVar = SomeValue☞ Basic often automatically typecasts when SomeValue is not of the same type as
MyVar. Prefer explicit typecasts using the CXxx() functions (RefCard #5).

Creating/Setting Object Variables☞ See RefCard #9 “Structured Types”

Variables Visibility
Dim MyVar As AType
Static MyVar As AType

Private MyVar As AType
Public MyVar As AType
Global MyVar As ATypegives visibility…
In the current subprogram or module.
In the current library.
In all libraries.

File Paths

Declaring Variables
Simple Variables

Declaring…

Declaring…

To ensure multi-platform compliance, file paths are often expressed using the URL format : file:///support/path/to/afile.txt instead of the native OS format.
Two functions allow to switch from one to the other representation:
URLname = ConvertToURL(NativeName)
From OS native to URL
NativeName = ConvertFromURL(URLname)
From URL to OS native
Example (Windows)
Native name: C:\MyDir\File.odt
URL name:
file:///C:/MyDir/File.odt☞ The URL format
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(some items could be omitted). An URL could be a FTP address, internet address(HTTP), file address or email address.

Subprograms
gives visibility…
In the current subprogram or module.
In the current subprogram.
☞ Persistent value between calls.
In the current module.
In the current library.
In all libraries.
 Persistent value between programs!

 Ensure arguments ↔ parameters correspondence, in number and type.
☞ Premature subprogram exit: Exit Sub, Exit Function

Sub
Executes an action.
 Naming hint: verb at the infinitive: DoXxx(), etc.

Declaration
Structure

Types
Specifies the value set a variable can carry or a function return.

Predefined Simple Types
Description
Initzed toFalse
Logical values True / False.
☞ Can be seen as False = 0 ; True = other integers (-1).
Byte0Integer numbers (8 bits), from 0 to 255.
Currency
0.0000Currency numbers (4 decimals).
(Decimal)n/aVariant subtype, returned by CDec(string)
28 digits (int. part + dec. part). From 1 x 10-28 to 7,9 x 1028
(max precision 28 decimals).
☞ Used with API functions that use 64bits integers.
 Overflow does not create any runtime error.
Date0.0Dates and hours. In fact, doubles.
Reference date (0.0) is 12/30/1899 at 00:00.
Double0.0
Floating numbers (64 bits).
Integer0Integer numbers (16 bits), from -32 768 to +32 767.
Long32bits int numbers, -2 147 483 648 to +2 147 483 647. 0Object
NullObjects. Allow to manipulate LibreOffice API objects.
Single0.0
Floating numbers (32 bits).
String"" (nullText (0 to 65 545 characters).
length)In code, strings are delimited with " (double quotes).
Variant
Empty
Any type, incl. object.
See also the Main types compatibility chart.
☞ Every time a type is unspecified, Variant is implicit.
☞ Integer values may be specified in hexadecimal base.
Prefix these values using &H. Ex : &HFF (decimal 255). Useful for colors.
☞ Always set initial values rather than rely upon implicit settings.
 Beware to rounding errors when using floating numbers!
Type name

BooleanArrays, Custom Types, Collections And Objects☞ See RefCard #9 “Structured Types”
LibOBasic_02_Overview_Flat_A4_EN_v200.odt

UseFunction

Sub SubName(parameters)
Sub SubName(parameters)'instructions
End Sub
SubName(arguments). If no argument: SubName()

Returns a value.
 Naming hint: verb at the indicative: IsXxx(), etc.

Declaration
Structure

Function FuncName(parameters) As SomeType
Function FuncName(parameters) As SomeType'instructions'somewhere, define the return value:
FuncName = SomeValue
End Function
SomeVar = FuncName(arguments)
Use
If no argument: SomeVar = FuncName()☞ A Function may be called like a Sub (without caring of the return value).

Parameters
Parameter a value the subprogram declaration specifies.
Argument the actual value the caller passes to the subprogram.

Usage
Ex : MySub(ByRef AParam as Long, ByVal OtherParam As String, _ByRef

Optional ByRef SomeParam As Object)

By reference (default). The parameter points to the argument passed by thecaller.
 Any modification of a ByRef item is propagated to the caller on exit.
ByVal
By value. The parameter is a copy of the argument passed by the caller.
☞ Value modifications are local to the called and not propagated to the caller.
Optional Optional parameter.
☞ Test the parameter absence using If IsMissing(SomeParam) Then …
The identifier is always available in the subprogram.
 Giving a default value to an optional parameter:
If IsMissing(SomeParam) Then SomeParam = SomeValue

Control StructuresError ManagementLoops

In Basic, error management relies upon:• On Error Xxx (and On Local Error Xxx) instructions for error interception.
• the Err, Erl and Error functions to get information about the last error met.

Repeat a sequence of instructions.
☞ Premature exit possible using Exit For or Exit Do according to situation.

For … Next
For each index value …

For i = Start To End [StepIncrement]'instructions
Next i

You must know the counter bounds.
By default, increment Step is 1.
☞ Indices are often named as i, j, k, etc.
 Never set the counter in the loop instructions!

For Each … Next
For each item …

For Each item In SomeObject'do smthg with item
Next

The number of items is unknown.
item must be of a compatible type.

Do While … Loop

Do While Condition'instructions
Loop

Condition is evaluated first.
 Infinite loops (Condition never met)!

While Condition'instructions
Wend☞ Older syntax, for compatibility only. Doesn’t support Exit.
Do not use!

or…

Do Loop ... Until

Do'instructions
Loop Until Condition

Condition is evaluated last.
 Infinite loops (Condition never met)!

Conditional Tests

ErrThe error code.
☞ An error code of 0 (zero) means “no error”.
Use If Err Then … to check for error presence.
The message that describes the error.
The line number where the error occurred.

Error
Erl

On Error – Globally Intercepting Errors
 Error interception using OnError is active as long as it has not been canceled.
On Error Goto MyLabel
Activates error interception. If an error occurs, theexecution continues to MyLabel.
☞ In the program body, you must define the label
MyLabel: (beware to the semicolon character).
On Error Resume Next
Activates error interception. If an error occurs, theexecution continues to the next instruction.
On Error Goto 0Cancels error interception.

On Local Error – Locally Intercepting Errors
In a subprogram, you might prefer the On Local Error Xxx syntax. This doesn’t requires calling On Error Goto 0 to cancel error interception: canceling is automatically
performed when leaving the Sub or Function.
☞ On Local Error Goto Xxx has precedence upon an existing On Error Goto Xxx.

Different Ways Of Running A Macro

A branch that allows to take action according to a given state/situation.

If (alone)
If Condition Then SomeInstruction

If Then [Else]If Condition Then'InstructionsThen
Else'InstructionsElse
End If

The Else condition is not mandatory.

If Condition Then'InstructionsThen1
ElseIf OtherCondition Then'InstructionsThen2
Else'InstructionsElse
End If

Instead of nested Ifs.

Select Case SomeVariable
Case Value : DoThat()
Case Value1, Value2'instructions for SomeValue
Case Value3 To Value4'instructions for OtherValue
Case Else'instructions for other situations
End SelectChoose among several possibilities,
according to SomeVariable actualvalue.

▼ Method
Using a toolbar button
Using a menu
Using a shortcut
Through an event

LibreOffice

Document Type
●
●
●

●
●

Current Document●●●

Source ▼Integer

LongSingle

DoubleCurrency

DecimalDate

StringObjectBooleanVariantMain Types Compatibility ChartInteger

●

●

●

●

●

●

●

●

x

●

●

Long!

●

●

●

●

●

●

●

x

●

●

Single

○!

○!

●

●

●

●

●

●

x!

●

Double○!

○!

○!

●

●

●

●

●

x!

●

Currency

○!

○!

!

●

●

●

○

●

x!

●

Decimal

○!

○!

○!

○

○!

●

○

●

x○!

●

Date○!

○!

!

●

●

○!

●

●

x!

●

String

○!

○!

○!

○!

○!

●

○!

●

x○!

●

Objectxxx

x

x

xx

x

●

x

●

Target ▶

If ElseIf

SelectLoading 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. Other libraries must be explicitly loaded to gain access to their code.
 Library names are case sensitive!

Loading From The Local Container (document)
Checking existence
Loading

Error Information Functions

LibExists = BasicLibraries.hasByName("MyLib")
BasicLibraries.loadLibrary("MyLib")

Loading From A Global Container
Same as above but BasicLibraries is replaced with GlobalScope.BasicLibraries.
 Mind to identifiers collisions between libraries! You may qualify names using:container.library.module.name (all or part).
Ex: GlobalScope.Tools.Strings.ClearMultiDimArray(MyArray, 3)

Calling A Command Associated With A LibreOffice Menu

Boolean

●

●

●

●

●

●

●

●

x

●

●

Variant

○!

○!

○!

○!

○!

●

○!

○!

●

○!

●

Compatibility● compatible○ possible loss

! possible overflow

x not compatible

Reading The Chart• You may assign a source variable contents of type Double to a target variable of anyof the Double, Currency, Date, and Variant types, without data loss.
• A target variable of type Double may lossless receive values of types Integer, Long,Single, Double, Date and Byte.

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 thewanted module (eg: sglobal/menubar/menubar.xml, etc.).
All commands start with .uno:
Ex : ".uno:Open" (File > Open), ".uno:OptionsTreeDialog" (Tools > Options), etc.

Program Skeleton
Dim Frame As Variant
Dim Dispatch As Object
Dim Args() As Variant 'contents depends upon context
Dim UnoCmd As String
Frame = ThisComponent.CurrentController.Frame
UnoCmd = 'UNO command to run (above)
Dispatch = createUnoService("com.sun.star.frame.DispatchHelper")
Dispatch.executeDispatch(Frame, UnoCmd, "", 0, Args())

Credits
Author : Jean-François Nifenecker – jean-francois.nifenecker@laposte.net
We are like dwarves perched on the shoulders of giants, and thus we are able to see more and farther than thelatter. And this is not at all because of the acuteness of our sight or the stature of our body, but because we arecarried aloft and elevated by the magnitude of the giants (Bernard de Chartres [attr.])HistoryVersionDateComments

2.0

04/20/2019

Restructure (some types moved to new RefCard #9)

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
Dim Args(0) As New com.sun.star.beans.PropertyValue
Args(0).Name = "Sidebar"
Args(0).Value = True'or False depending on aim
Dispatch.executeDispatch(Frame, ".uno:Sidebar", "", 0, Args())

LicenseThis refcard is placed under theCreativeCommons BY-SA v4 (intl) license.
More information:
https://creativecommons.org/licenses/by-sa/4.0/