LibO Primitives V0ad Without Classes
LibO Primitives V0ad Without Classes
3
Presentation
Presentation
This document comes with a bunch of subprogram “primitives” aimed at filling some program-
ming gaps in LibreOffice Basic. These primitives cover much of LibreOffice functionality and are
meant to be extended by any contributor over time. They complement the usual Tools library
made available under LibreOffice packages since the OOo years.
I aim at “correcting” some of the drawbacks that the Tools library suffers: would we see them un-
der a result point of view or a thematic theme, the Tools library mixes different primitives (its
Strings module has some maths functions); too few are documented and, when they are, it’s
quite poorly; the development standards aren’t clear (there’s no pedagogic incentive towards the
naming of items, code structure and the like); some of these primitives call UI items (ex. the Msg-
Box() function) which imply they can’t be used “as-is” in a non-UI environment; error handling
isn’t standardized and often non effective; test tools are not available.
In other words, LibO Basic users need reinventing the wheel each and every time they have a
new set of tools to develop.
Covered areas
The primitive subprograms proposed here are thematically grouped. The current edition covers
the following areas:
• Operating System information,
• IO helpers,
• Logging tool,
• Strings management,
• Arrays management,
• Mathematical tools,
• LibreOffice application suite tools,
• Calc module management,
• Writer module tools,
• Forms helpers,
• Email sending tool.
5
Vocabulary
7
Primitives Programming Guidelines
No User Interaction
For obvious reasons, most of the primitives never visually communicate with the user. This means
that such visual functions like MsgBox() are forbidden within the primitives. This allows to use
the primitives for non-visual uses, the visual part and error managing burdens being transferred
to the caller.
Note that some parts may use GUI when appropriate, as this is the case for the folder and file
pickers. This is clearly documented anytime.
Error Handling
For a better inter-process communication, the primitives generally handle errors by use of error
codes. Most of the time, these are stored within global constants named as ERR_xxx, as specified
in the details of the libraries below. It is up to the caller to make appropriate use of the return val-
ues.
The ERR_xxx constants are declared in the modules where they are used. This means that none is
available if the module is not used.
These constants naming follows the ERR_<library>_<name> mask,
ex: ERR_IOPRIM_NOSUCHFOLDER
Full Documentation
Modules
9
LibO Primitives
Subprograms
Naming Conventions
Modules Structure
Modules structure should be consistent. Here’s my take on this, which I’m applying everywhere
(See the actual code as an example).
1. A header
The header is a set of comment lines which introduce the code and give basic information. A
header should always specify at least the following:
1. The module name and summarized purpose.
2. The dependencies with other modules or libraries.
3. The author name.
4. The module version and date.
5. The license under which the code is released.
2. Execution options
In LibreOffice Basic, any execution option must appear first.
3. Declares
This is a very old habit of mine, from my Pascal days, that declares always come before the
code that uses the identifiers. They are listed in the following order:
1. Custom types.
2. Constants
Globals, then Public, then private to the module.
3. Variables
Globals, then Public, then private to the module.
4. Sub-programs
In alphabetical order ( _ prefixes are ignored for ordering).
5. A footer
A single End-of-file comment line.
No line of text is allowed past the footer.
Mode details below.
Dependencies
I’ve tried to avoid dependencies between modules as much as possible. At times, though, in order
to minimize code duplication, some dependencies may be present. These are specified in the mod-
ules headers and in the following descriptive pages.
10
Dependencies
In other situations, though, you’ll find internal subprograms, noted with a _ (underscore) prefix,
that may replicate code found elsewhere. I’ve adopted this format to avoid the said dependencies.
Subprograms structure
Subs and Functions follow this structure:
1. Declaration
2. Comments
1. A quick overview.
2. Input parameters details.
3. Output value (functions only).
4. Various details (optional).
3. Declares
Constants and variable declares, strictly separated from the subprogram body.
This is a heritage from my Pascal days, where all declares must be done at the top of the sub-
program. Anyway, I find this way of doing to be much clearer than some of the intricacies one
can see sometimes in Basic code.
4. Subprogram body
5. Function exit (functions only)
I always set the function exit at a single (final) place to ensure readability. Only on very excep-
tional occasions, where code would be overly complicated, a function may have more than one
exit point or not have its exit point at the end.
6. Subprogram end
Shown using a comment mentioning the subprogram name as a reminder.
Example (function ArrayExists() in ArrayPrim.Arrays)
Function ArrayExists(ByRef pArray As Variant) As Boolean
'Checks whether an array exists (is dimensioned) and can be manipulated.
'Input:
'-- pArray: the array to check
'Output: True if pArray is a valid array variable otherwise False
ArrayExists = l_Exists
End Function 'ArrayExists
11
LibO Primitives
Test Modules
All modules and subprograms come with a test routine. The test routines are stored in the same
module as the routines they test. The test routines are named from the tested routines names. For
instance, to test Function GetSomeResult() there is a Sub _GetSomeResult_test(). As the
primitives are listed alphabetically, this means that both the primitive routine and its test sub
come together in the code.
Note that classes are not tested that way. (WIP)
In case of changes within the primitives, the corresponding tests must be carried again.
Examples
Ideally, any piece of code should come with a real-life example. Unfortunately, such is not cur-
rently the case here. When time permits, I add code samples that show how to use some of the
primitives together in order to achieve some common goal.
12
Installation (version 0ad
13
Using the Primitives
Classes
Very few primitives are provided under the form of classes. This is the case for ini file and log file
management or for mailing facilities.
(from the defunct CereusAPIs)
Classes can just be instantiated using one the three ways shown below:
1 Sub Main
2
3 '1 - Using the Dim statement
4 Dim obj as new clsBase
5 ’MsgBox "I’ll popup before class initialization"
6
7 '2 - Using Set
8 Dim obj as Object
9 Set obj = new clsBase
10 'MsgBox "I’ll popup after class initialization"
11
12 '3 - Using createObject (according to documentation only on Window systems)
13 Dim obj as Object
14 Set obj = CreateObject("clsBase")
15 'MsgBox "I’ll popup before class initialization"
16
17 End Sub
There is a slight difference between the second approach and the first and third approaches. Fol-
lowing the second approach (Set) the class instance is initialized after assigning it to the obj
variable. In the other two approaches the class is initialized as soon as a field, property or method
is referenced/called.
15
Author & License
Author
The first version of these primitives collection is
© 2016-2018 – Jean-François Nifenecker, [email protected].
Most of the macros are from the author above. Nevertheless, some may come from different
sources, such as forums or mailing lists. When it is the case, the original author is credited in
these lines and in the code. Here’s a list of the cited authors:
(list)
CereusAPIs (website seems to have vanished by now)
Heertsch
If you are one of the authors and do not want your work to be collected in this set, just let me
know so that I remove the corresponding macros from the set.
License
The document and associated code are released under the CreativeCom-
mons Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.
See: http://creativecommons.org/licenses/by-sa/4.0/ The legal license text
is available at: http://creativecommons.org/licenses/by-sa/4.0/legalcode
17
The primitives
The primitives
The following pages list the global constants, global variables, subs and functions that are part of
the primitives set.
One chapter is devoted to each library, the modules being listed in sub-chapters. While constants
and variables are listed in apparent disorder, the primitives are listed in alphabetical order.
19
OSPrim
Operating system primitives.
OSPrim.OS............................................................................22 GetOSName().................................................................22
OSPRIM_OSWIN..........................................................22 IsLinux()..........................................................................22
OSPRIM_OSLINUX......................................................22 IsOSX().............................................................................22
OSPRIM_OSMAC.........................................................22 IsWindows()...................................................................22
OSPRIM_OSOSX...........................................................22 SetEnvString()................................................................22
GetEnvString()...............................................................22
21
LibO Primitives
OSPrim.OS
Dependencies: (none)
Constants
Constant name Value Description
OSPRIM_OSWIN Windows
OSPRIM_OSLINUX Linux
OSPRIM_OSMAC MacOS
OSPRIM_OSOSX OSX
Primitives
GetEnvString() TBD
GetOSName()
Function GetOSName() As String
IsLinux()
Function IsLinux() As Boolean
IsOSX()
Function IsOSX() As Boolean
IsWindows()
Function IsWindows() As Boolean
SetEnvString() TBD
22
ErrorPrim
ErrorPrim
Error handling library.
An effort is being put in all primitives in order to provide error checking every time it is possible
or useful. While many functions returns error values ( -1, zero-length string, False, Null and so
on), some functions and some subs just set an error value. It’s then up to the caller to test for
these errors values.
Whenever error values are set, you’ll find the corresponding constants listed at the top of each
chapter and at the top of each code module. The following syntax convention was adopted: the
constant name mask is ERR_<LIBNAME>_<ERRORTYPE>.
For instance, you’ll find ERR_IOPRIM_NOSUCHFOLDER.
TBD
23
IOPrim
This library offers folder and file access modules.
Note that internally, because LibreOffice is multi-platform, files, folders and paths names are con-
verted to the URL format. This format should always be preferred and the OS native format used
only when communicating with the user.
IOPrim.Globals....................................................................27 GetFileSize()...................................................................33
ERR_IOPRIM_NOERR.................................................27 GetSafeDateTimeStr()..................................................34
ERR_IOPRIM..................................................................27 IsHidden().......................................................................34
ERR_IOPRIM_NOSUCHFOLDER.............................27 IsReadOnly()..................................................................34
ERR_IOPRIM_FOLDERDELETE...............................27 JustFileName()...............................................................34
ERR_IOPRIM_FOLDERMOVE...................................27 NTFSFileNameString()................................................35
ERR_IOPRIM_FOLDERCOPY....................................27 SetHidden().....................................................................35
ERR_IOPRIM_FOLDEREXISTS.................................27 SetReadOnly()................................................................35
ERR_IOPRIM_FOLDERLIST......................................27 IOPrim.TextFiles..................................................................36
ERR_IOPRIM_FOLDERTOSELF................................27 CloseTextFile()...............................................................36
ERR_IOPRIM_NOSUCHFILE.....................................27 LoadTextFileAsString()................................................36
ERR_IOPRIM_UNKNOWNMODE...........................27 LoadTextFileAsVector()...............................................36
ERR_IOPRIM_FILEEXISTS.........................................27 OpenTextFile()...............................................................37
ERR_IOPRIM_FILETOSELF........................................27 ReadTextAsString()......................................................37
ERR_IOPRIM_FILEREADONLY................................27 ReadTextAsVector()......................................................37
ERR_IOPRIM_FILEHIDE............................................27 ReadTextLine()...............................................................37
ERR_IOPRIM_CANTCLOSETEXT...........................27 StoreFromArray()..........................................................37
ERR_IOPRIM_NOSPACE............................................27 StoreText().......................................................................37
ERR_IOPRIM_INISECUNKNOWN..........................27 WriteTextLine().............................................................37
ERR_IOPRIM_INIKEYUNKNOWN.........................27 IOPrim.Streams....................................................................38
IOPRIM_READMODE.................................................27 IOPRIM_SERV_SFA......................................................38
IOPRIM_WRITEMODE...............................................27 CloseStream().................................................................38
IOPRIM_APPENDMODE...........................................27 LoadTextStreamAsString().........................................38
IOPRIM_NOLOCK........................................................27 LoadTextStreamAsVector().........................................39
IOPRIM_LOCKREAD..................................................27 OpenStream().................................................................39
IOPRIM_LOCKWRITE................................................27 ReadTextFromStream()................................................39
IOPRIM_LOCKREADWRITE....................................27 StoreToStream().............................................................39
IOPRIM_FOLDERFILTER_ALL.................................27 WriteTextToStream()....................................................40
IOPRIM_FOLDERFILTER_FILESONLY...................27 IOPrim.Ini.............................................................................41
IOPRIM_FOLDERFILTER_FOLDERSONLY...........27 DeleteIniKey()................................................................41
IOPRIM_PATHSEPCHAR...........................................28 DeleteIniSection().........................................................41
IOPRIM_EXTSEPCHAR..............................................28 IniKeyExists().................................................................41
IOPrim.Folders.....................................................................29 IniSectionExists()..........................................................41
CheckPathStr()..............................................................29 ReadIniKey()...................................................................41
CopyFolder()..................................................................29 IniSectionStr()................................................................42
CreateFolder()................................................................29 WriteIniKey().................................................................42
DeleteFolder()................................................................29 IOPrim.Log...........................................................................43
FolderExists().................................................................30 IOPRIM_LOGUNK.......................................................43
FolderIsEmpty().............................................................30 IOPRIM_LOGERROR...................................................43
GetFolderContents()....................................................30 IOPRIM_LOGINFO......................................................43
GetParentFolder().........................................................30 IOPRIM_LOGERRORSTR...........................................43
IsFolder().........................................................................30 IOPRIM_LOGINFOSTR...............................................43
IsSubFolder()..................................................................31 ERR_IOPRIMLOGNONE............................................43
IOPrim.Files..........................................................................32 ERR_IOPRIM_LOGCANTCLOSE.............................44
ChangeFileExt().............................................................32 ERR_IOPRIM_LOGSUSPENDED..............................44
ExtractFileExt()..............................................................32 ERR_IOPRIM_LOGFILECLOSED.............................44
ExtractFileName().........................................................32 ERR_IOPRIM_LOGCANTWRITE............................44
ExtractFilePath()...........................................................33 ERR_IOPRIM_LOGCANTOPEN...............................44
GetFileContents()..........................................................33 ERR_IOPRIM_LOGSET...............................................44
GetFileDateTimeModified()........................................33 CloseLog().......................................................................44
25
LibO Primitives
DisableLogging()...........................................................44 ERR_ZIP_NONEMPTYDIR........................................46
EnableLogging()............................................................44 ErrorStatus......................................................................47
LogError().......................................................................44 IsInitialized.....................................................................47
LogInfo()..........................................................................44 ZipContainer..................................................................47
LogIt()..............................................................................44 AddDirectory()..............................................................47
OpenLog().......................................................................45 AddFile()..........................................................................47
SetLogging()...................................................................45 AddTree()........................................................................47
IOPrim.ZipClass..................................................................46 CloseZip().......................................................................47
ERR_ZIP_NONE............................................................46 DeleteDirectory()..........................................................48
ERR_ZIP_PACKAGEINIT...........................................46 DeleteFile().....................................................................48
ERR_ZIP_NOSUCHZIP...............................................46 DirectoryContents().....................................................48
ERR_ZIP_NOSUCHFILE.............................................46 DirectoryExistsInZip().................................................48
ERR_ZIP_DIREXISTSINZIP.......................................46 ExtractAll().....................................................................49
ERR_ZIP_NOSUCHFILEINZIP..................................46 ExtractFile()....................................................................49
ERR_ZIP_NOSUCHDIRINZIP...................................46 ExtractTree()..................................................................49
ERR_ZIP_NOTAZIP.....................................................46 FileExistsInZip()............................................................49
ERR_ZIP_NOTACHILDDIR.......................................46 FileStream()....................................................................50
ERR_ZIP_NOPARENTDIR.........................................46 OpenZip().......................................................................50
ERR_ZIP_NOSUBDIR..................................................46 ResetErrorStatus().........................................................50
26
IOPrim.Globals
IOPrim.Globals
Dependencies: (none)
Global Constants
Constant name Value Description
Error Constants
(longs)
ERR_IOPRIM_NOERR 0 No error.
ERR_IOPRIM 1000 Base value for all files and folders error results.
The other error codes are added to ERR_IOPRIM value.
ERR_IOPRIM_NOSUCHFOLDER ERR_IOPRIM + 1 Folder not found.
ERR_IOPRIM_FOLDERDELETE ERR_IOPRIM + 2 Folder deletion error.
ERR_IOPRIM_FOLDERMOVE ERR_IOPRIM + 3 Folder move error.
ERR_IOPRIM_FOLDERCOPY ERR_IOPRIM + 4 Folder copy error.
ERR_IOPRIM_FOLDEREXISTS ERR_IOPRIM + 5 The target folder already exists.
ERR_IOPRIM_FOLDERLIST ERR_IOPRIM + 6 Folder contents listing error.
ERR_IOPRIM_FOLDERTOSELF ERR_IOPRIM + 7 Can’t copy to self.
ERR_IOPRIM_NOSUCHFILE ERR_IOPRIM + 101 File not found.
ERR_IOPRIM_UNKNOWNMODE ERR_IOPRIM + 102 File opening mode is unknown.
ERR_IOPRIM_FILEEXISTS ERR_IOPRIM + 103 File already exists.
ERR_IOPRIM_FILETOSELF ERR_IOPRIM + 104 Can’t copy file to self.
ERR_IOPRIM_FILEREADONLY ERR_IOPRIM + 105 Can’t set file R/O.
ERR_IOPRIM_FILEHIDE ERR_IOPRIM + 106 Can’t hide file.
ERR_IOPRIM_CANTCLOSETEXT ERR_IOPRIM + 201 Text file can’t be closed.
ERR_IOPRIM_NOSPACE ERR_IOPRIM + 301 No space left on drive.
ERR_IOPRIM_INISECUNKNOWN ERR_IOPRIM + 401 Ini Section not found.
ERR_IOPRIM_INIKEYUNKNOWN ERR_IOPRIM + 402 Ini Key not found.
File Access Mode Constants
(longs)
IOPRIM_READMODE 1 Open a file for reading.
IOPRIM_WRITEMODE 2 Open a file for writing.
IOPRIM_APPENDMODE 8 Open a file for appending (read and write).
File Locking Modes (long)
IOPRIM_NOLOCK 0 No file locking.
IOPRIM_LOCKREAD 1 Lock a file in read mode.
IOPRIM_LOCKWRITE 2 Lock a file in write mode.
IOPRIM_LOCKREADWRITE 4 Lock a file in read and write modes.
Folder contents filtering
IOPRIM_FOLDERFILTER_ALL 0 (no filtering)
IOPRIM_FOLDERFILTER_FILESONLY 1 Return files only.
IOPRIM_FOLDERFILTER_FOLDERSONLY 2 Return folders only.
27
LibO Primitives
28
IOPrim.Folders
IOPrim.Folders
Dependencies: ArrayPrim.Arrays, IOPrim.Files
Primitives
CheckPathStr()
Function CheckPathStr(ByRef pPath As String) As String
CopyFolder()
Function CopyFolder(ByRef pSourceFolder As String, pTargetFolder As
String) As Long
CreateFolder()
Function CreateFolder(ByRef pFolderName As String) As Long
Creates a folder.
Input
pFolderName: the FQN of the folder to create (in URL or OS form).
Output
Returns 0 if the folder was created, or the creation error:
ERR_IOPRIM_FOLDEREXISTS: the folder already exists.
ERR_IOPRIM_NOSPACE: no space left on drive.
DeleteFolder()
Function DeleteFolder(ByRef pFolderName As String) As Long
Deletes a folder.
Input
pFolderName: the FQN of the folder to delete (in URL or OS form).
Output
Returns 0 if the folder was deleted, or the deletion error:
ERR_IOPRIM_NOSUCHFOLDER: folder not found.
ERR_IOPRIM_FOLDERDELETE: can’t delete folder.
29
LibO Primitives
FolderExists()
Function FolderExists(ByRef pFolderName As String) As Boolean
FolderIsEmpty()
Function FolderIsEmpty(ByRef pFolderName As String) As Boolean
GetFolderContents()
Function GetFolderContents(ByRef pFolderName As String, pFilter As
Byte, pContents As Variant) As Long
GetParentFolder()
Function GetParentFolder(ByRef pFolderName As String) As String
IsFolder()
Function IsFolder(ByRef pName As String) As Boolean
30
IOPrim.Folders
IsSubFolder()
Function IsSubFolder(ByRef pParentName As String, pChildName As String)
As Boolean
31
LibO Primitives
IOPrim.Files
Dependencies: StringsPrim.Strings
Primitives
ChangeFileExt()
Function ChangeFileExt(ByRef pFileName As String, pNewExt As String)
As String
ExtractFileExt()
Function ExtractFileExt(ByRef pFileName As String) As String
ExtractFileName()
Function ExtractFileName(ByRef pFileName As String) As String
32
IOPrim.Files
ExtractFilePath()
Function ExtractFilePath(ByRef pFileName As String) As String
GetFileContents()
Function GetFileContents(ByRef pFileName As String) As String
(from Tools.GetRealFileContent)
Returns the content type of a document.
Input
pFileName: the file name to be processed (in URL or OS form).
Output
Returns the content type of a document by extracting the content from the
header of the document or an empty string if the content couldn’t be
determined.
Returns:
odt: writer8
ods: calc8
odp: impress8
odg: draw8
odb: StarBase
txt: writer_T602_Document
rtf: writer_Rich_Text_Format
pdf: pdf_Portable_Document_Format
zip: writer_FictionBook_2
etc.
GetFileDateTimeModified()
Function GetFileDateTimeModified(ByRef pFileName As String) As Date
GetFileSize()
Function GetFileSize(ByRef pFileName As String) As Long
33
LibO Primitives
GetSafeDateTimeStr()
Function GetSafeDateTimeStr(ByRef pDate As Date, Optional pWithTime
As Boolean) As String
IsHidden()
Function IsHidden(ByRef pFileName As String) As Boolean
IsReadOnly()
Function IsReadOnly(ByRef pFileName As String) As Boolean
JustFileName()
Function JustFileName(ByRef pFileName As String) As String
Retrieves a filename without its access path nor its extension from a FQN file
name.
Input
pFileName: the file name to be processed (in URL or OS form).
Output
The file name without the path and extension parts.
Note: this does not check for the file/path existence.
See also ExtractFileName().
Usage
JustFile = JustFileName("C:\Path\To\MyFile.odt")
returns MyFile
34
IOPrim.Files
NTFSFileNameString()
Function NTFSFileNameString(ByRef pFileName As String, Optional
ByRef pExtended As Boolean) As String
SetHidden()
Function SetHidden(ByRef pFileName As String, pHide As Boolean) As
Long
SetReadOnly()
Function SetReadOnly(ByRef pFileName As String, pRO As Boolean) As
Long
35
LibO Primitives
IOPrim.TextFiles
Dependencies: (none)
This module’s subprograms allow for text files control using the standard LibreOffice Basic tools.
As streams were introduced lately, another set of primitives has been developed for the same pur-
pose in another module (see IOPrim.Streams)
Primitives
CloseTextFile()
Function CloseTextFile(ByRef pFileH As Integer) As Long
LoadTextFileAsString()
Function LoadTextFileAsString(ByRef pFileName As String, pLineSep As
String) As String
LoadTextFileAsVector()
Function LoadTextFileAsVector(ByRef pFileName As String) As Variant
36
IOPrim.TextFiles
OpenTextFile()
Function OpenTextFile(ByRef pFileName As String, Optional pMode As
Long) As Integer
ReadTextAsString()
Function ReadTextAsString(ByRef pHFile As Integer, pLineSep As String)
As String
ReadTextAsVector()
Function ReadTextAsVector(ByRef pHFile As Integer) As Variant
Reads an opened text file and returns its contents as a 1D array (vector).
The source text file is not closed when the function returns.
Input
pHFile: the text file handler
Output
The text file as a string vector.
See also
LoadTextFileAsVector()
ReadTextLine()
Function ReadTextLine() As String
Reads a line of text from a text file, at the current cursor location.
StoreFromArray()
Function StoreFromArray() As Long
Stores all the strings within a one-dimension array into a text file.
StoreText()
Function StoreText() As Long
WriteTextLine()
Function WriteTextLine() As Long
Writes a line of text within a text file, at the current cursor location.
37
LibO Primitives
IOPrim.Streams
(work-in-progress)
Dependencies: (none)
The primitives in this module access to files using the API SimpleFileAccess service (aka
streams). When multi-platform development is in order, they should be preferred to the classic
primitives in IOPrim.TextFiles.
For a demonstration of these routines use, see the ini-file management (Ini module). (not yet
done)
Stream encoding methods: the stream read/write functions may set the source or target text en-
coding method. If not explicitly set, the encoding is in UTF-8 by default. The encoding is set using
a description string (ex: "UTF-8"). The complete list of available encoding descriptors can be
found here:
https://www.iana.org/assignments/character-sets/character-sets.xhtml (name column).
Globals
Constant name Value Description
IOPRIM_SERV_SFA "com.sun.star.ucb.SimpleFileAccess" (string) SimpleFileAccess service name.
Primitives
CloseStream()
Function CloseStream(ByRef pStream As Object) As Long
Closes a stream.
Input
pStream: the stream to close.
Output
Returns 0 if the operation was executed, or an error code:
pStream is Null.
pStream doesn’t support any stream service.
Can’t close the stream ().
LoadTextStreamAsString()
Function LoadTextStreamAsString(ByRef pFileName As String, pEncoding
As String) As String
38
IOPrim.Streams
LoadTextStreamAsVector()
Function LoadTextStreamAsVector(ByRef pFileName As String, pEncoding
As String) As Variant
Reads a text file and returns its contents as a vector (1D array).
This function opens, reads then closes the source text file.
Input
pFileName: the file name (FQN, in URL or OS mode)
pEncoding: the text file contents encoding, as a string (defaults to UTF-8 when
not specified).
Output
The text contents as a 1D array.
OpenStream()
Function OpenStream(ByRef pFileName As String, pMode As Long,
Optional pEncoding As String) As Object
ReadTextFromStream()
Function ReadTextFromStream(ByRef pStream As Object, pString As
String) As Long
StoreToStream()
Function StoreToStream(ByRef pFileName As String, pStr As String) As
Long
39
LibO Primitives
WriteTextToStream()
Function WriteTextToStream(ByRef pStream As Object, pStr As String)
As Long
40
IOPrim.Ini
IOPrim.Ini
(work-in-progress)
Dependencies: (none)
This module offers ini file handling (based upon IOPrim.TextFile primitives above).
Primitives
DeleteIniKey()
Function DeleteIniKey(ByRef pFileName As String, pSection As String,
pKey As String) As Long
DeleteIniSection()
Function DeleteIniSection(ByRef pFileName As String, pSection As
String) As Long
IniKeyExists()
Function IniKeyExists(ByRef pFileName As String, pSection As String,
pKey As String) As Boolean
IniSectionExists()
Function IniSectionExists(ByRef pFileName As String, pSection As
String) As Boolean
ReadIniKey()
Function ReadIniKey(ByRef pFileName As String, pSection As String, pKey
As String, pValue As String) As Long
41
LibO Primitives
IniSectionStr()
Function IniSectionStr(ByRef pSName As String) As String
Returns a section name for ini file writing or reading, that is with surrounding
square brackets.
Note that spaces are left untouched, except starting and ending ones which are
stripped off the input string.
WriteIniKey()
Function WriteIniKey(ByRef pFileName As String, pSection As String,
pKey As String, pValue As String) As Long
42
IOPrim.Log
IOPrim.Log
Dependencies: (none)
The subprograms in this module handle writing to log files.
A log file is a text file which holds lines of messages. A log message/line structure follows this
scheme:
20160325 153412 [ERR ] File not found
^^^^^^^^ ^^^^^^ ^^^^^^ ^^^.......
date time type message...
(iso)
You may log three message types: error messages [ERR ], information messages [INFO] and un-
categorized messages (see the IOPRIM_LOGUNK, IOPRIM_LOGERROR and IOPRIM_LOGINFO con-
stants). Basically, logging a message is done using either LogIt(), LogError() or LogInfo()
functions.
Logging strategy:
0. Define the logging context (file name and overwrite mode) (SetLogging()).
1. Enable logging (EnableLogging()) to start the logging process.
2. Log events by choosing the event type (error or information, or nothing) ( LogIt(), LogEr-
ror() or LogInfo())
Note that you don’t have to explicitly open the log file as it is automatically opened whenever
necessary.
3. End logging (CloseLog()), which actually closes the log file.
Notes:
Logging may be suspended and resumed at any time, using DisableLogging() and EnableL-
ogging().
If you want to log again after explicitly closing the log file, just re-enable the logging (EnableL-
ogging()) before logging new messages.
This module has been made as independent as possible from any other in the set.
Error management is possible through the ERR_IOPRIM_LOGxxx constants.
Constants
Constant name Value Description
General
IOPRIM_LOGUNK 0
IOPRIM_LOGERROR 1
IOPRIM_LOGINFO 2
43
LibO Primitives
Primitives
CloseLog()
Function CloseLog() As Long
DisableLogging()
Sub DisableLogging()
EnableLogging()
Sub EnableLogging()
Starts logging.
LogError()
Function LogError(ByRef pMsg As String) As Long
LogInfo()
Function LogInfo(ByRef pMsg As String) As Long
LogIt()
Function LogIt(ByRef pMsg As String, Optional pType As Integer) As Long
44
IOPrim.Log
OpenLog()
Function OpenLog() As Long
SetLogging()
Sub SetLogging(ByRef pLogFileName As String, Optional pOvw As Boolean)
45
LibO Primitives
IOPrim.ZipClass
Dependencies: (none)
This class manages zip files (compressed files): zip container creation, adding, deleting, suppress-
ing or extracting files or folders. It can be used to explore LibreOffice documents.
Directories
Zip containers can store directories. Accessing a directory is straightforward: just specify its full
name wherever required. The root directory name usually is "" (null-length string) and subdirec-
tories are separated with the "/" (slash) character.
Note that the root directory name can also be written as "/" (slash). Thus, both /Path/To/My-
File.odt and Path/To/MyFile.odt are valid and point to the same file (MyFile.odt).
Error Management
Errors are reported internally by the ZipClass. The last error code can be accessed using the Er-
rorStatus read-only property. The ResetError() method resets the error status to the default.
The available error values are described through the ERR_ZIP_XXX values below.
Constants
Constant name Value Description
Error Constants
ERR_ZIP_NONE 0 No error (default error value)
ERR_ZIP_PACKAGEINIT 1 The zip package container couldn’t be
initialized.
ERR_ZIP_NOSUCHZIP 2 The zip file doesn’t exist.
ERR_ZIP_NOSUCHFILE 3 The specified file cannot be found on the
device.
ERR_ZIP_DIREXISTSINZIP 4 The specified directory already exists in the
zip container.
This can possibly not be an error.
ERR_ZIP_NOSUCHFILEINZIP 5 The specified file cannot be found in the zip
directory.
ERR_ZIP_NOSUCHDIRINZIP 6 The directory doesn’t exist within the zip
container.
ERR_ZIP_NOTAZIP 7 The container is not a zip.
ERR_ZIP_NOTACHILDDIR 8 The specified subdirectory is not a child of the
parent.
ERR_ZIP_NOPARENTDIR 9 The specified directory is not a parent of the
subdir.
ERR_ZIP_NOSUBDIR 10 The specified directory has no subdirs.
ERR_ZIP_NONEMPTYDIR 11 The directory is not empty, thus can’t be
deleted.
46
IOPrim.ZipClass
Properties
ErrorStatus Integer [RO] Returns the current error status.
See ERR_ZIP_XXX constants above.
IsInitialized Boolean [RO] Returns True if the zip container is initialized, False otherwise.
Methods
Public Methods
AddDirectory()
Public Sub AddDirectory(ByRef pZipDir As String)
AddFile()
Public Sub AddFile(ByRef pFileURL As String, Optional ByRef pZipDir As
String)
AddTree()
Public Sub AddTree(ByRef pTreeURL As String, pParentURL As String)
(TBD)
CloseZip()
Public Sub CloseZip()
47
LibO Primitives
DeleteDirectory()
Public Sub DeleteDirectory(ByRef pDirName As String, pParentURL As
String)
DeleteFile()
Public Sub DeleteFile(ByRef pFileName As String)
DirectoryContents()
Public Function DirectoryContents(ByRef pDirURL As String) As Variant
DirectoryExistsInZip()
Public Function DirectoryExistsInZip(ByRef pPathURL As String) As
Boolean
48
IOPrim.ZipClass
ExtractAll()
Public Sub ExtractAll(ByRef pTargetDirURL As String, Optional
pIgnoreEmpty As Boolean)
ExtractFile()
Public Sub ExtractFile(ByRef pFileName As String, pTargetURL As String)
ExtractTree()
Public Sub ExtractTree(ByRef pTreeURL As String, pTargetDirURL As
String)
Extracts a container directory tree and its contents to some directory on a device.
Input
pTreeURL: the internal tree to extract, in URL form (all dirs and subdirs).
pTargetDirURL: the target device (in URL form) where to extract directories and
files.
If the target doesn’t exist, it is created if possible.
pIgnoreEmpty: (optional) empty directories are not recreated.
Defaults to True
Possible error results:
ERR_ZIP_NONE: everything went OK.
ERR_ZIP_NOSUCHZIP: zip file not found.
ERR_ZIP_PACKAGEINIT: zip container initialization problem.
ERR_ZIP_NOSUCHDIRINZIP: directory not found in zip.
FileExistsInZip()
Public Function FileExistsInZip(ByRef pPathURL As String) As Boolean
49
LibO Primitives
FileStream()
Public Function FileStream(ByRef pFileName As String) As Object
Reads a file stream from the zip container and returns it.
Input
pFileName: the full path to the file in the container (FQN)
Ex: Path/To/SomeFile.odt
Output
The file stream read or Null if an error occurred.
Possible error results:
ERR_ZIP_NONE: everything went OK
ERR_ZIP_NOSUCHFILEINZIP: file not found in zip
OpenZip()
Public Sub OpenZip(ByRef pZipURL As String)
ResetErrorStatus()
Public Sub ResetErrorStatus()
Usage
See the ZipClass_Test module.
50
IniPrim
(under development – not working yet)
IniPrim.Globals....................................................................52 RemChars.......................................................................53
ERR_INICLASS_NOTHINGTODO..........................52 Stream..............................................................................53
ERR_INICLASS_EMPTYVALUE...............................52 CloseFile().......................................................................53
ERR_INICLASS_NONE...............................................52 DeleteKey().....................................................................53
ERR_INICLASS_CANTCREATEFILE......................52 DeleteSection()..............................................................54
ERR_INICLASS_CANTOPENFILE...........................52 KeyExists()......................................................................54
ERR_INICLASS_FILENOTFOUND..........................52 Init()..................................................................................54
ERR_INICLASS_CANTWRITEFILE........................52 Load()...............................................................................54
ERR_INICLASS_SECTIONNOTFOUND.................52 ReadKey()........................................................................54
ERR_INICLASS_KEYNOTFOUND...........................52 SectionExists()...............................................................54
IniPrim.IniStreamClass......................................................53 SectionKeys().................................................................54
BackupExtension..........................................................53 Sections().........................................................................54
CacheUpdates................................................................53 SectionValues()..............................................................55
FileName.........................................................................53 UpdateFile()....................................................................55
LastError.........................................................................53 WriteKey()......................................................................55
51
LibO Primitives
IniPrim.Globals
Dependencies: (none)
All constants have a INIPRIM or INICLASS prefix. As always, error constants are ERR_ prefixed.
Constant name Value Description
Error Constants
ERR_INICLASS_NOTHINGTODO -2 Nothing to do.
ERR_INICLASS_EMPTYVALUE -1 The wanted value is empty (the key exists). This is
not really an “error”.
ERR_INICLASS_NONE 0 No error.
ERR_INICLASS_CANTCREATEFILE 1 Impossible to create or update the ini file.
ERR_INICLASS_CANTOPENFILE 2 The file can’t be opened.
ERR_INICLASS_FILENOTFOUND 3 The ini file specified was not found.
ERR_INICLASS_CANTWRITEFILE 4 The ini file is set as read-only. Can’t write to the file.
ERR_INICLASS_SECTIONNOTFOUND 11 The specified section is not defined in the ini file.
ERR_INICLASS_KEYNOTFOUND 12 The specified key is not defined in the section.
52
IniPrim.IniStreamClass
IniPrim.IniStreamClass
(not yet available)
Dependencies: StringsPrim.Strings
This module defines an Ini file management class. Ini files can be managed either in memory or
on-disk.
Properties
BackupExtension String [R/W] The ini file backup extension.
Defaults to “.bak”
CacheUpdates Boolean [R/W] Defines the way the ini file is handled:
if CacheUpdates is True, the ini file is managed in memory. The
file is written on disk on object destruction or on a call to the
UpdateFile() method.
if CacheUpdates is False, then every change in the ini file is
immediately written to disk.
Defaults to False: all changes are immediately sent to device.
FileName String [R/W] Sets or gets the ini file name (FQN).
Note: the file name must specify the extension which is not set by
the class.
RemChars String [R/W] Sets and reads the comment chars values.
By default RemChars is set to # only.
Stream Object [RO] Returns the stream associated with the ini file.
Methods
CloseFile()
Sub CloseFile()
DeleteKey()
Function DeleteKey(ByRef pSection As String, pKey As String) As Long
53
LibO Primitives
DeleteSection()
Function DeleteSection(ByRef pSection As String) As Long
KeyExists()
Function KeyExists(ByRef pSection As String, pKey As String) As Boolean
Init()
Function Init(ByRef pFileName As String, Optional pCacheUpdates As Boolean) As
Long
This method initializes both FileName and CacheUpdates properties at once, then
loads the specified ini file if it exists (see Load() method).
CacheUpdates defaults to False.
Returns ERR_INICLASS_NONE if successfully completed, otherwise an error code:
File not found ( ERR_INICLASS_FILENOTFOUND),
Can’t open file (ERR_INICLASS_CANTOPENFILE)
Load()
Function Load() As Long
ReadKey()
Function ReadKey(ByRef pSection As String, pKey As String, pValue As
String) As Long
SectionExists()
Function SectionExists(ByRef pSection As String) As Long
SectionKeys()
Returns an array of all key names present within a section in the ini file.
Sections()
Returns an array of all section names present within the ini file.
54
IniPrim.IniStreamClass
SectionValues()
Returns an array of all key-value pairs in a section of the ini file.
UpdateFile()
Function UpdateFile() As Long
WriteKey()
Function WriteKey(ByRef pSection As String, pKey As String, pValue As
String) As Long
55
LogPrim
This library offers logging means through a dedicated class.
LogPrim.LogTextClass.......................................................58 Paused..............................................................................59
ERR_LOGCLASS_NONE............................................58 TimeStampFormat........................................................59
ERR_LOGCLASS_CANTCREATEFILE....................58 ClearError()....................................................................59
ERR_LOGCLASS_CANTOPENFILE........................58 Log().................................................................................59
ERR_LOGCLASS_FILENOTFOUND........................58 LogDebug().....................................................................59
ERR_LOGCLASS_CANTWRITEFILE......................58 LogError().......................................................................59
Active...............................................................................58 LogInfo()..........................................................................59
DefaultType...................................................................58 LogWarning().................................................................59
Filename..........................................................................58 PauseLog()......................................................................59
LastError.........................................................................58 ResumeLog()..................................................................59
LogMask..........................................................................58 LogPrim.LogStreamClass..................................................60
57
LibO Primitives
LogPrim.LogTextClass
Dependencies: (none)
This module defines a log file management class using standard text file management. Log mes-
sages are immediately written to disk.
Constants
All constants have a LOGCLASS prefix. Moreover, error constants are ERR_ prefixed.
Constant name Value Description
Error Constants
ERR_LOGCLASS_NONE 0 No error.
ERR_LOGCLASS_CANTCREATEFILE 1 Impossible to create or update the ini file.
ERR_LOGCLASS_CANTOPENFILE 2 The file can’t be opened.
ERR_LOGCLASS_FILENOTFOUND 3 The ini file specified was not found.
ERR_LOGCLASS_CANTWRITEFILE 4 The ini file is set as read-only. Can’t write to the file.
Other constants
Properties
Active Boolean [R/W] Active determines whether the log mechanism is active.
If set to True, the object opens the log file if needed.
Any attempt to log a message while the log is not active will try to
set this property to True. Closing the log file is done by setting the
Active property to False.
If the log file cannot be opened, this property results in an
ERR_LOGCLASS_CANTOPENFILE error (see the LastError property).
DefaultType String [R/W] Defines the default logging type, among the ones in the
LOGCLASS_LOGxxx constants (see above).
Filename String [R/W] FileName is the name of the log file used to log messages.
If none is specified, then the name of the document is used, with
the extension replaced by .log. The file is then located in the /tmp
directory on unix-like systems, or in the application directory for
Dos/Windows systems.
58
LogPrim.LogTextClass
Paused Boolean [RO] Paused indicates whether the sending of messages is temporarily
suspended or not.
See PauseLog() and ResumeLog() methods.
Methods
Public Methods
ClearError()
ClearError()
Log()
Log()
Logs a message.
The optional pType argument is used as the message event type.
pType defaults to “info”.
LogDebug()
LogDebug()
LogError()
LogError()
LogInfo()
LogInfo()
LogWarning()
LogWarning()
PauseLog()
PauseLog()
ResumeLog()
ResumeLog()
Resumes the sending of log messages if sending was paused through Pause().
The Paused property (R/O) returns the pause status.
59
LibO Primitives
LogPrim.LogStreamClass
Dependencies: (none)
This class is the same as LogTextclass, except it uses streams as a text file output. The overall
methods and properties are identical.
(under development)
60
StringsPrim
StringsPrim.Strings.............................................................62 QuoteStr().......................................................................63
STRPRIM_SGLQUOTECHAR....................................62 ReplaceStr()....................................................................64
STRPRIM_DBLQUOTECHAR...................................62 RightPad().......................................................................64
DelChar()........................................................................62 StripChars()....................................................................64
DelSpaces().....................................................................62 SuppressMultipleChars().............................................64
FilterNonPrintableStr()................................................62 TitleCase().......................................................................65
LeftPad()..........................................................................63 TrimEx()..........................................................................65
NoAccentStr()................................................................63 UnQuoteStr()..................................................................65
61
LibO Primitives
StringsPrim.Strings
Dependencies: (none)
Global Constants
Constant name Value Description
STRPRIM_SGLQUOTECHAR ’ Single quote char.
STRPRIM_DBLQUOTECHAR " Double quote char.
Primitives
DelChar()
Function DelChar(ByRef pStr As String, pChar As String) As String
DelSpaces()
Function DelSpaces(ByRef pStr As String, Optional pUnBreak As Boolean)
As String
FilterNonPrintableStr()
Function FilterNonPrintableStr(ByRef pStr As String) As String
62
StringsPrim.Strings
LeftPad()
Function LeftPad(ByRef pStr As String, pPadChar As String, pLength As
Long) As String
Pads a string on the left to a given length using a padding character and returns the
resulting string.
Input
pStr: the string to process
pPadChar: the character used for padding
pLength: the output string length
Output
The result string.
If pLength is less than pStr actual length, the resulting string is shortened
accordingly on the left.
See RightPad().
Usage
LeftPad("LibreOffice", "-", 15)
returns "----LibreOffice"
NoAccentStr()
Function NoAccentStr(ByRef pStr As String) As String
QuoteStr()
Function QuoteStr(ByRef pStr As String, pQuoteChar As String) As String
63
LibO Primitives
ReplaceStr()
Function ReplaceStr(ByRef pStr As String, pSearchStr As String,
pReplStr As String) As String
RightPad()
Function RightPad(ByRef pStr As String, pPadChar As String, pLength As
Long) As String
Pads a string on the right to a given length using a padding character and returns
the resulting string.
Input
pStr: the string to process
pPadChar: the character used for padding
pLength: the output string length
Output
The result string.
If pLength is less than pStr actual length, the resulting string is shortened
accordingly on the right.
See LeftPad().
Usage
RightPad("1234", 7, "x") → "1234xxx"
RightPad("1234", 3, "x") → "123"
StripChars()
Function StripChars(ByRef pStr As String, pStripChars As String) As
String
SuppressMultipleChars()
Function SuppressMultipleChars(ByRef pStr As String, pChar As String)
As String
64
StringsPrim.Strings
TitleCase()
Function TitleCase(ByRef pStr As String) As String
TrimEx()
Function TrimEx(ByRef pStr As String) As String
Enhanced version of the Basic Trim() function that suppresses surrounding spaces
from a given string. This function suppresses both standard spaces (Ascii 032) and
unbreakable spaces (Ascii 160).
Input
pStr: The string to process.
Output
The process result.
UnQuoteStr()
Function UnQuoteStr(ByRef pStr As String, pQuoteChar As String) As
String
65
ArrayPrim
Array primitives.
ArrayPrim.Arrays...............................................................68 QuickSort1D()................................................................69
AddToVector()................................................................68 ReverseVector()..............................................................69
Array2DToDataArray()...............................................68 ShellSort().......................................................................70
ArrayDimCount().........................................................68 SortVectorBubble().......................................................70
ArrayExists()..................................................................68 StringPosInArray().......................................................70
ArrayIsEmpty()..............................................................69 VectorFromStringNums()............................................70
ConcatVectors().............................................................69 VectorToDataArray()...................................................71
DataArrayToArray2D()................................................69
67
LibO Primitives
ArrayPrim.Arrays
Dependencies: (none)
Vocabulary:
• Vector: a 1-dimension array.
• Array: any array with more than one dimension.
• Nested array: an array with another array in it.
Primitives
AddToVector()
Sub AddToVector(ByRef pVector As Variant, pItem as Variant)
Array2DToDataArray()
Function Array2DToDataArray(ByRef pArray2D As Variant) As Variant
Creates a 2-dimensions nested array (compatible with the Calc ranges .DataArray
property) from a 2D array.
Input
pArray2D: the input array. Must be 1 or 2D otherwise it is ignored.
The input array is supposed to be an existing array.
Output
A data array compatible with Calc ranges .DataArray. The output may be a 1D or
2D array, or Null according to the input array characteristics.
See also: DataArrayToArray2D()
ArrayDimCount()
Function ArrayDimCount(ByRef pArray As Variant) As Integer
ArrayExists()
Function ArrayExists(ByRef pArray As Variant) As Boolean
68
ArrayPrim.Arrays
ArrayIsEmpty()
Function ArrayIsEmpty(ByRef pArray() As Variant, Optional pDim As Byte)
As Boolean
ConcatVectors()
Function ConcatVectors(ByRef pVectors As Variant) As Variant
DataArrayToArray2D()
Function DataArrayToArray2D(ByRef pDataArray() As Variant, Optional
pIgnoreEmpty As Boolean) As Variant
QuickSort1D()
Sub QuickSort1D(ByRef pArray() As Variant, Optional pFrom As Long,
Optional pTo as Long)
Sorts a one dimension array in ascending order using the Quicksort algorithm.
starting at the pFrom item ans ending with the pTo item (pFrom and pTo are included
in the sorted set).
Default value for pFrom is LBound(pArray).
Default value for pTo is UBound(pArray).
Note: the sub is recursive, which means that very big sets of data will probably cause
memory overflow.
Adapted from VBScript in http://www.4guysfromrolla.com/webtech/012799-2.shtml
ReverseVector()
Function ReverseVector(ByRef pVector As Variant) As Variant
69
LibO Primitives
ShellSort()
Sub ShellSort(ByRef pArray)
Sorts a one dimension array in ascending order using the Shellsort algorithm.
Adapted from VBScript in http://www.4guysfromrolla.com/webtech/012799-2.shtml
SortVectorBubble()
Function SortVectorBubble(ByRef pVector As Variant, Optional ByRef pAsc
As Boolean)
Sort a vector (1-D array) data using the bubble sort algorithm (slow for large arrays).
Input
pVector: the vector to sort.
The input array must exist.
pAsc: (optional) True if the sort must be in ascending order, otherwise False.
Defaults to True.
Output
The sorted vector. The sort is case-sensitive.
Adapted from https://helloacm.com/bubble-sort-in-vbscript/
StringPosInArray()
Function StringPosInArray(ByRef pArray As String, pStr as String,
Optional pCompare as Integer) as Long
VectorFromStringNums()
Function VectorFromStringNums(ByRef pInputStr As String, pSepChar As
String, pRangeChar As String, pAsLongs As Boolean) As Variant
Converts a string of numbers into an array of discrete values. This mimics the page
selection behavior in the UI print dialog.
Input
pInputStr: the string to convert.
The string is made of integer numbers (longs) with separators.
pSepChar: the item separator character (one only).
pRangeChar: the range separator character (one only).
pAsLongs: convert the output array items into Longs.
Output
A vector (1-D array) containing each item in the input string, separated as specified
with pSepChar and pRangeChar.
If an error occurred, or if the input string is a zero-length one, the output is Null.
Usage
Str = "-1, 3-6, 10"
VectorFromStringNums(Str, ",", "-", True)
returns the array: (-1, 3, 4, 5, 6, 10)
VectorFromStringNums(Str, ",", "-", False)
returns the array: ("-1", "3", "4", "5", "6", "10")
70
ArrayPrim.Arrays
VectorToDataArray()
Function VectorToDataArray(ByRef pVector As Variant, Optional pRaw As
Boolean) As Variant
Converts a vector (1D array) into a DataArray that can be used to feed a Calc range
DataArray property.
A Calc DataArray is a 2D nested array.
Input
pVector: the vector to convert.
pRaw: (optional) Defines what should be done with empty vector items.
If set to True (the default), data is left as-is. That is, copying the data into a Calc
range may result in cells with error values for empty values. If set to False, the
empty value is replaced with a zero-length string.
Output
The DataArray. Its first array index is 0.
71
MathPrim
MathPrim.Math...................................................................74 IsLower().........................................................................76
mEpsilon.........................................................................74 IsLowerEqual()...............................................................76
MATH_DELTA..............................................................74 Max()................................................................................76
Average().........................................................................74 MaxInArray().................................................................76
BankersRound().............................................................74 MaxLng().........................................................................76
Init()..................................................................................74 Median()..........................................................................77
IsDifferent()....................................................................75 Min().................................................................................77
IsEqual()..........................................................................75 MinInArray()..................................................................77
IsGreater().......................................................................75 Round()............................................................................77
IsGreaterEqual()............................................................75 SetEpsilon()....................................................................77
IsInRange()......................................................................75 SwapValues()..................................................................77
73
LibO Primitives
MathPrim.Math
Dependencies: (none)
Basic math calculations.
Module Variables
Variable name Type Description
mEpsilon Double Stores the comparator value for equality tests.
The Init() sub sets this variable to 0.000001 (10-6).
See also MATH_DELTA and SetEpsilon().
Global Constants
Constant name Value Description
MATH_DELTA 0.000001 10-6 default value for mEpsilon.
Primitives
Average()
Function Average(ByRef pArray As Variant) As Double
BankersRound()
Function BankersRound(ByRef pValue As Double, pDecimals As Integer) As
Double
Rounds a value to a given number of decimals using the “bankers rounding”, that is
rounding to the nearest even number.
Input
pValue: the value to round.
pDecimals: the number of decimals for the rounding.
Output
The rounded number.
Usage
BankersRound(1.5, 0) →2
BankersRound(2.5, 0) →2
See also Round().
Init()
Sub Init()
74
MathPrim.Math
IsDifferent()
Function IsDifferent(ByRef pValue1 As Double, pValue2 As Double) As
Boolean
IsEqual()
Function IsEqual(ByRef pValue1 As Double, pValue2 As Double) As Boolean
IsGreater()
Function IsGreater(ByRef pValue1 As Double, pValue2 As Double) As
Boolean
IsGreaterEqual()
Function IsGreaterEqual(ByRef pValue1 As Double, pValue2 As Double) As
Boolean
IsInRange()
Function IsInRange(ByRef pValue As Double, pMin As Double, pMax As
Double, Optional pExclusive As Boolean) As Boolean
75
LibO Primitives
IsLower()
Function IsLower(ByRef pValue1 As Double, pValue2 As Double) As Boolean
IsLowerEqual()
Function IsLowerEqual(ByRef pValue1 As Double, pValue2 As Double) As
Boolean
Max()
Function Max(ByRef pValue1 As Double, pValue2 As Double) As Double
MaxInArray()
Function MaxInArray(ByRef pArray As Variant) As Double
MaxLng()
Function MaxLng(ByRef pNum1 As Long, pNum2 As Long) As Long
76
MathPrim.Math
Median()
Function Median(ByRef pArray As Variant) As Double
Min()
Function Min(ByRef pValue1 As Double, pValue2 As Double) As Double
MinInArray()
Function MinInArray(ByRef pArray As Variant) As Variant
Round()
Function Round(ByRef pValue As Double, pDecimals As Integer) As Double
SetEpsilon()
Sub SetEpsilon(ByRef pEpsilon As Double)
SwapValues()
Sub SwapValues(ByRef pValue1 As Variant, ByRef pValue2 As Variant)
77
LibOPrim
LibreOffice application primitives.
LibOPrim.App......................................................................81 IsMathDocument()........................................................86
ERR_LOPRIM_CMDUNK...........................................81 IsWriterDocument().....................................................87
LOPRIM_SERV_DISPATCH.......................................81 ModuleIdentifierStr()...................................................87
SetFullScreen()...............................................................81 OpenDocument()..........................................................87
ShowDocumentProperties().......................................81 OpenDocumentCopy()................................................87
ShowNavigator()...........................................................81 OpenDocumentEx()......................................................87
ShowPrinterDialog()....................................................81 LibOPrim.SpecialFiles........................................................88
ShowPrintPreview().....................................................81 CalcShareFileName()....................................................88
ShowSideBar()...............................................................81 GetLibreOfficeSpecialFileData()................................89
LibOPrim.DocCheckerClass.............................................82 IsCalcDocumentShared()............................................89
ERR_DOCCHKCLASS_NORUN................................82 LockFileName().............................................................89
ERR_DOCCHKCLASS_NONE...................................82 LibOPrim.Graphics.............................................................90
ERR_DOCCHKCLASS_CANTOPENSOURCE.......82 GetGraphicFromResource().......................................90
ERR_DOCCHKCLASS_SOURCENOTFOUND......82 GetImage()......................................................................90
ERR_DOCCHKCLASS_INCORRECTTYPE............82 GetImageManager()......................................................90
ERR_DOCCHKCLASS_CUSTOMPROPNAME.....82 LibOPrim.ToolBars..............................................................91
ERR_DOCCHKCLASS_CUSTOMPROPVALUE....82 ERR_TBAR_HIDDEN..................................................91
DOCCHKCLASS_DOCTYPE_NONE.......................82 ERR_TBAR_VISIBLE....................................................91
DOCCHKCLASS_DOCTYPE_WRITER..................82 ERR_TBAR_NONE.......................................................91
DOCCHKCLASS_DOCTYPE_WRITERWEB.........82 ERR_TBAR_UNKNOWN............................................91
DOCCHKCLASS_DOCTYPE_WRITERMASTER. 82 ERR_TBAR_DEL...........................................................91
DOCCHKCLASS_DOCTYPE_CALC.......................82 LOPRIM_TB_STANDARD.........................................91
DOCCHKCLASS_DOCTYPE_IMPRESS..................82 LOPRIM_TB_FIND.......................................................91
DOCCHKCLASS_DOCTYPE_DRAW......................82 LOPRIM_TB_FORMAT...............................................91
DOCCHKCLASS_DOCTYPE_MATH......................82 LOPRIM_TB_FULLSCREEN.......................................91
DOCCHKCLASS_DOCTYPE_CHART....................82 LOPRIM_TB_MENU....................................................91
DOCCHKCLASS_DOCTYPE_XFORMS..................82 LOPRIM_TB_STATUS.................................................91
DOCCHKCLASS_DOCTYPE_BASEAPP................82 CustomToolbarsToArray()..........................................91
LastError.........................................................................83 DeleteToolbar()..............................................................92
DocType..........................................................................83 DisplayToolbar()............................................................92
DocumentName............................................................83 GetToolbarResName().................................................92
AddPropertyCheck()....................................................83 HideToolbar().................................................................93
CheckDocument().........................................................83 ToolbarVisible().............................................................93
ClearError()....................................................................83 LibOPrim.CustomProperties............................................94
ClearPropertyChecks()................................................83 CPROP_TYPE_UNK.....................................................94
LibOPrim.Document..........................................................85 CPROP_TYPE_STRING...............................................94
ERR_LOPRIM_DOCTYPE..........................................85 CPROP_TYPE_NUMBER............................................94
LOPRIM_DOCTYPEUNK...........................................85 CPROP_TYPE_DATE...................................................94
LOPRIM_DOCTYPECALC.........................................85 CPROP_TYPE_UNODATE.........................................94
LOPRIM_DOCTYPEWRITER....................................85 CPROP_TYPE_UNODATETIME...............................94
LOPRIM_DOCTYPEIMPRESS...................................85 CPROP_TYPE_UNODURATION..............................94
LOPRIM_DOCTYPEDRAW.......................................85 CPROP_TYPE_YESNO.................................................94
LOPRIM_DOCTYPEMATH........................................85 ERR_CPROP_NORUN.................................................94
LOPRIM_DOCTYPEBASE..........................................85 ERR_CPROP_OK...........................................................94
CreateDocument()........................................................85 ERR_CPROP_CREATE................................................94
DocumentProtectionFlag().........................................85 ERR_CPROP_DELETE.................................................94
GetCurrentDirectory().................................................86 ERR_CPROP_NOTFOUND........................................94
GetLibODocumentType()...........................................86 ERR_CPROP_NAME....................................................94
IsBaseDocument().........................................................86 ERR_CPROP_EXISTS...................................................94
IsCalcDocument().........................................................86 ERR_CPROP_TYPE......................................................94
IsDrawDocument().......................................................86 CreateCustomProperty().............................................95
IsImpressDocument()...................................................86 CustomPropertyExists()..............................................95
79
LibO Primitives
CustomPropertiesToArray().......................................95 LastStep...........................................................................99
CustomPropertyType()................................................95 ProgressBar....................................................................99
DeleteAllCustomProperties().....................................96 AddStep()........................................................................99
DeleteCustomProperty().............................................96 AddSteps().......................................................................99
GetCustomProperty()..................................................96 NextStep().......................................................................99
GetCustomPropertyValue()........................................96 ProgressEnd()...............................................................100
SetCustomPropertyValue().........................................97 ProgressStart().............................................................100
LibOPrim.ProgressClass....................................................98 SetFirstStep()................................................................100
rMessage.........................................................................98 SetLastStep().................................................................100
rDelay..............................................................................98 LibOPrim.UNO..................................................................101
CreateProgressStepInformation().............................98 ImplementsUNOstruct()............................................101
CurrentStep....................................................................99 LibOPrim.Extensions.......................................................102
CurrentStepNum...........................................................99 ExtensionDir().............................................................102
FirstStep..........................................................................99
80
LibOPrim.App
LibOPrim.App
Dependencies: (none)
This module is related to the LibreOffice application as a whole.
Global Constants
Constant name Value Description
Error Constants
ERR_LOPRIM_CMDUNK 3 Unknown command.
Misc.
LOPRIM_SERV_DISPATCH "com.sun.star.frame.DispatchHelper" The dispatcher call.
Primitives
SetFullScreen()
Sub SetFullScreen(Optional ByRef pShowToolbar As Boolean)
ShowDocumentProperties()
Sub ShowDocumentProperties()
ShowNavigator()
Sub ShowNavigator(ByRef pShow As Boolean)
ShowPrinterDialog()
Sub ShowPrinterDialog()
ShowPrintPreview()
Sub ShowDocumentPreview()
ShowSideBar()
Sub ShowSidebar(ByRef pShow As Boolean)
81
LibO Primitives
LibOPrim.DocCheckerClass
Dependencies: none.
A LibreOffice document checking class.
This class allow to create a set of checks to carry against a given document, making easier to find
if this document satisfies the requirements.
Currently, this class offers checks against:
The document type (Writer, Calc, etc.).
The presence and value of custom properties.
This class may be used stand-alone. It is also used internally by the CalcImportClass (optionnally)
for which it was initially intended.
Global Constants
Constant name Value Description
Error Constants
ERR_DOCCHKCLASS_NORUN -1 Process did not run.
ERR_DOCCHKCLASS_NONE 0 No error (OK).
ERR_DOCCHKCLASS_CANTOPENSOURCE 1 Source document cant be opened.
ERR_DOCCHKCLASS_SOURCENOTFOUND 2 Document file wasnt found.
ERR_DOCCHKCLASS_INCORRECTTYPE 3 Document is not a spreadsheet.
ERR_DOCCHKCLASS_CUSTOMPROPNAME 4 Custom property not found.
ERR_DOCCHKCLASS_CUSTOMPROPVALUE 5 Custom property value not found.
Misc.
DOCCHKCLASS_DOCTYPE_NONE 0 (none/unknown).
DOCCHKCLASS_DOCTYPE_WRITER 1 Writer.
DOCCHKCLASS_DOCTYPE_WRITERWEB 2 Writer/Web.
DOCCHKCLASS_DOCTYPE_WRITERMASTER 3 Writer/Master document.
DOCCHKCLASS_DOCTYPE_CALC 4 Calc.
DOCCHKCLASS_DOCTYPE_IMPRESS 5 Impress.
DOCCHKCLASS_DOCTYPE_DRAW 6 Draw.
DOCCHKCLASS_DOCTYPE_MATH 7 Math.
DOCCHKCLASS_DOCTYPE_CHART 8 Chart.
DOCCHKCLASS_DOCTYPE_XFORMS 9 XML / XForms.
DOCCHKCLASS_DOCTYPE_BASEAPP 10 Base main application.
82
LibOPrim.DocCheckerClass
Properties
Property Type Description
LastError Long [RO] The last error that occurred.
DocType Byte [R/W] The document type to check.
The document type value is one of the DOCCHKCLASS_DOCTYPE_XXX
constants.
The default DOCCHKCLASS_DOCTYPE_NONE bypasses the document
type check.
DocumentName String [R/W] The name of the document to check (FQN), in OS or URL form.
Methods
Public
AddPropertyCheck()
Public Sub AddPropertyCheck(ByRef pPropName As String, pValue As
Variant)
CheckDocument()
Public Function CheckDocument() As Integer
ClearError()
Public Sub ClearError()
ClearPropertyChecks()
Public Sub ClearPropertyChecks()
83
LibO Primitives
Private
(private methods names are prefixed with underscores “_”)
They are not intended for use out of the class.
_AddCollectionItem()
Private Sub _AddCollectionItem(ByRef pColl As Object, ByRef pItem As
Variant, pKey As String)
_DocTypeStr()
Private Function _DocTypeStr() As String
_OpenDocument()
Private Function _OpenDocument(ByRef pFileName As String, Optional
pHidden As Boolean, Optional pReadOnly As Boolean) As Object
Opens the document to check in the background and returns that object or Null if a
problem occurred.
Example
1 Dim oDocChecker As Object
2 Dim Result As Integer
3 Set oDocChecker = New DocCheckerClass
4 oDocChecker.DocumentName = "C:\Path\To\Somefile.odt"
5 oDocChecker.DocType = DOCCHKCLASS_DOCTYPE_WRITER
6 oDocChecker.AddPropertyCheck("ApplicationName", "MyApp")
7 Result = oDocChecker.CheckDocument()
where Result holds the check result (see the ERR_DOCCHKCLASS_XXX constants above).
84
LibOPrim.Document
LibOPrim.Document
Dependencies: (none)
This module relates to the open documents in any of the LibreOffice modules.
Global Constants
Constant name Value Description
Error constants
ERR_LOPRIM_DOCTYPE -1
LOPRIM_DOCTYPEUNK 0
LOPRIM_DOCTYPECALC 1
LOPRIM_DOCTYPEWRITER 2
LOPRIM_DOCTYPEIMPRESS 3
LOPRIM_DOCTYPEDRAW 4
LOPRIM_DOCTYPEMATH 5
LOPRIM_DOCTYPEBASE 6
Primitives
CreateDocument()
Function CreateDocument(ByRef pType As Long, pHidden As Boolean,
pReadOnly As Boolean) As Object
DocumentProtectionFlag()
Function DocumentProtectionFlag(ByRef pDocURL As String) As Integer
85
LibO Primitives
GetCurrentDirectory()
Function GetCurrentDirectory() As String
GetLibODocumentType()
Function GetLibODocumentType(Optional ByRef pDoc As Object) As Long
IsBaseDocument()
Function IsBaseDocument(Optional ByRef pDoc As Object) As Boolean
Returns True if pDoc is a Base document, otherwise False. If omitted, looks at the
current document.
Note: if an error code is returned by GetLibODocType, it returns False as well.
IsCalcDocument()
Function IsCalcDocument(Optional ByRef pDoc As Object) As Boolean
Returns True if pDoc is a Calc document, otherwise False. If omitted, looks at the
current document.
Note: if an error code is returned by GetLibODocType, it returns False as well.
IsDrawDocument()
Function IsDrawDocument(Optional ByRef pDoc As Object) As Boolean
Returns True if pDoc is a Draw document, otherwise False. If omitted, looks at the
current document.
Note: if an error code is returned by GetLibODocType, it returns False as well.
IsImpressDocument()
Function IsImpressDocument(Optional ByRef pDoc As Object) As Boolean
IsMathDocument()
Function IsMathDocument(Optional ByRef pDoc As Object) As Boolean
Returns True if pDoc is a Math document, otherwise False. If omitted, looks at the
current document.
Note: if an error code is returned by GetLibODocType, it returns False as well.
86
LibOPrim.Document
IsWriterDocument()
Function IsWriterDocument(Optional ByRef pDoc As Object) As Boolean
Returns True if pDoc is a Writer document, otherwise False. If omitted, looks at the
current document.
Note: if an error code is returned by GetLibODocType, it returns False as well.
ModuleIdentifierStr()
Function ModuleIdentifierStr(Optional ByRef pDoc As Object) As String
OpenDocument()
Function OpenDocument(ByRef pFileName As String, pHidden As Boolean,
pReadOnly As Boolean, pAsTemplate As Boolean) As Object
OpenDocumentCopy()
Function OpenDocumentCopy(ByRef pTgtFileName As String, Optional
pHidden As Boolean, Optional ByRef pSrcDoc) As Object
OpenDocumentEx()
Function OpenDocumentEx(ByRef pFileName As String, pOptions As Variant)
As Object
TBD
87
LibO Primitives
LibOPrim.SpecialFiles
Dependencies: IOPrim.Files, IOPrim.TextFiles, StringPrim.Strings
This module helps managing the LibreOffice special files. These special files are the lock files and
the (Calc-only) share files. These are automatically created by LibreOffice whenever a document is
opened (lock file) or a Calc spreadsheet for which the share mode is enabled (share file).
The special file naming is similar in both situations:
• .~lock.somefile.odt# (all modules)
The file is opened in write mode.
• .~sharing.somefile.ods# (Calc-only)
The Calc spreadsheet is opened and is set for share mode ( Tools > Share mode).
where the somefile.od? part is the name of the associated user’s file name. These special files
are always created in the same directory as the user’s file.
The primitives here allow to check that a special file is present, read it and gain access to its con-
tents. This may be of use particularly when using the Calc share mode.
Primitives
CalcShareFileName()
Function CalcShareFileName(Optional ByRef pDoc As Object) As
String
88
LibOPrim.SpecialFiles
GetLibreOfficeSpecialFileData()
Function GetLibreOfficeSpecialFileData(ByRef pSpecialFileName As
String) As Variant
IsCalcDocumentShared()
Function IsCalcDocumentShared(Optional ByRef pDoc As Object) As
Boolean
LockFileName()
Function LockFileName(Optional ByRef pDoc As Object) As String
89
LibO Primitives
LibOPrim.Graphics
Dependencies: (none)
Global Constants
Constant name Value Description
Primitives
GetGraphicFromResource()
Function GetGraphicFromResource(ByRef pGraphicName As String, Optional
ByRef pDoc As Object) As Object
GetImage()
Function GetImage(ByRef pFileName As String) As Variant
GetImageManager()
Function GetImageManager(Optional ByRef pDoc As Object) As Object
Returns the ImageManager object for the current LibreOffice module (Writer, Base,
etc ).
Input
pDoc: (optional) the document to process.
Defaults to the current document.
Adapted from librebel in https://ask.libreoffice.org/en/question/111748/how-to-
change-toolbar-icon-back-to-text/
90
LibOPrim.ToolBars
LibOPrim.ToolBars
Global Constants
Constant name Value Description
Error Constants
ERR_TBAR_HIDDEN -2 (pseudo-error) the toolbar is
hidden
ERR_TBAR_VISIBLE -1 (pseudo-error) the toolbar is
visible
ERR_TBAR_NONE 0 No error.
ERR_TBAR_UNKNOWN 1 Unknown toolbar.
ERR_TBAR_DEL 2 The specified toolbar can’t be
deleted (typically applies to
LibreOffice native toolbar).
LibreOffice Toolbar Resource Names
LOPRIM_TB_STANDARD "private:resource/toolbar/ Resource name for the Standard
standardbar"
toolbar.
LOPRIM_TB_FIND "private:resource/toolbar/ Resource name for the Find
findbar"
toolbar.
LOPRIM_TB_FORMAT "private:resource/toolbar/ Resource name for the Format
formatobjectbar"
toolbar.
LOPRIM_TB_FULLSCREEN "private:resource/toolbar/ Resource name for the FullScreen
fullscreenbar"
toolbar.
LOPRIM_TB_MENU "private:resource/menubar/ Resource name for the Menu
menubar"
toolbar.
LOPRIM_TB_STATUS "private:resource/statusbar/ Resource name for the Status
statusbar"
toolbar.
Primitives
CustomToolbarsToArray()
Function CustomToolbarsToArray(Optional ByRef pDoc As Object) As
Variant
Returns an array that holds data about all custom toolbars within a document.
Input
pDoc: (optional) the document to explore.
Defaults to the current document.
Ouput
The returned array is a 2-dimension structure:
array(toolbar count, 2)
Adapted from Loopingss message, in
https://forum.openoffice.org/fr/forum/viewtopic.php?f=15&t=27370
91
LibO Primitives
DeleteToolbar()
Function DeleteToolbar(ByRef pToolbarName As String, Optional ByRef
pDoc As Object) As Long
DisplayToolbar()
Function DisplayToolbar(ByRef pToolbarName As String, Optional ByRef
pDoc As Object) As Long
Shows a toolbar.
Input
pToolbarName: the toolbar name.
pToolbarName can be either the UI name (ex. local document toolbars) or the
resource name (eg. LibreOffice native toolbars; see the LOPRIM_TB_XXX constants).
pDoc: the document (defaults to ThisComponent)
Output
Returns an error code:
ERR_TBAR_NONE: no error.
ERR_TBAR_UNKNOWN: the specified toolbar is unknown
ERR_TBAR_DEL: the specified toolbar can’t be displayed (LibO toolbars)
GetToolbarResName()
Function GetToolbarResName(ByRef pUIToolbarName As String, Optional
pDoc As Object) As String
92
LibOPrim.ToolBars
HideToolbar()
Function HideToolbar(ByRef pToolbarName As String, Optional ByRef pDoc
As Object) As Long
Hides a toolbar.
Input
pToolbarName: the toolbar name.
pToolbarName can be either the UI name (ex. local document toolbars) or the
resource name (eg. LibreOffice native toolbars; see the LOPRIM_TB_XXX constants).
pDoc: the document (defaults to ThisComponent)
Output
Returns an error code:
ERR_TBAR_NONE: no error.
ERR_TBAR_UNKNOWN: the specified toolbar is unknown
ERR_TBAR_HIDDEN: the specified toolbar is already hidden (LibO toolbars)
ToolbarVisible()
Function ToolbarVisible(ByRef pToolbarName As String, Optional ByRef
pDoc As Object) As Long
93
LibO Primitives
LibOPrim.CustomProperties
LibreOffice document custom properties management.
Dependencies: LibOPrim.UNO
Global Constants
Constant name Value Description
Custom property types
CPROP_TYPE_UNK -1 Unknown type.
CPROP_TYPE_STRING 1 String type.
CPROP_TYPE_NUMBER 2 Numeric type.
CPROP_TYPE_DATE 3 Date type.
CPROP_TYPE_UNODATE 4 UNO date type.
CPROP_TYPE_UNODATETIME 5 UNO datetime type.
CPROP_TYPE_UNODURATION 6 UNO duration.
CPROP_TYPE_YESNO 7 Boolean value (aka Yes/no)
Errors
ERR_CPROP_NORUN -1 The process did not run.
ERR_CPROP_OK 0 No error.
ERR_CPROP_CREATE 1 The property could not be created.
ERR_CPROP_DELETE 2 The property could not be deleted
ERR_CPROP_NOTFOUND 3 The property was not found.
ERR_CPROP_NAME 4 Illegal property name.
ERR_CPROP_EXISTS 5 The property name already exists.
ERR_CPROP_TYPE 6 Not supported type for a property.
94
LibOPrim.CustomProperties
Primitives
CreateCustomProperty()
Function CreateCustomProperty(ByRef pArrProps As Variant, Optional
ByRef pDoc As Object) As Long
CustomPropertyExists()
Function CustomPropertyExists(ByRef pName As String, Optional ByRef
pDoc As Object) As Boolean
CustomPropertiesToArray()
Function CustomPropertiesToArray(Optional ByRef pDoc As Object) As
Variant
CustomPropertyType()
Function CustomPropertyType(ByRef pValue As Variant) As Integer
95
LibO Primitives
DeleteAllCustomProperties()
Sub DeleteAllCustomProperties(Optional ByRef pDoc As Object)
DeleteCustomProperty()
Function DeleteCustomProperty(ByRef pName As String, Optional pDoc
As Object) As Long
GetCustomProperty()
Function GetCustomProperty(ByRef pName As String, Optional pDoc As
Object) As Object
GetCustomPropertyValue()
Function GetCustomPropertyValue(ByRef pName As String, Optional
pDocument As Object) As Variant
96
LibOPrim.CustomProperties
SetCustomPropertyValue()
Function SetCustomPropertyValue(ByRef pName As String, pValue As
Variant, Optional pDoc As Object) As Long
97
LibO Primitives
LibOPrim.ProgressClass
Dependencies: (none)
This class is very similar to the FormPrim.ProgressWidgetClass(see page 163. While that one is a
form progress bar class, this ProgressClass is dedicated to all-purpose displaying and managing
progress actions.
A progress bar management class for user feedback during lengthy processes.
This class encapsulates the LibreOffice documents progressbar functionalities. It aims at providing
an entry point where to manage progress bars steps, messages and display delays.
This class defines the properties of a progress bar:
a progress bar object.
messages and delays for the different process steps.
messages and delays for startup and termination steps.
TProgressStepInformation
This structure stores a message and a display delay for a given progress step.
Member name Type Description
rMessage String The message to display for a given step.
rDelay Long The message display delay, in ms..
Primitives
This module offers a factory function that can create an object of TProgressStepInformation.
Call it from your code to initialize such objects.
CreateProgressStepInformation()
Function CreateProgressStepInformation(Optional ByRef pMsg As
String, Optional ByRef pDelay As Long) As
TProgressStepInformation
98
LibOPrim.ProgressClass
Properties
Property Type Description
CurrentStep Object [RO] The progress current step information.
Returns an object of TProgressStepInformation type.
CurrentStepNum Long [RO] The progress current step number.
The steps are numbered from 0 (first), then 1 (first added step) to N
(nth added step) then -1 (last).
FirstStep Object [RO] The progress first step information
Returns an object of TProgressStepInformation type.
Use SetFirstStep() method to set this object.
LastStep Object [RO] The progress last step information
Returns an object of TProgressStepInformation type.
Use SetLastStep() method to set this object.
ProgressBar Object [R/W] The progress bar to show.
Set it from a document .CurrentController.StatusIndicator
object.
Methods
Public
AddStep()
Public Sub AddStep(ByRef pMsg As String, Optional pDelay As Long)
AddSteps()
Public Sub AddSteps(ByRef pArrSteps As Variant)
NextStep()
Public Sub NextStep(Optional ByRef pInc As Long, Optional ByRef pMsg As
String)
99
LibO Primitives
ProgressEnd()
Public Sub ProgressEnd(Optional ByRef pMsg As String)
ProgressStart()
Public Sub ProgressStart(Optional ByRef pMsg As String)
SetFirstStep()
Public Sub SetFirstStep(ByRef pMsg As String, Optional pDelay As Long)
SetLastStep()
Public Sub SetLastStep(ByRef pMsg As String, Optional pDelay As Long)
Private
(private methods are prefixed with underscores “_”)
These are not intended for use out of the class.
_AddCollectionItem()
Private Sub _AddCollectionItem(ByRef pColl As Object, ByRef pItem As
Variant, pKey As String)
_ArrayExists()
Private Function _ArrayExists(ByRef pArray As Variant) As Boolean
100
LibOPrim.UNO
LibOPrim.UNO
Dependencies: (none)
Global Constants
Constant name Value Description
Primitives
ImplementsUNOstruct()
Function ImplementsUNOstruct(ByRef pStruct As Object, ByRef pStructName
As String) As Boolean
101
LibO Primitives
LibOPrim.Extensions
Dependencies: (none)
Global Constants
Constant name Value Description
Primitives
ExtensionDir()
Function ExtensionDir(ByRef pExtID As String) As String
102
CalcPrim
Primitives for the LibreOffice Calc module.
CalcPrim.Functions..........................................................105 ColumnIndexFromReference()................................114
CalcFunc_CountIf()....................................................105 CopyUsedRange().......................................................115
CalcFunc_FilterXML()...............................................105 CreateCalcRangeEnumerator()................................115
CalcFunc_Match().......................................................105 FetchInRangeColumn().............................................115
CalcFunc_VLookup()..................................................105 FormatRange().............................................................116
CalcFunc_WebService().............................................106 GetAdjustedRange()...................................................116
GetCalcFunctionObject()..........................................106 GetDataArea().............................................................116
RunSpreadsheetFunction().......................................106 GetNamedCell()..........................................................117
_CalcFuncRange().......................................................106 GetNamedCellString()...............................................117
CalcPrim.Spreadsheet......................................................107 GetNamedCellValue()................................................117
ShowColumns()...........................................................107 GetNamedRange()......................................................117
ShowInputLine().........................................................107 GetRange()....................................................................118
ShowRows().................................................................107 GetRangeColumn().....................................................118
ToggleGrid().................................................................107 GetRangeFromColumns().........................................118
CalcPrim.Sheet..................................................................108 GetRangeFromRows()................................................119
COLMAX400................................................................108 GetRangeRow()...........................................................119
ERR_ROWINDEX_EMPTY......................................108 GetRangeType()..........................................................119
ERR_ROWINDEX_UNKSHEET..............................108 GotoLastCell()..............................................................119
ERR_ROWINDEX_UNKSHEETINDEX................108 IsRangeInRange()........................................................120
ERR_ROWINDEX_UNKSHEETNAME.................108 IsRangeInRanges()......................................................120
ERR_ROWINDEX_UNKCOLINDEX.....................108 PasteSpecial()...............................................................120
ERR_ROWINDEX_UNKCOLNAME......................108 PasteTransferable().....................................................120
GetColNameFromNumber().....................................108 RangeAddressFromReference()...............................121
GetSheet().....................................................................108 RangeAddrString()......................................................121
LastRowIndex()...........................................................109 RangeAsSheetCellRange()........................................121
LastUsedCell()..............................................................109 SetActiveCellByName()............................................121
LastUsedColumn()......................................................109 SetActiveSheetByName()..........................................122
LastUsedRow().............................................................109 SetNamedCellValue().................................................122
ProtectSheet()..............................................................110 ShiftRange()..................................................................122
ProtectSheetByName()..............................................110 UpdateRangeColumnValues()..................................123
ShowSheetByName().................................................110 UpdateRangeMultiColumnValues().......................124
CalcPrim.RangeCell..........................................................111 UpdateRangeMultiColumnValuesArray()............125
ERR_RANGE_ENUMERATOR................................111 UsedRange().................................................................125
ERR_RANGE_OUTOFBOUNDS.............................111 VLookupCell().............................................................126
ERR_RANGE_NOEXEC............................................111 CalcPrim.Document.........................................................127
ERR_RANGE_OK.......................................................111 SecureCalcUI().............................................................127
ERR_RANGE_UNK....................................................111 CalcPrim.CalcExportClass..............................................128
ERR_RANGE_NONE.................................................111 ERR_CALCEXPORTCLASS_NORUN....................128
ERR_RANGE_ARRAY...............................................111 ERR_CALCEXPORTCLASS_NONE.......................128
ERR_RANGE_SRCSHEET........................................111 ERR_CALCEXPORTCLASS_CANTCREATEFILE
ERR_RANGE_TGTSHEET........................................111 .........................................................................................128
RANGETYPE_NULL..................................................111 ERR_CALCEXPORTCLASS_CANTOPENSOURCE
RANGETYPE_UNK....................................................111 .........................................................................................128
RANGETYPE_CELL...................................................111 ERR_CALCEXPORTCLASS_SOURCENOTFOUND
RANGETYPE_RANGE..............................................111 .........................................................................................128
RANGETYPE_RANGES............................................111 ERR_CALCEXPORTCLASS_CANTWRITEFILE 128
RANGETYPE_NAMED.............................................111 ERR_CALCEXPORTCLASS_NOTASPREADSHEE
RANGE_NONE...........................................................111 T......................................................................................128
ArrayFromVectorRangeName()..............................112 ERR_CALCEXPORTCLASS_SOURCEUNDEFINED
CalcValue()...................................................................112 .........................................................................................128
CellAddressFromReference()...................................112 ERR_CALCEXPORTCLASS_TARGETUNDEFINED
ClearRange()................................................................113 .........................................................................................128
ClearRangeContents()...............................................113 ERR_CALCEXPORTCLASS_NOTHINGTOEXPOR
ClearRanges()...............................................................114 T......................................................................................128
103
LibO Primitives
ERR_CALCEXPORTCLASS_CUSTOMPROP......128 SourceRangeAddress..................................................135
Self..................................................................................128 SourceSheetName.......................................................135
Application...................................................................128 TargetSheetName.......................................................135
LastError.......................................................................128 AddEmptyColumn()...................................................136
Progress.........................................................................128 AddEmptyRow()..........................................................136
SheetInformation........................................................128 AddRemoveColumn()................................................136
SourceDocument.........................................................129 AddRemoveRow().......................................................136
TargetDocumentName..............................................129 ClearEmptyColumns()...............................................136
Version..........................................................................129 ClearEmptyRows().....................................................136
AddAllSheets().............................................................129 ClearIgnoredColumns().............................................136
AddSheet()....................................................................129 ClearIgnoredRows()...................................................136
AddSheetInfo()............................................................129 ClearRangeAddress()..................................................136
ClearError()..................................................................129 CalcPrim.CalcImportClass..............................................138
ClearSelection()...........................................................129 Self..................................................................................138
Execute().......................................................................129 DocChecker..................................................................138
GetSheetInformation()..............................................130 LastError.......................................................................138
Reset()............................................................................130 Progress.........................................................................138
CalcPrim.CalcExportPropertyClass..............................135 SheetInformation........................................................138
EmptyColumns............................................................135 SourceDocType...........................................................138
EmptyRows..................................................................135 SourceDocument.........................................................138
RemoveColumns.........................................................135 SourceDocumentName..............................................139
RemoveRows...............................................................135 TargetDocument.........................................................139
Self..................................................................................135 CalcPrim.CalcImportPropertyClass..............................140
104
CalcPrim.Functions
CalcPrim.Functions
Dependencies: (none)
Execute Calc functions. The programmatic versions of some Calc functions are only meant as ex-
amples of what can be done with all Calc functions.
CalcFunc_CountIf()
Function CalcFunc_CountIf(ByRef pRange As Object, pCriterion As
Variant) As Variant
CalcFunc_FilterXML()
Function CalcFunc_FilterXML(ByRef pXMLdoc As String, pXPath As String)
As Variant
CalcFunc_Match()
Function CalcFunc_Match(ByRef pSearch As Variant, pVector As Object,
Optional pMode As Integer) As Long
CalcFunc_VLookup()
Function CalcFunc_VLookup(ByRef pSearch As Variant, pRange As Object,
pLookup As Integer, Optional pExact As Byte) As Variant
105
LibO Primitives
CalcFunc_WebService()
Function CalcFunc_WebService(Byref pURI As String) As Variant
GetCalcFunctionObject()
Function GetCalcFunctionObject() As Object
RunSpreadsheetFunction()
Function RunSpreadsheetFunction(ByRef pFuncName As String, pArrParams()
As Variant) As Variant
Internal subprograms
_CalcFuncRange()
Function _CalcFuncRange(ByRef pRange As Object) As Object
106
CalcPrim.Spreadsheet
CalcPrim.Spreadsheet
Dependencies: (none)
Calc spreadsheet subprograms.
ShowColumns()
Sub ShowColumns(ByRef pSheetName As String, pRangeName As String, ByRef
pVisible As Boolean, ByRef Optional pDoc)
ShowInputLine()
Sub ShowInputLine(ByRef pVisible As Boolean)
ShowRows()
Sub ShowRows(ByRef pSheetName As String, pRangeName As String, pVisible
As Boolean, Optional ByRef pDoc As Object)
ToggleGrid()
Sub ToggleGrid()
107
LibO Primitives
CalcPrim.Sheet
Dependencies: (none)
Global Constants
Constant name Value Description
COLMAX400 1024 The maximum number of columns
in a sheet (as of LibreOffice v.4.0
onwards).
LastRowIndex() function return
errors
ERR_ROWINDEX_EMPTY -1 The column is empty (this is not
an error per se).
ERR_ROWINDEX_UNKSHEET -2 The sheet is unknown.
ERR_ROWINDEX_UNKSHEETINDEX -3 The sheet index doesn’t exist.
ERR_ROWINDEX_UNKSHEETNAME -4 The sheet name doesn’t exist.
ERR_ROWINDEX_UNKCOLINDEX -5 The column index doesn’t exist.
ERR_ROWINDEX_UNKCOLNAME -6 The column name doesn’t exist.
Primitives
GetColNameFromNumber()
Function GetColNameFromNumber(ByRef pNum As Long) As String
GetSheet()
Function GetSheet(Optional ByRef pSheetRef As Variant, Optional pDoc As
Object) As Object
108
CalcPrim.Sheet
LastRowIndex()
Function LastRowIndex(ByRef pColRef As Variant, Optional ByRef
pSheetRef As Variant, Optional ByRef pDoc As Object) As Long
Returns the index of the last row with data in a column of a sheet.
Input
pColRef: the name or the index of the column to check.
Ex: "A" or 0
pSheetRef: (optional) the name or the index of the sheet to process or an
initialized sheet object.
Ex: "Sheet1" or 0 or MySheet
Defaults to the active sheet.
pDoc: (optional) the document object in which to check.
Defaults to the current document.
Output
The row index for the last used cell in the given column ( 0 or value above 0) or a
negative number as an error flag.
Possible error values (see the ERR_ROWINDEX_XXX constants above):
ERR_ROWINDEX_EMPTY: the whole column is empty.
ERR_ROWINDEX_UNKSHEET: the sheet was not found.
ERR_ROWINDEX_UNKCOLINDEX: the index of the column doesn’t exist.
ERR_ROWINDEX_UNKCOLNAME: the name of the column doesn’t exist.
Adapted and edited from Martius code in
https://forum.openoffice.org/en/forum/viewtopic.php?f=20&t=10817
Usage
x = LastRowIndex("a", "Sheet3")
x = LastRowIndex(5, "Sheet3")
x = LastRowIndex(2000)
LastUsedCell()
Function LastUsedCell(ByRef pSheet As Object) As Object
Returns the last used cell in a given sheet (the one at the lower-right angle).
Input
pSheet: the sheet object to explore.
Output
The last used cell object in the sheet (the one at the lower-right angle).
LastUsedColumn()
Function LastUsedColumn(ByRef pSheet As Object) As Long
LastUsedRow()
Function LastUsedRow(ByRef pSheet As Object) As Long
109
LibO Primitives
ProtectSheet()
Function ProtectSheet(ByRef pSheet As Object, pProtect As Boolean,
Optional pPwd As String) As Integer
ProtectSheetByName()
Function ProtectSheetByName(ByRef pSheetName As String, pProtect As
Boolean, pPwd As String, Optional ByRef pDoc As Object) As Integer
ShowSheetByName()
Sub ShowSheetByName(ByRef pSheetName As String, pVisible As Boolean,
Optional ByRef pDoc As Object)
110
CalcPrim.RangeCell
CalcPrim.RangeCell
Dependencies: (none)
Macros for spreadsheet cells and ranges.
Global Constants
Constant name Value Description
Errors
ERR_RANGE_ENUMERATOR -3 The enumerator couldn’t be
created.
ERR_RANGE_OUTOFBOUNDS -2 The (column/row) index is out of
the range bounds.
ERR_RANGE_NOEXEC -1 Operation not executed.
ERR_RANGE_OK 0 The operation was completed
without error.
ERR_RANGE_UNK 10001 The specified range is
unknown/unset.
ERR_RANGE_NONE 10002 The range is empty.
ERR_RANGE_ARRAY 10003 The specified array is invalid.
ERR_RANGE_SRCSHEET 10004 The source sheet doesn’t exist.
ERR_RANGE_TGTSHEET 10005 The target sheet doesn’t exist.
Range Types
RANGETYPE_NULL -1 The range object is Null
(undefined).
RANGETYPE_UNK 0 The object type is unknown (not a
range).
RANGETYPE_CELL 1 The object is a single cell.
RANGETYPE_RANGE 2 The object is a single range.
RANGETYPE_RANGES 3 The object is a multiple range.
RANGETYPE_NAMED 4 The object is a named range.
Misc.
RANGE_NONE -1 The range is not contained in any
of the outer ranges.
111
LibO Primitives
Primitives
ArrayFromVectorRangeName()
Function ArrayFromVectorRangeName(ByRef pRangeName As String,
Optional pIgnoreEmpty As Boolean, Optional ByRef pDoc As
Object) As Variant
CalcValue()
Function CalcValue(ByRef pValue As Variant) As Variant
Converts any value to a data type a Calc cell can store, that is, numeric
or string.
Input
pValue: the value to convert.
Output
The converted value into a numeric or string type, which may be stored
into a Calc cell object (using Cell.Value property).
When a type cannot be converted (ex: object), the function result is 0.
CellAddressFromReference()
Function CellAddressFromReference(ByRef pCellRef As String,
Optional ByRef pDoc As Object) As Object
112
CalcPrim.RangeCell
ClearRange()
Function ClearRange(ByRef pRange As Object, pMode As Integer,
Optional pPwd As String) As Long
ClearRangeContents()
Function ClearRangeContents(ByRef pSheetRef As Variant,
pRangeRef As Variant, pMode As Integer, Optional pPwd As
String, Optional pDoc As Object) As Long
113
LibO Primitives
ClearRanges()
Function ClearRanges(ByRef pRangeInfo As Variant, pMode As
Integer, Optional ByRef pDoc As Object, Optional pProgress As
Object) As Long
ColumnIndexFromReference()
Function ColumnIndexFromReference(ByRef pCellRef As String,
Optional ByRef pDoc As Object) As Long
114
CalcPrim.RangeCell
CopyUsedRange()
Function CopyUsedRange(ByRef pSourceDoc As Object,
pSourceSheetName As String, pTargetDoc As Object,
pTargetSheetName As String, Optional ByRef pOrigin As String)
As Long
CreateCalcRangeEnumerator()
Function CreateCalcRangeEnumerator(ByRef pRange As Object) As
Object
FetchInRangeColumn()
Function FetchInRangeColumn(ByRef pSearch As Variant, pRange
As Object, pSearchCol As Integer, pFetchCol As Integer) As
Variant
115
LibO Primitives
FormatRange()
Function FormatRange(ByRef pRange As Object, pFormatStr As
String, Optional pIsTemp As Boolean, Optional pDoc As Object)
As Long
GetAdjustedRange()
Function GetAdjustedRange(ByRef pRefRange As Object,
pTopLeftCell As Object) As Object
GetDataArea()
Function GetDataArea(ByRef pDoc As Object, pSheetRef As
Variant, Optional pTopLeftCellAddr As Variant) As Object
116
CalcPrim.RangeCell
GetNamedCell()
Function GetNamedCell(ByRef pName As String, Optional ByRef
pDoc As Object) As Object
GetNamedCellString()
Function GetNamedCellString(ByRef pName As String, Optional
ByRef pDoc As Object) As String
GetNamedCellValue()
Function GetNamedCellValue(ByRef pName As String, Optional
ByRef pDoc As Object) As Variant
GetNamedRange()
Function GetNamedRange(ByRef pSheetName As String, pRangeName
As String, Optional ByRef pDoc As Object) As Object
Returns a range object from a sheet name and the range name.
Input
pSheetName: the sheet name
pRangeName: the searched range name.
The range name is a user-defined name (ex. MyRange).
The range name may apply to any range type: single cell, single range,
multiple range or named range.
pDoc: (optional) the document object.
Defaults to the current spreadsheet.
Output
The range object or Null if not found.
117
LibO Primitives
GetRange()
Function GetRange(Optional pRangeRef As Variant, Optional
ByRef pSheetRef As Variant, Optional pDoc As Object) As
Object
GetRangeColumn()
Function GetRangeColumn(ByRef pRange As Object, pColNum As
Integer) As Object
GetRangeFromColumns()
Function GetRangeFromColumns(ByRef pSheet As Object,
pStartColumn As Integer, Optional pEndColumn As Integer) As
Object
118
CalcPrim.RangeCell
GetRangeFromRows()
Function GetRangeFromRows(ByRef pSheet As Object, pStartRow
As Integer, Optional pEndRow As Integer) As Object
GetRangeRow()
Function GetRangeRow(ByRef pRange As Object, pRowNum As
Integer) As Object
GetRangeType()
Function GetRangeType(ByRef pRange As Object) As Integer
GotoLastCell()
Sub GotoLastCell(ByRef pSheet As Object, pSearchColNum As
Integer, pColNum As Integer, Optional ByRef pDoc As Object)
Searches the last data cell in a given column of a sheet, then moves the
active cell on the same row to another column of the same sheet.
Input
pSheet: the sheet object to process.
pSearchColNum: the column number to search for absence of data (0-
based: 0 = A; 1 = B; etc.).
pColNum: the column number to reach.
pColNum may be the same as pSearchColNum.
pDoc: (optional) the document to process.
Defaults to the current document.
119
LibO Primitives
IsRangeInRange()
Function IsRangeInRange(ByRef pInnerRange As Object,
pOuterRange As Object) As Boolean
IsRangeInRanges()
Function IsRangeInRanges(ByRef pInnerRange As Object,
pOuterRanges As Variant) As Integer
Tests whether a range is fully contained within another from a range set
(multi-range array).
Input
pInnerRange: the inner cell range.
pOuterRanges: the outer cell ranges array.
This array may be obtained using:
Const THERANGES = "Sheet1.A3:B4;Sheet4.C10;Sheet1.H2:K157"
ARangesArray =
MyDocument.Sheets.getCellRangesByName(THERANGES)
Output
The outer range array index in which the inner one is contained or -1
(RANGE_NONE) if it is not contained in any.
PasteSpecial()
Sub PasteSpecial(ByRef pSrcDoc As Object, pSrcRange As
Object, pTgtDoc As Object, pTgtRange As Object)
PasteTransferable()
Sub PasteTransferable(ByRef pSrcDoc As Object, pSrcRange As
Object, pTgtDoc As Object, pTgtRange As Object)
120
CalcPrim.RangeCell
RangeAddressFromReference()
Function RangeAddressFromReference(ByRef pRangeRef As String,
Optional ByRef pDoc As Object) As Object
RangeAddrString()
Function RangeAddrString(ByRef pDocument As Object,
pRangeAddr As Object) As String
RangeAsSheetCellRange()
Function RangeAsSheetCellRange(ByRef pRange As Object) As
Object
SetActiveCellByName()
Function SetActiveCellByName(ByRef pCellName As String, ByRef
pSheetName As String, Optional ByRef pDoc As Object) As
Object
121
LibO Primitives
SetActiveSheetByName()
Function SetActiveSheetByName(ByRef pSheetName As String,
Optional pDoc As Object) As Object
SetNamedCellValue()
Sub SetNamedCellValue(ByRef pName As String, pValue As
Variant, Optional ByRef pDoc As Variant)
ShiftRange()
Function ShiftRange(ByRef pOldRange As Object, pNewTLCell As
Object) As Object
122
CalcPrim.RangeCell
UpdateRangeColumnValues()
Function UpdateRangeColumnValues(ByRef pSearch As Variant,
pRange As Object, pLookupIndex As Integer, pUpdateIndex As
Integer, pValue As Variant) As Long
Updates all cell values in a range column that meet a search criterion.
Input
pSearch: the searched value.
pRange: the range in which to search.
pLookupIndex: the lookup column (1-based) within the search range.
This index must be within pRange bounds (1 to columns count).
pUpdateIndex: the update column (1-based) within the range.
This index must be within pRange bounds (1 to columns count).
pValue: the value to insert into the matching cells.
Output
The result code.
Possible return values:
ERR_RANGE_OK (0): process completed without error.
ERR_RANGE_OUTOFBOUNDS: the lookup index is out of range.
ERR_RANGE_ENUMERATOR: the range enumerator couldn’t be created.
(other): the Basic error code.
Note: Depending on the range height, the update process may be
lengthy. It is recommended that Calc controllers be locked in the
interval.
Usage
Result = UpdateRangeColumnValues(25, MyRange, 1, 27, 5)
replaces column 27 items with value 5 into MyRange range where
column 1 items equal 25.
See also: UpdateRangeMultiColumnValuesArray().
123
LibO Primitives
UpdateRangeMultiColumnValues()
Function UpdateRangeMultiColumnValues(ByRef pSearch As
Variant, pRange As Object, pLookupIndex As Integer,
pUpdateValues As Variant) As Long
Input
pSearch: the searched value in the range.
pRange: the selected range that contains data to search.
pLookupIndex: the lookup column (1-based) within the range.This
index must be within pRange bounds (1 to columns count).
pUpdateValues: the update columns array (indices are 1-based) within
the range. This is a nested array with (col_index, value, mode) array
items (see Usage below).
The column indices must all be within pRange bounds (1 to columns
count).
Mode: The Calc update mode. This value is one of the
com.sun.star.sheet.CellFlags.XXX constants.
The currently supported constants are: FORMULA, VALUE, DATETIME,
STRING.
Output
The process result code. Possible return values:
ERR_RANGE_OK (0): process completed without error.
ERR_RANGE_OUTOFBOUNDS: the lookup or update index is out of range.
ERR_RANGE_ENUMERATOR: the enumerator couldn’t be created.
ERR_RANGE_BADSRCARRAY: the update array is not usable.
(other): the Basic error code
Note: depending on the range height, the update process may be
lengthy. It is recommended that Calc controllers be locked in the
interval.
Usage
Mode1 = com.sun.star.sheet.CellFlags.VALUE
Mode2 = com.sun.star.sheet.CellFlags.FORMULA
Formula = "=SUM(A1:A5)"
Result = UpdateRangeMultiColumnValues(10, MyRange, 1,
Array(Array(27, 1, Mode1), Array(28, Formula, Mode2)))
replaces column 27 items with value 1 and column 28 items with a
formula into MyRange range where column 1 items equal 10.
124
CalcPrim.RangeCell
UpdateRangeMultiColumnValuesArray()
Function UpdateRangeMultiColumnValuesArray(ByRef pSearch As
Variant, pRange As Object, pLookupIndex As Integer,
pUpdateValues As Variant) As Long
Input
pSearch: the searched value in the range.
pRange: the selected range that contains data to search.
pLookupIndex: the lookup column (1-based) within the range.
This index must be within pRange bounds (1 to columns count).
pUpdateValues: the update columns array (indices are 1-based) within
the range.
This is a nested array with ( ColumnIndex, Value) array items.
The column indices must all be within pRange bounds (1 to columns
count).
Note: This function does its best to convert the provided values into
admissible Calc values types (numbers and strings only).
Output
The result code. Possible return values:
ERR_RANGE_OK (0): process completed without error.
ERR_RANGE_OUTOFBOUNDS: the lookup or update index is out of range.
ERR_RANGE_BADSRCARRAY: the update array is not usable.
(other): the Basic error code
Note: depending on the range height, while this function is fast, the
update process may be lengthy. It is recommended that Calc
controllers be locked in the interval.
Usage
Result = UpdateRangeMultiColumnValuesArray(SomeValue, MyRange,
1, Array(Array(27, True), Array(28, SomeDate)))
This replaces column 27 items with value True and column 28 items
with value SomeDate into the MyRange range where column 1 items
equal SomeValue.
UsedRange()
Function UsedRange(ByRef pSheet As Object, Optional ByRef
pOrigin As String) As Object
125
LibO Primitives
VLookupCell()
Function VLookupCell(ByRef pSearch As Variant, pRange As
Object, pLookupIndex As Integer, pMatchType As Integer) As
Object
This function is much alike the VLOOKUP() Calc function, but it returns a
cell object instead of a value.
Input
pSearch: the searched value
pRange: the range that contains data to search. The searched column
must be the first one.
pLookupIndex: the lookup column (1-based) within the search range
pMatchType: -1, 0 or 1 (see the MATCH() function help).
Output
The matching cell object or Null if none found.
126
CalcPrim.Document
CalcPrim.Document
Global Constants
Constant name Value Description
Errors
Primitives
SecureCalcUI()
Sub SecureCalcUI(ByRef pSecure As Boolean, Optional ByRef pDoc As
Object)
127
LibO Primitives
CalcPrim.CalcExportClass
Dependencies: CalcPrim.CalcExportPropertyClass
This class module defines a spreadsheet export management class. It uses CalcPrim.CalcExport-
PropertyClass as a sheet property source.
This class eases data backup or export from a given Calc document to another.
Note that this class is currently under heavy refactoring.
Constants
All constants have a CALCEXPORT prefix. Moreover, error constants are ERR_ prefixed.
Constant name Value Description
Error Constants
ERR_CALCEXPORTCLASS_NORUN -1 The process did not run.
ERR_CALCEXPORTCLASS_NONE 0 No error (OK).
ERR_CALCEXPORTCLASS_CANTCREATEFILE 1 The output file can’t be created.
Properties
Public Properties
LastError Long [RO] Stores the last error code while running the object.
See the error constants above.
Progress Object [R/W] Connection with a progress bar for UI user feedback.
Use a ProgressWidgetClass object for that.
If it is present, this widget is updated when processing each sheet.
See the FormPrim.ProgressWidgetClass module.
128
CalcPrim.CalcExportClass
SourceDocument Object [R/W] The document from which to export (must be a spreadsheet).
Version String [R/W] Specify a version property for the target export .ods file.
Methods
Public Methods
AddAllSheets()
Public Sub AddAllSheets()
AddSheet()
Public Sub AddSheet(ByRef pSheetRef As Variant)
AddSheetInfo()
Public Sub AddSheetInfo(ByRef pSheetInfo As Object)
ClearError()
Public Sub ClearError()
ClearSelection()
Public Sub ClearSelection()
Execute()
Public Sub Execute()
129
LibO Primitives
GetSheetInformation()
Public Function GetSheetInformation(ByRef pSheetName As String) As
Object
Reset()
Public Sub Reset()
Private Methods
_AddCollectionItem()
Private Sub _AddCollectionItem(ByRef pColl As Object, ByRef pItem As
Variant, pKey As String)
_AddSheet()
Private Sub _AddSheet(ByRef pDoc As Object, pSheetName As String)
_ArrayExists()
Private Function _ArrayExists(ByRef pArray As Variant) As Boolean
_CheckExport()
Private Function _CheckExport() As Long
130
CalcPrim.CalcExportClass
_CheckSheetName()
Private Function _CheckSheetName(ByRef pSheetName As String,
pSheetNames As Variant) As String
(recursive)
Checks whether a sheet name already exists in a names list and returns the
name set so that there’s no duplicate.
Input
pSheetName: the tested sheet name.
pNames: a vector (1-D array) of existing names against which to check.
The vector must exist.
Output
The sheet name, defined so that there’s no name collision. If the sheet name
exists, it is appended a number ( 1..n) until there’s no more collision.
_CleanUpTargetDocument()
Private Sub _CleanUpTargetDocument(ByRef pDoc As Object)
_CopyData()
Private Sub _CopyData(ByRef pSheetInfo As Object, ByRef pTgtDoc As
Object)
Actually copy data from the source document sheets to the target document.
Input
pSheetInfo: the sheet selection information
pTgtDoc: the target document (same sheet name)
_CreateCalcDocument()
Private Function _CreateCalcDocument() As Object
_CreateCustomProperties()
Private Function _CreateCustomProperties(ByRef pTgtDoc As Object,
pVersion As String, pDateTime As Date, pSource As String) As Long
_EmptyColumns()
Private Sub _EmptyColumns(ByRef pSheet As Object, pArray As Variant)
131
LibO Primitives
_EmptyRows()
Private Sub _EmptyRows(ByRef pSheet As Object, pArray As Variant)
_GetRange()
Function _GetRange(Optional ByRef pSheetRef As Variant, Optional
pRangeRef As Variant, Optional pDoc As Object) As Object
_GetSheet()
Function _GetSheet(Optional ByRef pSheetRef As Variant, Optional
pDoc As Object) As Object
132
CalcPrim.CalcExportClass
_GetUsedRange()
Private Function _GetUsedRange(ByRef pDoc As Object, pSheetRef As
Variant) As Object
_InsertMetadata()
Private Function _InsertMetadata(ByRef pDoc As Object) As long
Inserts the export metadata into the target document and returns a result status.
The metadata are the version, date/time, source file name and application name
of the export process.
Input
pDoc: the document in which to insert the metadata.
Output
A result status.
_ProcessSheets()
Private Sub _ProcessSheets(ByRef pTgtDoc As Object)
_RemoveColumns()
Private Sub _RemoveColumns(ByRef pSheet As Object, pArray As
Variant)
_RemoveRows()
Private Sub _RemoveRows(ByRef pSheet As Object, pArray As Variant)
_ReplaceStr()
Private Function _ReplaceStr(ByRef pSourceStr As String, pSearchStr
As String, pReplStr As String) As String
_SaveTargetDocument()
Private Function _SaveTargetDocument(ByRef pDoc As Object) As Long
Saves the in-memory document to the target file name and returns the result
status.
133
LibO Primitives
134
CalcPrim.CalcExportPropertyClass
CalcPrim.CalcExportPropertyClass
Dependencies: (none)
This module defines an export property to use with the previous CalcPrim.CalcExportClass.
Properties
Public Properties
EmptyColumns Variant [R/W] This property defines the list of columns that will be present but
empty in the target document. The list is 0-based.
[W] Set the empty columns list from a 1-D array (vector).
For practical reasons, the vector may hold discrete values or
ranges:
EmptyColumns(Array(1, 2-5, 15))
[R] Get the EmptyColumns array.
EmptyRows Variant [R/W] This property defines the list of rows that will be present but
empty in the target document. The list is 0-based.
[W] Set the empty rows list from a 1-D array (vector).
For practical reasons, the vector may hold discrete values or
ranges:
EmptyRows(Array(1-3))
[R] Get the EmptyRows array.
RemoveColumns Variant [R/W] This property defines the list of columns that will be removed from
the target document. The list is 0-based.
[W] Set the removed columns list from a 1-D array (vector).
For practical reasons, the vector may hold discrete values or
ranges:
RemoveColumns(Array(0))
[R] Get the RemoveColumns array.
RemoveRows Variant [R/W] This property defines the list of rows that will be removed from the
target document. The list is 0-based.
[W] Set the removed rows list from a 1-D array (vector).
For practical reasons, the vector may hold discrete values or
ranges:
RemoveRows(Array(1, 2))
[R] Get the RemoveRows array.
SourceRangeAddress Object [R/W] This property defines a range to export within the source sheet.
[W] Set the range address using a RangeAddress object.
Note that the RangeAddress.Sheet property is not used, so its
value in of no importance.
[R] Get the source range address as a RangeAddress object.
SourceSheetName String [R/W] This property defines the name of the source sheet. This
information is unique and identifies the properties, which means
that the same sheet cannot be exported twice (the newest added
properties for a given sheet would replace the previous ones)..
[W] Set the source sheet name. If the target name is not set, then
the same name is assumed.
[R] Get the SourceSheetName string.
135
LibO Primitives
TargetSheetName String [R/W] This property defines the name of the source sheet which can
differ from the source sheet name.
[W] Set the target sheet name.
[R] Get the TargetSheetName string.
Methods
Public Methods
AddEmptyColumn()
Public Sub AddEmptyColumn(ByRef pItem As Variant)
AddEmptyRow()
Public Sub AddEmptyRow(ByRef pItem As Variant)
AddRemoveColumn()
Public Sub AddRemoveColumn(ByRef pItem As Variant)
AddRemoveRow()
Public Sub AddRemoveRow(ByRef pItem As Variant)
ClearEmptyColumns()
Public Sub ClearEmptyColumns()
ClearEmptyRows()
Public Sub ClearEmptyRows()
ClearIgnoredColumns()
Public Sub ClearIgnoredColumns()
ClearIgnoredRows()
Public Sub ClearIgnoredRows()
ClearRangeAddress()
Public Sub ClearRangeAddress()
Private Methods
_AddToVector()
Private Sub _AddToVector(ByRef pArray As Variant, pItem as Variant)
136
CalcPrim.CalcExportPropertyClass
_ArrayExists()
Private Function _ArrayExists(ByRef pArray As Variant) As Boolean
_SortVector()
Private Function _SortVector(ByRef pArray As Variant, Optional ByRef
pAsc As Boolean)
_SwapValues()
Private Sub _SwapValues(ByRef pVal1 As Variant, pVal2 As Variant)
137
LibO Primitives
CalcPrim.CalcImportClass
Dependencies: CalcPrim.CalcImportPropertyClass
This class module defines a spreadsheet import management class. It uses CalcPrim.CalcImport-
PropertyClass as a sheet property source.
This class eases data restoration or import from a given Calc document to another.
This class is currently under heavy refactoring!
Constants
All constants have a CALCIMPORT prefix. Moreover, error constants are ERR_ prefixed.
Constant name Value Description
Error Constants
ERR_CALCIMPORTCLASS_NORUN -1 The process did not run.
ERR_CALCIMPORTCLASS_NONE 0 No error (OK).
ERR_CALCIMPORTCLASS_CANTCREATEFILE 1 The output file can’t be created.
Properties
Public Properties
Progress Object [R/W] A progress bar information object for display purposes.
138
CalcPrim.CalcImportClass
SourceDocumentName String [R/W] the source document name (FQN), in URL or OS form.
TargetDocument Object [R/W] The target calc document object to which to import.
Methods
Public Methods
Private Methods
139
LibO Primitives
CalcPrim.CalcImportPropertyClass
Dependencies: (none)
This module defines an import property to use with the previous CalcPrim.CalcImportClass.
Properties
Public Properties
Methods
Public Methods
Private Methods
140
WriterPrim
LibreOffice Writer module primitives.
WriterPrim.Styles.............................................................142 ERR_AUTOTEXT_NAME.........................................147
STY_WFAMPAGES.....................................................142 ERR_AUTOTEXT_SHORTCUT..............................147
STY_WFAMPARAS....................................................142 ERR_AUTOTEXTGROUP_UNKNOWN...............147
STY_WFAMCHARS...................................................142 ERR_AUTOTEXTGROUP_CANTCREATE..........147
STY_WFAMFRAMES.................................................142 ERR_AUTOTEXTGROUP_CANTDELETE..........147
STY_WFAMNUMBER................................................142 ERR_AUTOTEXTGROUP_EXISTS........................148
STY_WFAMTABLES..................................................142 AddAutoTextGroup().................................................148
GetStyleAtCursor().....................................................142 AutoTextGroupExists()..............................................148
WriterPrim.Fields..............................................................143 AutoTextGroupID()....................................................148
MFLD_USERSERVICE...............................................143 AutoTextGroupNameIndex()...................................148
MFLD_USERINSTANCE...........................................143 DeleteAutoTextGroupByName().............................149
MFLD_TYPE_UNK.....................................................143 GetAutoTextGroupByIndex()...................................149
MFLD_TYPE_USER....................................................143 GetAutoTextGroupByName()..................................149
MFLD_TYPE_EXPR...................................................143 GetAutoTextGroupNames().....................................149
MFLD_TYPEUSERID.................................................143 NewAutoTextGroup().................................................149
MFLD_TYPEEXPRID.................................................143 AddAutoText().............................................................150
CreateMasterField()....................................................143 AddAutoTexts()...........................................................150
DeleteMasterField()....................................................144 AddRawAutoTexts()...................................................150
ExportMasterFields()..................................................144 AutoTextExists()..........................................................151
GetMasterFieldNameOnly().....................................144 AutoTextShortcutIndex()...........................................151
GetMasterFieldType()................................................144 CreateAutoTextContainer()......................................151
GetMasterFieldValue()...............................................144 DeleteAutoTextByShortcut()....................................151
IsMasterFieldUser()....................................................145 GetAutoTextByShortcut().........................................151
SetMasterFieldValue()................................................145 GetAutoTextShortcuts()............................................152
WriterPrim.Tables.............................................................146 GetAutoTextTitles()....................................................152
GetColumnWidths()...................................................146 NewAutoText().............................................................152
GetTableActualWidth().............................................146 RenameAutoText()......................................................152
GetTableColCountByName()...................................146 UpdateAutoText()........................................................153
GetTableRowCountByName().................................146 UpdateAutoTextTitle()...............................................153
WriterPrim.Autotexts......................................................147 _CreateHiddenDocument()......................................153
SVC_AUTOCONTAINER.........................................147 WriterPrim.Text.................................................................154
SVC_TEXTRANGE.....................................................147 GetSelection()..............................................................154
ERR_AUTOTEXT_NONE.........................................147 HasSelection()..............................................................154
ERR_AUTOTEXT_UNKNOWN..............................147 WriterPrim.Bookmarks...................................................155
ERR_AUTOTEXT_CANTCREATE.........................147 CreateBookmark()......................................................155
ERR_AUTOTEXT_CANTDELETE.........................147 GotoBookmark().........................................................155
ERR_AUTOTEXT_CANTUPDATE........................147 GotoBookmarkFromCursor()...................................156
ERR_AUTOTEXT_EXISTS.......................................147 RemoveBookmark()...................................................156
141
LibO Primitives
WriterPrim.Styles
Dependencies: (none)
Global Constants
Constant name Value Description
Style families
Primitives
GetStyleAtCursor()
Function GetStyleAtCursor(ByRef pTextCursor As Object, pStyleFamily As
String) As Object
142
WriterPrim.Fields
WriterPrim.Fields
Masterfields (aka user fields) management.
Dependencies: (none)
Masterfields are stored in a container object (Document.TextfieldMasters). Their names can be
read from its ElementNames() array, where each name is stored with the following syntax:
User-defined masterfields: "com.sun.star.text.fieldmaster.User.SomeMasterFieldName"
Sequences: "com.sun.star.text.fieldmaster.SetExpression.SomeSequenceName"
Global Constants
Constant name Value Description
Services
MFLD_USERSERVICE "com.sun.star.text.fieldmaster.User." Root name for a masterfield, incl.
the final dot.
MFLD_USERINSTANCE "com.sun.star.text.fieldmaster.User" Root name for a masterfield, not
incl. the final dot.
Master field types
MFLD_TYPE_UNK 0 Unknown type
MFLD_TYPE_USER 1 User-created field
MFLD_TYPE_EXPR 2 LibO sequence field (Illustration,
Table, Text or Drawing)
Master field identifiers
MFLD_TYPEUSERID ".User." User field.
MFLD_TYPEEXPRID ".SetExpression." Sequence field.
Primitives
CreateMasterField()
Function CreateMasterField(ByRef pFieldName As String, Optional pValue
As Variant, Optional pDoc As Object) As Boolean
143
LibO Primitives
DeleteMasterField()
Function DeleteMasterField(ByRef pFieldName As String, Optional pDoc As
Object) As Boolean
ExportMasterFields()
Function ExportMasterFields(ByRef pDocTgt As Object, Optional pReset As
Boolean, Optional pDocSrc As Object) As Boolean
GetMasterFieldNameOnly()
Function GetMasterFieldNameOnly(ByRef pFieldName As String) As String
GetMasterFieldType()
Function GetMasterFieldType(ByRef pFieldName As String) As Long
GetMasterFieldValue()
Function GetMasterFieldValue(ByRef pFieldName As String, Optional pDoc
As Object) As Variant
144
WriterPrim.Fields
IsMasterFieldUser()
Function IsMasterFieldUser(ByRef pFieldName As String) As Boolean
SetMasterFieldValue()
Sub SetMasterFieldValue(ByRef pFieldName As String, pValue As Variant,
Optional pDoc As Object)
145
LibO Primitives
WriterPrim.Tables
Dependencies: (none)
GetColumnWidths()
Function GetColumnWidths(ByRef pTableName As String, pRowNum As Long,
Optional pDoc As Object) As Variant
GetTableActualWidth()
Function GetTableActualWidth(ByRef pTable As Object) As Long
GetTableColCountByName()
Function GetTableColCountByName(ByRef pTableName As String, pRowNum As
Long, Optional pDoc As Object) As Long
GetTableRowCountByName()
Function GetTableRowCountByName(ByRef pTableName As String, Optional
pDoc As Object) As Long
146
WriterPrim.Autotexts
WriterPrim.Autotexts
Dependencies: (none)
Deals with autotexts: retrieving, creating, deleting.
Vocabulary
An Autotext (or glossary entry) is made of three items:
its shortcut
This is the string that is entered by the user in the document before hitting F3 .
its name/description/title
This is the contents of the Name textbox within the UI
its contents
This is the actual text that is inserted in the document after hitting F3
The contents may be either raw text or formatted text.
Note that, because of a long-standing bug with LibreOffice, inserting a raw text adds an (empty)
paragraph just after.
Warning
A few of the following functions attempt to create new autotexts or groups. When the target group
is the LibO Basis container (global level), some systems might refuse write access under non-
administrative accounts, thus cause a runtime error. To deal with this, the error is intercepted by an
On Local Error statement, hence in this situation the returned object would be Null.
Applies to AddAutoTextGroup(), NewAutoTextGroup(), AddAutoText(), NewAutoText(),
UpdateAutoText(), UpdateAutoTextTitle().
Global Constants
Constant name Value Description
Services
SVC_AUTOCONTAINER "com.sun.star.text.AutoTextContainer"
SVC_TEXTRANGE "com.sun.star.text.TextRange"
Errors
ERR_AUTOTEXT_NONE 0 Everything went ok.
ERR_AUTOTEXT_UNKNOWN 1 The shortcut wasn’t found.
ERR_AUTOTEXT_CANTCREATE 2 Autotext entry creation problem.
ERR_AUTOTEXT_CANTDELETE 3 Autotext entry deletion problem.
ERR_AUTOTEXT_CANTUPDATE 4 Autotext entry update problem.
ERR_AUTOTEXT_EXISTS 5 Autotext entry shortcut already
exists.
ERR_AUTOTEXT_NAME 6 Non valid autotext entry name.
ERR_AUTOTEXT_SHORTCUT 7 Non valid autotext entry shortcut.
ERR_AUTOTEXTGROUP_UNKNOWN 11 Group not found.
ERR_AUTOTEXTGROUP_CANTCREATE 12 Group creation problem.
ERR_AUTOTEXTGROUP_CANTDELETE 13 Group deletion problem.
147
LibO Primitives
Primitives
Autotext Groups
AddAutoTextGroup()
Function AddAutoTextGroup(ByRef pGroupName As String, Optional ByRef
pLocal As Boolean, Optional ByRef pReplace As Boolean) As Long
AutoTextGroupExists()
Function AutoTextGroupExists(ByRef pGroupName As String) As Boolean
AutoTextGroupID()
Function AutoTextGroupID(ByRef pGroupName As String, ByRef pLocal As
Boolean) As String
AutoTextGroupNameIndex()
Function AutoTextGroupNameIndex(ByRef pGroupName As String) As Long
Returns the index of an autotext group within the container from its name.
Input
pGroupName: the name of the group to check.
Output
The index of the autotext group, or -1 if not found.
148
WriterPrim.Autotexts
DeleteAutoTextGroupByName()
Function DeleteAutoTextGroupByName(ByRef pGroupName As String) As
Long
GetAutoTextGroupByIndex()
Function GetAutoTextGroupByIndex(ByRef pIndex As Long) As Object
GetAutoTextGroupByName()
Function GetAutoTextGroupByName(ByRef pGroupName As String) As
Object
GetAutoTextGroupNames()
Function GetAutoTextGroupNames() As Variant
NewAutoTextGroup()
Function NewAutoTextGroup(ByRef pGroupName As String, ByRef pLocal
As Boolean, Optional ByRef pReplace As Boolean) As Object
Autotexts
149
LibO Primitives
AddAutoText()
Function AddAutoText(ByRef pGroupName As String, pTitle As String,
pShortcut As String, pText As Object, Optional pUpdate As Boolean)
As Long
AddAutoTexts()
Function AddAutoTexts(ByRef pGroupName As String, ByRef
pAutoTextArray() As Variant) As Long
AddRawAutoTexts()
Function AddRawAutoTexts(ByRef pGroupName As String, ByRef
pAutoTextArray() As Variant) As Long
150
WriterPrim.Autotexts
AutoTextExists()
Function AutoTextExists(ByRef pGroupName As String, pShortcut As
String) As Boolean
AutoTextShortcutIndex()
Function AutoTextShortcutIndex(ByRef pGroup As Object, pShortcut As
String) As Long
Returns the index of an autotext within the group from its name.
Input
pGroup: the group owner object
pShortcut: the name of the shortcut to check.
Output
The index of the autotext, or -1 if not found.
CreateAutoTextContainer()
Function CreateAutoTextContainer() As Object
DeleteAutoTextByShortcut()
Function DeleteAutoTextByShortcut(ByRef pGroupName As String,
pShortcut As String) As Long
GetAutoTextByShortcut()
Function GetAutoTextByShortcut(ByRef pGroupName As String, pShortcut
As String) As Object
151
LibO Primitives
GetAutoTextShortcuts()
Function GetAutoTextShortcuts(ByRef pGroupName As String) As Variant
GetAutoTextTitles()
Function GetAutoTextTitles(ByRef pGroupName As String) As Variant
NewAutoText()
Function NewAutoText(ByRef pGroup As Object, pTitle As String,
pShortcut As String, pText As Object, Optional pUpdate As Boolean)
As Object
RenameAutoText()
Function RenameAutoText(ByRef pGroupName As String, ByRef
pOldShortcut As String, ByRef pNewShortcut As String) As Long
Renames an entry shortcut. The other items of the entry are left untouched.
Input
pGroupName: the owning autotext group name for the autotext.
pOldShortcut: the current autotext shortcut.
pNewShortcut: the new autotext shortcut.
Output
The error status. Returns ERR_AUTOTEXT_NONE (0) if OK, otherwise see
ERR_AUTOTEXT_XXX constants.
ERR_AUTOTEXT_SHORTCUT: a shortcut is not valid.
ERR_AUTOTEXT_UNKNOWN: the shortcut doesn’t exist for this group.
ERR_AUTOTEXTGROUP_UNKNOWN: the group is unknown.
ERR_AUTOTEXT_EXISTS: the shortcut already exists in this group.
ERR_AUTOTEXT_CANTCREATE: creation problem. The AutoText wasn’t created.
152
WriterPrim.Autotexts
UpdateAutoText()
Function UpdateAutoText(ByRef pGroupName As String, pTitle As
String, pShortcut As String, pNewText As Object) As Long
UpdateAutoTextTitle()
Function UpdateAutoTextTitle(ByRef pGroupName As String, pNewTitle
As String, pShortcut As String) As Long
Internal
_CreateHiddenDocument()
Function _CreateHiddenDocument() As Object
153
LibO Primitives
WriterPrim.Text
Dependencies: (none)
Text-related primitives.
Global Constants
Constant name Value Description
Primitives
GetSelection()
Function GetSelection(Optional pNearestWord As Boolean, Optional ByRef
pDoc As Object) As Object
HasSelection()
Function HasSelection(Optional ByRef pDoc As Object) As Boolean
154
WriterPrim.Bookmarks
WriterPrim.Bookmarks
Dependencies: (none)
Bookmark-related primitives.
Note: a bookmark can be a single point or encompass a number of characters.
Global Constants
Constant name Value Description
Primitives
CreateBookmark()
Function CreateBookmark(ByRef pBookmarkName As String, ByRef pCursor As
Object, Optional ByRef pDoc As Object) As Object
GotoBookmark()
Function GotoBookmark(ByRef pBookmarkName As String, Optional pSelect
As Boolean, Optional ByRef pVisible As Boolean, Optional ByRef pDoc As
Object) As Object
155
LibO Primitives
GotoBookmarkFromCursor()
Function GotoBookmarkFromCursor(ByRef pBookmarkName As String, ByRef
pCursor As Object, Optional pSelect As Boolean, Optional ByRef pDoc As
Object) As Object
RemoveBookmark()
Function RemoveBookmark(ByRef pBookmarkName As String, Optional ByRef
pDoc As Object) As Boolean
156
DataStructPrim
DataStructPrim.Collections............................................158 ERR_COLL_KEYEXISTS...........................................158
ERR_COLL_OK...........................................................158 ERR_COLL_OBJECT..................................................158
ERR_COLL_NOTSET.................................................158
157
LibO Primitives
DataStructPrim.Collections
(to be finished)
Global Constants
Constant name Value Description
Errors
ERR_COLL_OK 0
ERR_COLL_NOTSET 1
ERR_COLL_KEYEXISTS 2
ERR_COLL_OBJECT 3
Primitives
AddCollectionItem()
Function AddCollectionItem(ByRef pColl As Object, ByRef pItem As
Variant, pKey As String, Optional ByRef pForce As Boolean) As Long
158
DialogPrim
DialogPrim.Dialogs..........................................................160 CreateDialog().............................................................160
BrowseForDir()............................................................160 YesNoDialog()..............................................................160
159
LibO Primitives
DialogPrim.Dialogs
Dependencies: (none)
Primitives
BrowseForDir()
Function BrowseForDir(ByRef pDefDir As String, pTitle As String,
pDescription As String) As String
CreateDialog()
Function CreateDialog(ByRef pLibName As String, pModuleName As String,
Optional ByRef pLibCtnr As Object) As Object
YesNoDialog()
Function YesNoDialog(ByRef pTitle As String, pMsg As String) As Boolean
160
FormPrim
LibreOffice forms primitives.
FormPrim.Widgets............................................................162 CurrentStepNum.........................................................164
ERR_FORMPRIM_NODOC......................................162 FirstStep........................................................................164
ERR_FORMPRIM_NOFORM...................................162 LastStep.........................................................................164
ERR_FORMPRIM_NOCONTROL...........................162 Mute...............................................................................164
ERR_FORMPRIM_NOWIDGET..............................162 ProgressBar..................................................................164
WIDG_ID_CBX...........................................................162 ProgressLabel...............................................................164
CheckBoxCount().......................................................162 AddStep()......................................................................164
GetFormControl().......................................................162 AddSteps()....................................................................164
FormPrim.ProgressWidgetClass....................................163 NextStep().....................................................................165
rMessage.......................................................................163 ProgressEnd()...............................................................165
rDelay............................................................................163 ProgressStart().............................................................165
CreateProgressStepInformation()...........................163 SetFirstStep()................................................................165
CurrentStep..................................................................164 SetLastStep().................................................................165
161
LibO Primitives
FormPrim.Widgets
Dependencies: (none)
Global Constants
Constant name Value Description
Errors
ERR_FORMPRIM_NODOC -1 The specified document doesn’t exist.
ERR_FORMPRIM_NOFORM -2 The specified form doesn’t exist.
ERR_FORMPRIM_NOCONTROL -3 No controls on the form.
ERR_FORMPRIM_NOWIDGET -4 No such widget on the form.
Misc.
WIDG_ID_CBX 5 Checkbox identifier
Primitives
CheckBoxCount()
Function CheckBoxCount(ByRef pFormName As String, Optional ByRef pDoc
As Object, Optional pChecked As Boolean, Optional pNonPrintable As
Boolean) As Long
GetFormControl()
Function GetFormControl(ByRef pFormName As String, ByRef pCtrlName As
String, Optional ByRef pDoc As Object) As Object
162
FormPrim.ProgressWidgetClass
FormPrim.ProgressWidgetClass
Dependencies: (none)
A progress bar management class for user feedback during lengthy processes in forms.
This class is very similar to the LibOPrim.ProgressClass(see page 98). While that one is an all pur-
pose progress bar class, the ProgressWidgetClass is dedicated to displaying and managing
progress actions within forms.
This class encapsulates the LibreOffice form progressbar widget functionalities. It aims at provid-
ing an entry point where to manage progress bars steps, messages and display delays.
This class defines the properties of a progress bar:
a progress bar object.
messages and delays for the different process steps.
messages and delays for startup and termination steps.
TProgressStepInformation
This structure stores a message and a display delay for a given progress step.
Member name Type Description
rMessage String The message to display for a given step.
rDelay Long The message display delay, in ms..
Primitives
This module offers a factory function that can create an object of TProgressStepInformation.
Call it from your code to initialize such objects.
CreateProgressStepInformation()
Function CreateProgressStepInformation(Optional ByRef pMsg As
String, Optional ByRef pDelay As Long) As
TProgressStepInformation
163
LibO Primitives
Properties
Property Type Description
CurrentStep Object [RO] The progress current step information.
Returns an object of TProgressStepInformation type.
CurrentStepNum Long [RO] The progress current step number.
The steps are numbered from 0 (first), then 1 (first added step) to N
(nth added step) then -1 (last).
FirstStep Object [RO] The progress first step information
Returns an object of TProgressStepInformation type.
Use SetFirstStep() method to set this object.
LastStep Object [RO] The progress last step information
Returns an object of TProgressStepInformation type.
Use SetLastStep() method to set this object.
Mute Boolean [R/W] (un)sets the display of messages.
Defaults to False.
ProgressBar Object [R/W] The progress bar to update.
Set it from a form ProgressBar widget.
ProgressLabel Object [R/W] A label object for user feedback.
If not set, messages are not displayed.
Methods
Public
AddStep()
Public Sub AddStep(ByRef pMsg As String, Optional pDelay As Long)
AddSteps()
Public Sub AddSteps(ByRef pArrSteps As Variant)
164
FormPrim.ProgressWidgetClass
NextStep()
Public Sub NextStep(Optional ByRef pInc As Long, Optional ByRef pMsg As
String)
ProgressEnd()
Public Sub ProgressEnd(Optional ByRef pMsg As String)
ProgressStart()
Public Sub ProgressStart(Optional ByRef pMsg As String)
SetFirstStep()
Public Sub SetFirstStep(ByRef pMsg As String, Optional pDelay As Long)
SetLastStep()
Public Sub SetLastStep(ByRef pMsg As String, Optional pDelay As Long)
_AddCollectionItem()
Private Sub _AddCollectionItem(ByRef pColl As Object, ByRef pItem As
Variant, pKey As String)
165
LibO Primitives
_ArrayExists()
Private Function _ArrayExists(ByRef pArray As Variant) As Boolean
166
EmailPrim
EmailPrim.SendMailClass...............................................168 AddAttachement()......................................................169
ERR_EMAILCLASS_NORUN...................................168 AddBCC()......................................................................169
ERR_EMAILCLASS_NONE......................................168 AddBCCbyCSV().........................................................169
ERR_EMAILCLASS_NORECIPIENT.....................168 AddCC().........................................................................170
ERR_EMAILCLASS_AUTHENTICATION...........168 AddCCbyCSV()............................................................170
ERR_EMAILCLASS_RECIPIENTEXISTS..............168 AddTo()..........................................................................170
ERR_EMAILCLASS_NOSUCHRECIPIENT..........168 AddToByCSV()............................................................170
ERR_EMAILCLASS_NOSUCHCC..........................168 ClearAttachments()....................................................170
ERR_EMAILCLASS_NOSUCHBCC.......................168 ClearBCCs()..................................................................170
ERR_EMAILCLASS_ATTACHMENTEXISTS......168 ClearCCs()....................................................................171
ERR_EMAILCLASS_CANTATTACH.....................168 ClearError()..................................................................171
SMTP_SERVINSECURE............................................168 ClearTos()......................................................................171
SMTP_SERVSSL..........................................................168 GetAttachment().........................................................171
SMTP_SERVTLS.........................................................168 RemoveBCC()..............................................................171
EmailBodyText............................................................168 RemoveCC().................................................................171
EmailReplyTo...............................................................168 RemoveTo.....................................................................171
EmailSubject................................................................168 SendMail().....................................................................171
ErrorCode.....................................................................168 TestConnection().........................................................172
ErrorMessage...............................................................168 EmailPrim.SendMailClassListeners..............................173
Log..................................................................................168 CreateBodyListener().................................................173
ServerName..................................................................169 ResetAttachmentCounters().....................................173
ServerPort.....................................................................169 CreateAttachmentListener(......................................173
ServerSecurity.............................................................169 GetMimeTypeFromUrl()...........................................173
SMTPPassword............................................................169 GetFileContents()........................................................173
UserName.....................................................................169 CreateServerContextListener()...............................173
UserAddress.................................................................169 CreateAuthenticationListener()..............................173
167
LibO Primitives
EmailPrim.SendMailClass
Dependencies: (none)
This module defines a mail sending class directly from LibreOffice.
Warning: only tested using the SMTP_SERVINSECURE mode.
Constants
All constants have a EMAILCLASS_ prefix. Moreover, error constants are ERR_ prefixed.
Constant name Value Description
Error Constants
ERR_EMAILCLASS_NORUN -1
ERR_EMAILCLASS_NONE 0
ERR_EMAILCLASS_NORECIPIENT 1
ERR_EMAILCLASS_AUTHENTICATION 2
ERR_EMAILCLASS_RECIPIENTEXISTS 3
ERR_EMAILCLASS_NOSUCHRECIPIENT 4
ERR_EMAILCLASS_NOSUCHCC 5
ERR_EMAILCLASS_NOSUCHBCC 6
ERR_EMAILCLASS_ATTACHMENTEXISTS 7
ERR_EMAILCLASS_CANTATTACH 8
Server Context
SMTP_SERVINSECURE "Insecure" Insecure server flag.
SMTP_SERVSSL "SSL" SSL security server flag.
SMTP_SERVTLS "STARTTLS" STARTTLS security server flag.
Properties
EmailBodyText String [R/W] The email body.
The body is text-only (no formatting).
168
EmailPrim.SendMailClass
Methods
AddAttachement()
Function AddAttachment(ByRef pAttachmentURL As String) As Long
AddBCC()
Sub AddBCC(ByRef pBCC As String)
AddBCCbyCSV()
Sub AddBCCbyCSV(ByRef pBCCcsv As String)
169
LibO Primitives
AddCC()
Sub AddCC(ByRef pCC As String)
AddCCbyCSV()
Sub AddCCbyCSV(ByRef pCCcsv As String)
AddTo()
Sub AddTo(ByRef pTo As String)
AddToByCSV()
Sub AddToByCSV(ByRef pToCsv As String)
ClearAttachments()
Sub ClearAttachments()
ClearBCCs()
Sub ClearBCCs()
170
EmailPrim.SendMailClass
ClearCCs()
Sub ClearCCs()
ClearError()
Sub ClearError()
ClearTos()
Sub ClearTos()
GetAttachment()
Function GetAttachment(ByRef pNum As Long) As String
Returns an attachment
Input
pNum: the wanted attachment number (1-based)
Output
The attachment name or an empty string if not found.
RemoveBCC()
Function RemoveBCC(ByRef pBCC As String) As Long
RemoveCC()
Function RemoveCC(ByRef pCC As String) As Long
RemoveTo
Function RemoveTo(ByRef pRecipient As String) As Long
SendMail()
Function SendMail() As Long
171
LibO Primitives
TestConnection()
Function TestConnection() As Long
Usage
TBD
172
EmailPrim.SendMailClassListeners
EmailPrim.SendMailClassListeners
Dependencies: (none)
This is a complementary module to the SendMailClass one. Both go together and must not (can-
not) be used separately. This module implements the listeners the SendMailClass uses and needs.
Primitives
CreateBodyListener()
Function CreateBodyListener(ByRef pBodyText As String) As Object
ResetAttachmentCounters()
Sub ResetAttachmentCounters()
CreateAttachmentListener(
Function CreateAttachmentListener(ByRef pAttachments As Object)
As Object
GetMimeTypeFromUrl()
Function GetMimeTypeFromUrl(ByRef pFileName As String) As Variant
GetFileContents()
Function GetFileContents(ByRef pFileName As String) As Variant
CreateServerContextListener()
Function CreateServerContextListener(ByRef pServerName As String,
pPort As Long, pIsSecure As Boolean) As Object
CreateAuthenticationListener()
Function CreateAuthenticationListener(ByRef pUserName As String,
pPwd As String) As Object
173
Appendices
Appendices
LibreOffice Runtime Error Codes ........................................................................................................................................... 177
175
LibreOffice Runtime Error Codes
177
LibO Primitives
178
Alphabetical Index
Alphabetical Index
Global Constants
COLMAX400 (CalcPrim.Sheet) .......................................................................................................................................... 108
CPROP_TYPE_DATE (LibOPrim.CustomProperties) ..................................................................................................... 94
CPROP_TYPE_NUMBER (LibOPrim.CustomProperties) ............................................................................................... 94
CPROP_TYPE_STRING (LibOPrim.CustomProperties) ............................................................................................... 94
CPROP_TYPE_UNK (LibOPrim.CustomProperties) ....................................................................................................... 94
CPROP_TYPE_UNODATE (LibOPrim.CustomProperties) ............................................................................................. 94
CPROP_TYPE_UNODATETIME (LibOPrim.CustomProperties) .................................................................................. 94
CPROP_TYPE_UNODURATION (LibOPrim.CustomProperties) .................................................................................. 94
CPROP_TYPE_YESNO (LibOPrim.CustomProperties) .................................................................................................. 94
DOCCHKCLASS_DOCTYPE_BASEAPP (LibOPrim.DocCheckerClass) ...................................................................... 82
DOCCHKCLASS_DOCTYPE_CALC (LibOPrim.DocCheckerClass) .............................................................................. 82
DOCCHKCLASS_DOCTYPE_CHART (LibOPrim.DocCheckerClass) ........................................................................... 82
DOCCHKCLASS_DOCTYPE_DRAW (LibOPrim.DocCheckerClass) .............................................................................. 82
DOCCHKCLASS_DOCTYPE_IMPRESS (LibOPrim.DocCheckerClass) ...................................................................... 82
DOCCHKCLASS_DOCTYPE_MATH (LibOPrim.DocCheckerClass) .............................................................................. 82
DOCCHKCLASS_DOCTYPE_NONE (LibOPrim.DocCheckerClass) .............................................................................. 82
DOCCHKCLASS_DOCTYPE_WRITER (LibOPrim.DocCheckerClass) ........................................................................ 82
DOCCHKCLASS_DOCTYPE_WRITERMASTER (LibOPrim.DocCheckerClass) ......................................................... 82
DOCCHKCLASS_DOCTYPE_WRITERWEB (LibOPrim.DocCheckerClass) ................................................................. 82
DOCCHKCLASS_DOCTYPE_XFORMS (LibOPrim.DocCheckerClass) ........................................................................ 82
ERR_AUTOTEXT_CANTCREATE (WriterPrim.Autotexts) .......................................................................................... 147
ERR_AUTOTEXT_CANTDELETE (WriterPrim.Autotexts) .......................................................................................... 147
ERR_AUTOTEXT_CANTUPDATE (WriterPrim.Autotexts) .......................................................................................... 147
ERR_AUTOTEXT_EXISTS (WriterPrim.Autotexts) .................................................................................................... 147
ERR_AUTOTEXT_NAME (WriterPrim.Autotexts) .......................................................................................................... 147
ERR_AUTOTEXT_NONE (WriterPrim.Autotexts) .......................................................................................................... 147
ERR_AUTOTEXT_SHORTCUT (WriterPrim.Autotexts) ............................................................................................... 147
ERR_AUTOTEXT_UNKNOWN (WriterPrim.Autotexts) .................................................................................................. 147
ERR_AUTOTEXTGROUP_CANTCREATE (WriterPrim.Autotexts) ............................................................................. 147
ERR_AUTOTEXTGROUP_CANTDELETE (WriterPrim.Autotexts) ............................................................................. 147
ERR_AUTOTEXTGROUP_EXISTS (WriterPrim.Autotexts) ....................................................................................... 148
ERR_AUTOTEXTGROUP_UNKNOWN (WriterPrim.Autotexts) ..................................................................................... 147
ERR_CALCEXPORTCLASS_CANTCREATEFILE (CalcPrim.CalcExportClass) ..................................................... 128
ERR_CALCEXPORTCLASS_CANTOPENSOURCE (CalcPrim.CalcExportClass) ..................................................... 128
ERR_CALCEXPORTCLASS_CANTWRITEFILE (CalcPrim.CalcExportClass) ........................................................ 128
ERR_CALCEXPORTCLASS_CUSTOMPROP (CalcPrim.CalcExportClass) ............................................................... 128
ERR_CALCEXPORTCLASS_NONE (CalcPrim.CalcExportClass) ............................................................................... 128
ERR_CALCEXPORTCLASS_NORUN (CalcPrim.CalcExportClass) ............................................................................ 128
ERR_CALCEXPORTCLASS_NOTASPREADSHEET (CalcPrim.CalcExportClass) .................................................. 128
ERR_CALCEXPORTCLASS_NOTHINGTOEXPORT (CalcPrim.CalcExportClass) .................................................. 128
ERR_CALCEXPORTCLASS_SOURCENOTFOUND (CalcPrim.CalcExportClass) ..................................................... 128
ERR_CALCEXPORTCLASS_SOURCEUNDEFINED (CalcPrim.CalcExportClass) .................................................. 128
ERR_CALCEXPORTCLASS_TARGETUNDEFINED (CalcPrim.CalcExportClass) .................................................. 128
ERR_CPROP_CREATE (LibOPrim.CustomProperties) .................................................................................................. 94
ERR_CPROP_DELETE (LibOPrim.CustomProperties) .................................................................................................. 94
ERR_CPROP_EXISTS (LibOPrim.CustomProperties) .................................................................................................. 94
ERR_CPROP_NAME (LibOPrim.CustomProperties) ....................................................................................................... 94
ERR_CPROP_NORUN (LibOPrim.CustomProperties) ..................................................................................................... 94
ERR_CPROP_NOTFOUND (LibOPrim.CustomProperties) ............................................................................................. 94
ERR_CPROP_OK (LibOPrim.CustomProperties) ............................................................................................................ 94
ERR_CPROP_TYPE (LibOPrim.CustomProperties) ....................................................................................................... 94
179
LibO Primitives
180
Alphabetical Index
181
LibO Primitives
182
Alphabetical Index
183
LibO Primitives
184
Alphabetical Index
185
LibO Primitives
186
Alphabetical Index
187
LibO Primitives
188
Alphabetical Index
AddFile() ....................................................................................................................................................................... 47
AddTree() ....................................................................................................................................................................... 47
CloseZip() .................................................................................................................................................................... 47
DeleteDirectory() .................................................................................................................................................. 48
DeleteFile() ............................................................................................................................................................... 48
DirectoryContents() ............................................................................................................................................. 48
DirectoryExistsInZip() ..................................................................................................................................... 48
ErrorStatus .................................................................................................................................................................. 47
ExtractAll() ............................................................................................................................................................... 49
ExtractFile() ............................................................................................................................................................ 49
ExtractTree() ............................................................................................................................................................ 49
FileExistsInZip() .................................................................................................................................................. 49
FileStream() ............................................................................................................................................................... 50
IsInitialized ............................................................................................................................................................ 47
OpenZip() ....................................................................................................................................................................... 50
ResetErrorStatus() ............................................................................................................................................... 50
ZipContainer ............................................................................................................................................................... 47
(CalcPrim.CalcImportPropertyClass) ...................................................................................................... 46, 128, 135, 140
189