You are on page 1of 2

AMLibO no3

LibreOffice Reference Card Sheets (sheets)


LibreOffice Basic The Doc object points to the document (ex: Doc=ThisComponent).
Access to sheets
Calc Work with Sheets objects:
Active sheet MySheet = Doc.CurrentController.ActiveSheet
Beginner Sheet list AllSheets = Doc.Sheets
v. 1.11 – January 13, 2018 Number of sheets NumberSheets = Doc.Sheets.Count
Sheet object (by index [base MySheet = Doc.Sheets(index)
Written with LibreOffice v. 5.3.3 – Platform : All 0])
Sheet object (by name) MySheet = Doc.Sheets.getByName("SheetName")
LibreOffice Documents Check existence (name) Exist = Doc.Sheets.hasByName("SheetName")
Sheet index Index = MySheet.RangeAddress.Sheet
Current document
Modify sheets
Dim Doc As Object
Doc = ThisComponent Add a sheet named Name at Doc.Sheets.insertNewByName(Name, p)
Open another existing document position p(base 0)
Visible mode Delete a sheet Doc.Sheets.removeByName("SheetName")
Duplicate a sheet Doc.Sheets.copyByName("SourceName","Target-
Dim Doc As Object to the position p (base 0) Name", p)
Dim PathDoc As String
Dim Props() 'here, this table is not initialized Move sheet Doc.Sheets.moveByName(SheetName, p)
PathDoc = ConvertToURL("C:\Path\To\CalcFile.ods") to the position p (base 0)
Doc = StarDesktop.loadComponentFromURL(PathDoc, "_blank", 0, _ Manage sheets
Props())
MySheet is a sheet object.
Invisible mode Activate sheet Doc.CurrentController.ActiveSheet = MySheet
Dim Doc As Object Protect sheet MySheet.protect(password)
Dim PathDoc As String (password can be empty)
Dim Props(0) As New com.sun.star.beans.PropertyValue Unprotect sheet MySheet.unprotect(password)
PathDoc = ConvertToURL("C:\Path\To\CalcFile.ods") MySheet.tabColor = RGB(255, 255, 0)
Props(0).Name = "Hidden" 'the document will open hidden" Tab color
Props(0).Value = True Link a sheet
Doc = StarDesktop.loadComponentFromURL(PathDoc, "_blank", 0, _
Props()) Link to a file (ex: MySheet.link(URL, "", "Text - txt - csv (StarCalc)", _
CSV) Filter, com.sun.star.sheet.SheetLinkMode.VALUE)
Turn visible a posteriori Break a link MySheet.setLinkMode(com.sun.star.sheet.SheetLinkMod-
Doc.CurrentController.Frame.ContainerWindow.Visible = True e.NONE)
Doc.CurrentController.Frame.ContainerWindow.toFront()
Find last row/column used
Create a new Calc document MySheet is the sheet object to explore. Row and Col are information to fetch.
From (1) the default template or (2) a specific template. Dim Cur As Object ' cursor on the cell
Dim Doc As Object Dim Range As Object ' the used range
Dim Props() 'here, this table is not initialized Dim Row As Long
Model = "private:factory/scalc" '(1) Dim Col As Long
'or Cur = MySheet.createCursorByRange(MySheet.getCellRangeByName("A1"))
Model = "C:\Path\To\ACalcTemplateFile.ots" '(2) Cur.gotoEndOfUsedArea(True)
Doc = StarDesktop.loadComponentFromURL(Model, "_blank", 0, Props()) Range = MySheet.getCellRangeByName(Cur.AbsoluteName)
Row = Range.RangeAddress.EndRow
Save a document Col = Range.RangeAddress.EndColumn
The document already exist Cells (cells)
(equivalent to File > Save )
Below Cel is an cell object.
Use the method store from the document object. Ex : ThisComponent.store
The document was not yet saved Access to cells
(equivalent to File > Save as) MySheet is a sheet object. Access to cell object:
By cell default notation Cel = MySheet.getCellRangeByName("A4")
Dim Doc As Object 'the object document to store By name Cel = MySheet.getCellRangeByName("TVA")
Dim PathDoc As String 'the path for saving
Dim Props() 'the saving properties. (empty) By coordinates X and Y Cel = MySheet.getCellByPosition(0,3)
PathDoc = ConvertToURL("C:\Path\To\CalcFile.ods") Wih X=0 (col.A) ; Y=3 (row.4)
Doc.storeAsURL(PathDoc, Props()) Access to active cell
☞ If a copy, it turns to active document Doc is an document object and ActiveCel the active cell object.
Save a copy If Doc.currentSelection.supportsService _
Like above but with Doc.storeToURL(PathDoc, Props()) ("com.sun.star.sheet.SheetCell") Then
☞ The copy does not become the active document. 'It's a cell
ActiveCel = Doc.currentSelection
Close a document End If
Use the method close from the document object: ThisComponent.close(True) Select a cell
Document information ThisComponent.CurrentController.select(Cel)
The document object expose properties Cell coordinates
Location The folder of the document. Coordinates (Object) Coord = Cel.CellAddress
☞ Empty string is not yet saved Sheet index (Integer) NumS = Cel.CellAddress.Sheet
DocumentProperties (Object) Additional properties (below). Columns index (Long) NumC = Cel.CellAddress.Column
DocumentProperties Row index (Long) NumL = Cel.CellAddress.Row
Author Author's name ModifyDate Last modification date Sheet container object MySheet = Cel.Spreadsheet
CreationDate Creation date. Subject Document subject (string). Absolute coordinates (String) Coord = Cel.AbsoluteName
Description Document description Title Document title (un)protect cells
ModifiedBy User name who modified the UserDefined- Custom properties
Cel.CellProtection can take boolean values:
document. Properties (Object).
Prevent modification CellProtection.IsLocked = True
Is it a Calc document? Hide cell formula CellProtection.IsFormulaHidden = True
The Doc object points to the document (ex: Doc=ThisComponent). Hide cell CellProtection.IsHidden = True
CalcOK = Doc.SupportsService("com.sun.star.sheet.SpreadsheetDocument") Don't print cell CellProtection.IsPrintHidden = True
Calc – General functionalities Access cell contents
The Doc object points to the document (ex: Doc=ThisComponent). Properties
Automatic calculation Read text contents MyText = Cel.String
Read numeric contents aNumeber = Cel.Value
Active? (Boolean) Auto = Doc.isAutomaticCalculationEnabled
Read cell formula (en-US names) TheFormula = Cel.Formula
Disable Doc.enableAutomaticCalculation(False)
Read cell formula (localized names) LaFormule = Cel.FormulaLocal
Enable Doc.enableAutomaticCalculation(True)
Cell type TheType = Cel.Type
Force recalculation Doc.calculate (only for formulas not updated)
Empty a cell Cel.String = ""
Doc.calculateAll (all formulas)
Contents type (Type property)
Protect document
The constants com.sun.star.table.CellContentType.XXX represent the cell informa-
Is document protected? Test = Doc.isProtected
tion type (Cel.Type, above) :
Protect document Doc.protect(password) [password can be
empty] EMPTY Empty cell VALUE Numerical value
Unprotect document Doc.unprotect(password) TEXT Text contents FORMULA Formula contents
Write in a cell
Replace existing text Cel.String = "Hello !"
Replace an existing value Cel.Value = 1.234
Replace an existing formula Cel.Formula = "=AND(A1="YES";A2="OK")"
(localized)
Replace an existing formula Cel.FormulaLocal = "=ET(A1="OUI";A2="OK")"
LibOBasic-3-Calc-Flat-A4-EN-v111.odt (localized)
 Always test a cell before a single range because a cell is also a single range !
Ranges (ranges)
Range = set of cells, (including a single one): Dim MyRange As Object Rows/Columns (rows/columns)
Access to ranges Rows and columns are Sheet and Range objects properties.
MySheet is a sheet object. Get a range object Ran>: General
By cell default notation Ran = MySheet.getCellRangeByName("C2:G14") Rows (TheRows object) TheRows = MyRange.Rows
By name Ran = MySheet.getCellRangeByName("RangeName") Columns (TheCols object) TheCols = MyRange.Columns
By coordinates Ran = MySheet.getCellRangeByPosition(2, 1, 6, 13) Counting NbL = MyRange.Rows.Count
(X1, Y1, X2, Y2) NbC = MyRange.Columns.Count
Randomly Ran = ThisComponent.Sheets.getCellRangeByPosition(2, A row (TheRow object (base 0) TheRow = MyRange.Rows(index)
(ex third sheet) 2, 1, 6, 13)
A column (TheCol object (base 0) TheCol = MyRange.Columns(index)
Active range Row/Columns properties
Like active cell, but check "com.sun.star.sheet.SheetCellRange" or "[...].Sheet- Applies to Row or Rows (resp. Column or Columns).
CellRanges". Visible / Hidden (Boolean) IsVisible = True
Range selection Optimal width (Boolean) OptimalWidth = True
ThisComponent.CurrentController.select(MyRange) where MyRange is an objetc. Insert/delete rows/columns
Range coordinates Define object RorC, and FirstPos and LastPos the positions of the begining and end of
Coordinates (Object) Coord = MyRange.RangeAddress the row set (resp. columns) to add/delete (Long).
Sheet index (Integer) Ran = MyRange.RangeAddress.Sheet Insert RorC.insertByIndex(FirstPos, LastPos)
Column rank (Long) Delete RorC.removeByIndex(FirstPos, LastPos)
NumCHG = MyRange.RangeAddress.StartColumn
top/left corner Freeze row/columns
Row rank (Long) NumLHG = MyRange.RangeAddress.StartRow
Use the Controller object: MyController = ThisComponent.CurrentColtroller
top/left corner
Is there one? Freeze = MyController.hasFrozenPanes
Column rank (Long) NumCBD = MyRange.RangeAddress.EndColumn
Freeze MyController.freezeAtPosition(1, 2)
bottom/right corner
Delete MyController.freezeAtPosition(0, 0)
Row rank (Long) NumLBD = MyRow.RangeAddress.EndRow
bottom/right corner Call a Calc function
Sheet container object MySheet = MyRange.Spreadsheet
Coord = MyRange.AbsoluteName Use service "com.sun.star.sheet.FunctionAccess"
Absolute coordinates (String)
Usage
Named ranges
The Doc object points to the document. With Dim TheRanges As Object Dim FCalc As Object
Dim Result As (context dependent)
Named ranges TheRanges = Doc.NamedRanges Dim Params As (context dependent)
Number (Long) Nb = TheRanges.Count Dim FunctionName As String
Get a range (by index) MyRange = TheRanges(index) FCalc = CreateUnoService("com.sun.star.sheet.FunctionAccess")
Results = FCalc.callFunction(FunctionName, Params)
Check existence (name) Exist = TheRanges.hasByName("RangeName")
Get range (by name) MyRange = TheRanges.getByName("Range- ☞ Function name, parameters and type of results depends on the selected function
Name")  The function name must be its English name.
Add TheRanges.addNewByName("Rangename", Co- To get the function English name, switch temporarily to English Calc function names
display, at Tools > Options > LibreOffice Calc > Formula, Use English function names.
Coord : range coordinates ord, _
CellRef : reference cell object CellRef.CellAddress, 0)
Example 1 (function SUM())
Delete (by name) TheRanges.removeByName("RangeName") Dim FCalc As Object
Erase a range Dim Results As Long
FCalc = CreateUnoService("com.sun.star.sheet.FunctionAccess")
Erase MyRange contents MyRange.clearContents(EraseMode) Results = FCalc.callFunction("SUM", Array(1, 55, 321, 8))
EraseMode is a value that define the type of cleaning. Use com.sun.star.sheet.-
Example 2 (function ROUND())
CellFlags.XXX and combine them with +) :
ANNOTATION Comments STRING Text Dim FCalc As Object
DATETIME Date/time formatted numbers VALUE Numbers (except date/time) Dim Results As Double
Dim Params(1) As Variant
FORMULA Formulae Params(0) = 1,2345 'number to round
Get cell contents in a range Params(1) = 3 '3 places
FCalc = CreateUnoService("com.sun.star.sheet.FunctionAccess")
MyRange.DataArray is a table of cell values for MyRange. Results = FCalc.callFunction("ROUND", Params())
Copy range contents into another range
Have 2 ranges Source and Target, with same dimensions. Create a Calc function
Copy contents (values) from Source into Target.DataArray = Source.DataArray Create
Target.
Example : calculate the area of a trapeze (S = ((B + b) / 2) × H)
Write values in a range
MyRange is a range object and MyTable a table, with same dmensions, where values Function AreaTrapeze(GB As Double, PB As Double, H As Double) As
Double
must be transfered to the range. AreaTrapeze = ((GB + PB) / 2) * H
Dim MyTable As Variant End Function
MyTable = MyRange.DataArray 'MyTable takes the range dimensions
'(give values to the tabel elements) Usage in Calc
MyRange.DataArray = MyTable If A2 is the large base, A3 the small base and A4 the height, the area of the trapeze is ob-
☞ .DataArray is an embedded table: use .DataArray(i)(j) tained inserting the following formula in a cell: =AREATRAPEZE(A2;A3;A4)
Traverse cells in a range ☞ The macro receives the values of the arguments and not the cell object.
☞ The macro returns a value. It does not applies to a cell.
From a collection (MyRanges.Cells) create an enumeration. Traverse the range calling ☞ The function must be located in a library accessible at runtime (e.g.Standard library of
its properties hasMoreElements and NextElement: the document or user) (otherwise, it produces the #VALUE! error).
Dim Plages As Object
MyRanges =
ThisComponent.createInstance("com.sun.star.sheet.SheetCellRanges")
MyRanges.insertByName("", MyRange)
LEnum = MyRanges.Cells.CreateEnumeration
Do While LEnum.hasMoreElements
MyCell = LEnum.NextElement
' apply instructions to object cell Credits
Loop Author : Jean-François Nifenecker – jean-francois.nifenecker@laposte.net
 Empty cells are not traversed ! We are like dwarves perched on the shoulders of giants. If we are able to see more and farther than the
latter, and this is not at all because of the acuteness of our sight or the stature of our body, but because we
Ranges: Miscellaneous are carried aloft and elevated by the magnitude of the giants (Bernard de Chartres [attr.])
Merge cells of MyRange MyRange.Merge Hisory
Range types Version Date Comments
Depending of the access mode, ranges implement one of these services: 1.01 01-10-2017 First version.
① com.sun.star.sheet.SheetCell ④ com.sun.star.sheet.SheetCellRange 1.11 13-01-2018 Add range types.
② com.sun.star.table.CellRange ➄ com.sun.star.sheet.SheetCellRanges
③ com.sun.star.sheet.NamedRange
 Depending on the service implemented, ranges must be employed differently.
Test through method supportsService() (ex. below)
Cell or range?
To know the object type, test supportsService() with service_name below (boolean)
on the object (range or cell):
Licence
If MyObj.supportsService(service_name) Then …
This reference card is under license
Replace service_name by :
Cell ? "com.sun.star.sheet.SheetCell" ① CreativeCommons BY-SA v3 (fr).
Single range ? "com.sun.star.sheet.SheetCellRange" ④ Information
Multiple range ? "com.sun.star.sheet.SheetCellRanges" ➄ https://creativecommons.org/licenses/by-sa/3.0/fr/

You might also like