sfRcw‖SFDocuments.Calc service

EkFAT‖The SFDocuments shared library provides a number of methods and properties to facilitate the management and handling of LibreOfficeDev documents.

WHqRB‖The SFDocuments.Calc service is a subclass of the SFDocuments.Document service. All methods and properties defined for the Document service can also be accessed using a Calc service instance.

4uAEX‖The Calc service is focused on:

note

UFCyZ‖This help page describes methods and properties that are applicable only to Calc documents.


A47hJ‖Service invocation

RAtZX‖Before using the Calc service the ScriptForge library needs to be loaded or imported:

note

gF8D8‖• Basic macros require to load ScriptForge library using the following statement:
GlobalScope.BasicLibraries.loadLibrary("ScriptForge")

• Python scripts require an import from scriptforge module:
from scriptforge import CreateScriptService


z3JcW‖The Calc service is closely related to the UI service of the ScriptForge library. Below are a few examples of how the Calc service can be invoked.

3aa4B‖In Basic

mKqEu‖The code snippet below creates a Calc service instance that corresponds to the currently active Calc document.


    Set oDoc = CreateScriptService("Calc")
  

gECrc‖Another way to create an instance of the Calc service is using the UI service. In the following example, a new Calc document is created and oDoc is a Calc service instance:


    Dim ui As Object, oDoc As Object
    Set ui = CreateScriptService("UI")
    Set oDoc = ui.CreateDocument("Calc")
  

x6qdq‖Or using the OpenDocument method from the UI service:


    Set oDoc = ui.OpenDocument("C:\Documents\MyFile.ods")
  

LA2sA‖It is also possible to instantiate the Calc service specifying a window name for the CreateScriptService method:


    Dim oDoc As Object
    Set oDoc = CreateScriptService("SFDocuments.Calc", "MyFile.ods")
  

CKafD‖In the example above, "MyFile.ods" is the name of an open document window. If this argument is not provided, the active window is considered.

ucEa2‖It is also possible to invoke the Calc service using the document referenced by ThisComponent. This is specially useful when running a macro from within the Basic IDE.


    Dim oDoc As Object
    Set oDoc = CreateScriptService("Calc", ThisComponent)
  

gfpHw‖It is recommended to free resources after use:


    Set oDoc = oDoc.Dispose()
  

3EHn2‖However, if the document was closed using the CloseDocument method, it becomes unnecessary to free resources using the command described above.

BenDd‖In Python

    myDoc = CreateScriptService("Calc")
  

    ui = CreateScriptService("UI")
    myDoc = ui.CreateDocument("Calc")
  

    myDoc = ui.OpenDocument(r"C:\Documents\MyFile.ods")
  

    myDoc = CreateScriptService("SFDocuments.Calc", "MyFile.ods")
    myDoc.Dispose()
  

    bas = CreateScriptService("Basic")
    myDoc = CreateScriptService("Calc", bas.ThisComponent)
  
tip

WqVjE‖The use of the prefix "SFDocuments." while calling the service is optional.


Cpd5a‖Definitions

4gE5A‖Many methods require a "Sheet" or a "Range" as argument. Single cells are considered a special case of a Range.

kq2Br‖Both may be expressed either as a string or as a reference (= object) depending on the situation:

EFSA4‖Example:

AHSav‖The example below copies data from document A (opened as read-only and hidden) to document B.

3aa4B‖In Basic

    Dim oDocA As Object, oDocB As Object
    Set oDocA = ui.OpenDocument("C:\Documents\FileA.ods", Hidden := True, ReadOnly := True)
    Set oDocB = ui.OpenDocument("C:\Documents\FileB.ods")
    oDocB.CopyToRange(oDocA.Range("SheetX.D4:F8"), "D2:F6") 'CopyToRange(source, target)
  
BenDd‖In Python

    docA = ui.OpenDocument(r"C:\Documents\FileA.ods", hidden = True, readonly = True)
    docB = ui.OpenDocument(r"C:\Documents\FileB.ods")
    docB.CopyToRange(docA.Range("SheetX.D4:F8"), "D2:F6")
  

SheetName

iED65‖Either the sheet name as a string or an object produced by the .Sheet property.

GDuU3‖The shortcut "~" (tilde) represents the current sheet.

RangeName

nskFb‖Either a string designating a set of contiguous cells located in a sheet of the current instance or an object produced by the .Range property.

6CySa‖The shortcut "~" (tilde) represents the current selection or the first selected range if multiple ranges are selected.

7JEat‖The shortcut "*" represents all used cells.

C6fBT‖The sheet name is optional when defining a range. If no sheet name is provided, then the active sheet is used. Surrounding single quotes and $ signs are allowed but ignored.

5fjQM‖When specifying a SheetName as a string, the use of single quotes to enclose the sheet name are required if the name contains blank spaces " " or periods ".".

BsAKT‖The examples below illustrate in which cases the use of single quotes is mandatory:


      DGacM‖' The use of single quotes is optional
      oDoc.clearAll("SheetA.A1:B10")
      oDoc.clearAll("'SheetA'.A1:B10")
      yWFhF‖' The use of single quotes is required
      oDoc.clearAll("'Sheet.A'.A1:B10")
    
tip

GVF9g‖Except for the CurrentSelection property, the Calc service considers only single ranges of cells.


vRxTa‖Examples of valid ranges

yADDC‖1) $'SheetX'.D2
2) $D$2

pMZEe‖A single cell

AcGDY‖1) $'SheetX'.D2:F6
2) D2:D10

P7Ete‖Single range with multiple cells

vXrSu‖$'SheetX'.*

eQu5j‖All used cells in the given sheet

C6egy‖1) $'SheetX'.A:A (column A)
2) 3:5 (rows 3 to 5)

qpGBr‖All cells in contiguous columns or rows up to the last used cell

qezwg‖myRange

97TnU‖A range named "myRange" at spreadsheet level

WxyY4‖1) ~.someRange
2) SheetX.someRange

9gjmL‖A range name at sheet level

yB3Be‖myDoc.Range("SheetX.D2:F6")

ENndn‖A range within the sheet SheetX in file associated with the myDoc Calc instance

Yero3‖~.~ or ~

kmjCL‖The current selection in the active sheet


qFqGJ‖Properties

nntpM‖All the properties generic to any document are implicitly applicable also to Calc documents. For more information, read the Document service Help page.

DTzRF‖The properties specifically available for Calc documents are:

G4iX6‖Name

PK7n2‖Readonly

oFX3A‖Argument

H9m2q‖Return type

DDSFu‖Description

CurrentSelection

3MHFG‖No

pJnFE‖None

UUDuD‖String or array of strings

kAAXc‖The single selected range as a string or the list of selected ranges as an array.

FirstCell

PFB5D‖Yes

5GeyC‖SheetName or RangeName as String

String

TBHV2‖Returns the first used cell in a given range or sheet.

FirstColumn

BkCoD‖Yes

ToQBc‖SheetName or RangeName as String

Long

boSak‖Returns the leftmost column number in a given range or sheet.

FirstRow

3AKqL‖Yes

zf3hK‖SheetName or RangeName as String

Long

BXscD‖Returns the topmost row number in a given range or sheet.

Height

BHFeu‖Yes

KedYU‖RangeName As String

Long

FhLMF‖The number of rows (>= 1) in the given range.

LastCell

cU3Ah‖Yes

ALJCP‖SheetName or RangeName as String

String

SNj7Q‖Returns the last used cell in a given range or sheet.

LastColumn

75PEK‖Yes

3h43j‖SheetName or RangeName as String

Long

bU5vD‖The last used column in a given range or sheet.

LastRow

q9Bx7‖Yes

r6diM‖SheetName or RangeName as String

Long

SDdEC‖The last used row in a given range or sheet.

Range

4t3He‖Yes

2BJKz‖RangeName As String

Object

2tmEj‖A range reference that can be used as argument of methods like CopyToRange.

Region

boDiE‖Yes

kJCwG‖RangeName As String

String

ey2LS‖Returns the address of the smallest area that contains the specified range so that the area is surrounded by empty cells or sheet edges. This is equivalent to applying the shortcut to the given range.

Sheet

66iAb‖Yes

dWFQE‖SheetName As String

Object

4KoAw‖A sheet reference that can be used as argument of methods like CopySheet.

SheetName

WanFm‖Yes

wRCYZ‖RangeName As String

String

w7Gft‖Returns the sheet name of a given range address.

Sheets

HLpEQ‖Yes

V43zC‖None

B5BXR‖Array of strings

qGsms‖The list with the names of all existing sheets.

Width

EaAB2‖Yes

PFLkD‖RangeName As String

Long

BKFhE‖The number of columns (>= 1) in the given range.

XCellRange

cju3B‖Yes

DMf2S‖RangeName As String

Object

VaGpB‖A com.sun.star.Table.XCellRange UNO object.

XSheetCellCursor

nAD2d‖Yes

yNxZn‖RangeName As String

Object

UydnH‖A com.sun.star.sheet.XSheetCellCursor UNO object. After moving the cursor, the resulting range address can be accessed through the AbsoluteName UNO property of the cursor object, which returns a string value that can be used as argument for properties and methods of the Calc service.

XSpreadsheet

QbTFX‖Yes

jWLAC‖SheetName As String

Object

cJAB7‖A com.sun.star.sheet.XSpreadsheet UNO object.


tip

nZz4a‖Visit LibreOfficeDev API Documentation's website to learn more about XCellRange, XSheetCellCursor and XSpreadsheet UNO objects.


V5dF8‖Methods

soCDf‖List of Methods in the Calc Service

A1Style
Activate
Charts
ClearAll
ClearFormats
ClearValues
CompactLeft
CompactUp
CopySheet
CopySheetFromFile
CopyToCell
CopyToRange
CreateChart
CreatePivotTable
DAvg
DCount

DMax
DMin
DSum
ExportRangeToFile
Forms
GetColumnName
GetFormula
GetValue
ImportFromCSVFile
ImportFromDatabase
ImportStylesFromFile
InsertSheet
MoveRange
MoveSheet
Offset
OpenRangeSelector

PrintOut
Printf
RemoveDuplicates
RemoveSheet
RenameSheet
SetArray
SetCellStyle
SetFormula
SetValue
ShiftDown
ShiftLeft
ShiftRight
ShiftUp
SortRange



A1Style

Dis6i‖Returns a range address as a string based on sheet coordinates, i.e. row and column numbers.

4TBiF‖If only a pair of coordinates is given, then an address to a single cell is returned. Additional arguments can specify the bottom-right cell of a rectangular range.

FVEx2‖Syntax:

svc.A1Style(row1: int, column1: int, row2: int = 0; column2: int = 0; sheetname: str = "~"): str

WADQ4‖Parameters:

2BuFG‖row1, column1: Specify the row and column numbers of the top-left cell in the range to be considered. Row and column numbers start at 1.

i7N7S‖row2, column2: Specify the row and column numbers of the bottom-right cell in the range to be considered. If these arguments are not provided, or if values smaller than row1 and column1 are given, then the address of the single cell range represented by row1 and column1 is returned.

Egj6k‖sheetname: The name of the sheet to be appended to the returned range address. The sheet must exist. The default value is "~" corresponding to the currently active sheet.

EFSA4‖Example:

idfEg‖The examples below in Basic and Python consider that "Sheet1" is the currently active sheet.

3aa4B‖In Basic

    Set oDoc = CreateScriptService("Calc")
    addr1 = oDoc.A1Style(1, 1) ' '$Sheet1'.$A$1
    addr2 = oDoc.A1Style(2, 2, 3, 6) ' '$Sheet1'.$B$2:$F$3
    addr3 = oDoc.A1Style(2, 2, 0, 6) ' '$Sheet1'.$B$2
    addr4 = oDoc.A1Style(3, 4, 3, 8, "Sheet2") ' '$Sheet2'.$D$3:$H$3
    addr5 = oDoc.A1Style(5, 1, SheetName := "Sheet3") ' '$Sheet3'.$A$5
  
BenDd‖In Python

    doc = CreateScriptService("Calc")
    addr1 = doc.A1Style(1, 1) # '$Sheet1'.$A$1
    addr2 = doc.A1Style(2, 2, 3, 6) # '$Sheet1'.$B$2:$F$3
    addr3 = doc.A1Style(2, 2, 0, 6) # '$Sheet1'.$B$2
    addr4 = doc.A1Style(3, 4, 3, 8, "Sheet2") # '$Sheet2'.$D$3:$H$3
    addr5 = doc.A1Style(5, 1, sheetname="Sheet3") # '$Sheet3'.$A$5
  
tip

eXJNG‖The method A1Style can be combined with any of the many properties and methods of the Calc service that require a range as argument, such as GetValue, GetFormula, ClearAll, etc.


Activate

Hfeug‖If the argument sheetname is provided, the given sheet is activated and it becomes the currently selected sheet. If the argument is absent, then the document window is activated.

FVEx2‖Syntax:

svc.Activate(sheetname: str = ""): bool

WADQ4‖Parameters:

EhMzz‖sheetname: The name of the sheet to be activated in the document. The default value is an empty string, meaning that the document window will be activated without changing the active sheet.

EFSA4‖Example:

2cgiA‖The example below activates the sheet named "Sheet4" in the currently active document.

3aa4B‖In Basic

    Dim ui as Variant, oDoc as Object
    Set ui = CreateScriptService("UI")
    Set oDoc = ui.GetDocument(ui.ActiveWindow)
    oDoc.Activate("Sheet4")
  
BenDd‖In Python

    ui = CreateScriptService("UI")
    myDoc = ui.GetDocument(ui.ActiveWindow)
    myDoc.Activate("Sheet4")
  
tip

LRebz‖Activating a sheet makes sense only if it is performed on a Calc document. To make sure you have a Calc document at hand you can use the isCalc property of the document object, which returns True if it is a Calc document and False otherwise.


Charts

KWFFF‖Returns either the list with the names of all chart objects in a given sheet or a single Chart service instance.

FVEx2‖Syntax:

svc.Charts(sheetname: str, chartname: str = ""): obj

WADQ4‖Parameters:

T2e3d‖sheetname: The name of the sheet from which the list of charts is to be retrieved or where the specified chart is located.

Dhape‖chartname: The user-defined name of the chart object to be returned. If the chart does not have a user-defined name, then the internal object name can be used. If this argument is absent, then the list of chart names in the specified sheet is returned.

tip

C7CSH‖Use the Navigator sidebar to check the names assigned to charts under the OLE objects category.


EFSA4‖Example:

3aa4B‖In Basic

zbX9R‖The example below shows the number of chart objects in "Sheet1".


    Dim arrNames as Object
    arrNames = oDoc.Charts("Sheet1")
    MsgBox "There are " & UBound(arrNames) + 1 & " charts in Sheet1"
  

gsLHX‖The following example accesses the chart named "MyChart" in "Sheet1" and prints its type.


    Dim oChart as Object
    oChart = oDoc.Charts("Sheet1", "MyChart")
    MsgBox oChart.ChartType
  
BenDd‖In Python

    bas = CreateScriptService("Basic")
    chart_names = doc.Charts("Sheet1")
    bas.MsgBox(f"There are {len(chart_names)} charts in Sheet1")
  

    chart = doc.Charts("Sheet1", "MyChart")
    bas.MsgBox(chart.ChartType)
  

ClearAll

auJdC‖Clears all the contents and formats of the given range.

kjBF4‖A filter formula can be specified to determine which cells shall be affected.

FVEx2‖Syntax:

svc.ClearAll(range: str, opt filterformula: str, opt filterscope: str)

WADQ4‖Parameters:

UXnVo‖range: The range to be cleared, as a string.

Bq7qT‖filterformula: A Calc formula that shall be applied to the given range to determine which cells will be affected. The specified formula must return True or False. If this argument is not specified, then all cells in the range are affected.

Lvzwc‖filterscope: Determines how filterformula is expanded to the given range. This argument is mandatory if a filterformula is specified. The following values are accepted:

EFSA4‖Example:

3aa4B‖In Basic

    gZzon‖' Clears all cells in the range SheetX.A1:J10
    dZnwN‖oDoc.ClearAll("SheetX.A1:J10")
    SpP9R‖' Clears all cells in the range SheetX.A1:J10 that have a value greater than 100
    7Nnnv‖oDoc.ClearAll("SheetX.A1:J10", "=SheetX.A1>100", "CELL")
    8CXRd‖' Clears all rows in the range SheetX.A1:J10 whose sum is greater than 500
    pABDv‖oDoc.ClearAll("SheetX.A1:J10", "=SUM(SheetX.A1:J1)>100", "ROW")
    5av7R‖' Clears all columns in the range SheetX.A1:J10 whose sum is greater than 500
    Bp2iA‖oDoc.ClearAll("SheetX.A1:J10", "=SUM(SheetX.A1:A10)>100", "COLUMN")
  
BenDd‖In Python

    jBH48‖myDoc.ClearAll("SheetX.A1:F10")
    CGEqi‖myDoc.ClearAll("SheetX.A1:J10", "=SheetX.A1>100", "CELL")
    GDBWA‖myDoc.ClearAll("SheetX.A1:J10", "=SUM(SheetX.A1:J1)>100", "ROW")
    3fSEb‖myDoc.ClearAll("SheetX.A1:J10", "=SUM(SheetX.A1:A10)>100", "COLUMN")
  

ClearFormats

Wz6CH‖Clears the formats and styles in the given range.

PqtC3‖A filter formula can be specified to determine which cells shall be affected.

FVEx2‖Syntax:

svc.ClearFormats(range: str, opt filterformula: str, opt filterscope: str)

WADQ4‖Parameters:

6Qxnv‖range: The range whose formats and styles are to be cleared, as a string.

Bq7qT‖filterformula: A Calc formula that shall be applied to the given range to determine which cells will be affected. The specified formula must return True or False. If this argument is not specified, then all cells in the range are affected.

Lvzwc‖filterscope: Determines how filterformula is expanded to the given range. This argument is mandatory if a filterformula is specified. The following values are accepted:

EFSA4‖Example:

3aa4B‖In Basic

      oDoc.ClearFormats("SheetX.*")
  
BenDd‖In Python

    myDoc.ClearFormats("SheetX.*")
  
tip

WUdrV‖Refer to the ClearAll method documentation for examples on how to use the arguments filterformula and filterscope.


ClearValues

sMwMp‖Clears the values and formulas in the given range.

te7oW‖A filter formula can be specified to determine which cells shall be affected.

FVEx2‖Syntax:

svc.ClearValues(range: str, opt filterformula: str, opt filterscope: str)

WADQ4‖Parameters:

eEGn9‖range: The range whose values and formulas are to be cleared, as a string.

Bq7qT‖filterformula: A Calc formula that shall be applied to the given range to determine which cells will be affected. The specified formula must return True or False. If this argument is not specified, then all cells in the range are affected.

Lvzwc‖filterscope: Determines how filterformula is expanded to the given range. This argument is mandatory if a filterformula is specified. The following values are accepted:

EFSA4‖Example:

3aa4B‖In Basic

      oDoc.ClearValues("SheetX.A1:F10")
  
BenDd‖In Python

    myDoc.ClearValues("SheetX.A1:F10")
  
tip

ZhT2V‖Refer to the ClearAll method documentation for examples on how to use the arguments filterformula and filterscope.


CompactLeft

JWFDb‖Deletes the columns of a specified range that match a filter expressed as a Calc formula. The filter is applied to each column to decide whether it will be deleted or not.

4JWnp‖The deleted column can be limited to the height of the specified range or span to the height of the entire sheet, thus deleting whole columns.

VAVU3‖This method returns a string with the range address of the compacted range. If all columns are deleted, then an empty string is returned.

note

j2GAb‖If a range of cells is selected, calling this method will not impact the selection.


FVEx2‖Syntax:

svc.CompactLeft(range: str, wholecolumn: bool = False, opt filterformula: str): str

WADQ4‖Parameters:

WsrKe‖range: The range from which columns will be deleted, as a string.

Q9QBp‖wholecolumn: If this option is set to True the entire column will be deleted from the sheet. The default value is False, which means that the deleted column will be limited to the height of the specified range.

M7qto‖filterformula: The filter to be applied to each column to determine whether or not it will be deleted. The filter is expressed as a Calc formula that should be applied to the first column. When the formula returns True for a column, that column will be deleted. The default filter deletes all empty columns.

8sYWa‖For example, suppose range A1:J200 is selected (height = 200), so the default formula is =(COUNTBLANK(A1:A200)=200). This means that if all 200 cells are empty in the first column (Column A), then the column is deleted. Note that the formula is expressed with respect to the first column only. Internally the CompactLeft method will generalize this formula for all the remaining columns.

note

LQz5G‖Calc functions used in the filterformula argument must be expressed using their English names. Visit the Wiki page List of Calc Functions for a complete list of Calc functions in English.


EFSA4‖Example:

3aa4B‖In Basic

    FDspT‖' Delete all empty columns in the range G1:L10 from Sheet1
    huH9x‖newrange = oDoc.CompactLeft("Sheet1.G1:L10")
    2BkcC‖' The example below is similar, but the entire column is deleted from the sheet
    6GoCu‖newrange = oDoc.CompactLeft("Sheet1.G1:L10", WholeColumn := True)
    KfQRA‖' Deletes all columns where the first row is marked with an "X"
    fLJ7y‖newrange = oDoc.CompactLeft("Sheet1.G1:L10", FilterFormula := "=(G1=""X"")")
    UqpQB‖' Deletes all columns where the sum of values in the column is odd
    5rxDM‖newrange = oDoc.CompactLeft("Sheet1.G1:L10", FilterFormula := "=(MOD(SUM(G1:G10);2)=1)")
  
BenDd‖In Python

    i4ux6‖newrange = myDoc.CompactLeft("Sheet1.G1:L10")
    j5kGd‖newrange = myDoc.CompactLeft("Sheet1.G1:L10", wholecolumn = True)
    pBca4‖newrange = myDoc.CompactLeft("Sheet1.G1:L10", filterformula = '=(G1="X")')
    VGAj6‖newrange = myDoc.CompactLeft("Sheet1.G1:L10", filterformula = '=(MOD(SUM(G1:G10);2)=1)')
  

CompactUp

vqJ5B‖Deletes the rows of a specified range that match a filter expressed as a Calc formula. The filter is applied to each row to decide whether it will be deleted or not.

RhiRD‖The deleted rows can be limited to the width of the specified range or span to the width of the entire sheet, thus deleting whole rows.

Yw3WB‖This method returns a string with the range address of the compacted range. If all rows are deleted, then an empty string is returned.

note

RtGtW‖If a range of cells is selected, calling this method will not impact the selection.


FVEx2‖Syntax:

svc.CompactUp(range: str, wholerow: bool = False, opt filterformula: str): str

WADQ4‖Parameters:

X3Ekj‖range: The range from which rows will be deleted, as a string.

sAtHM‖wholerow: If this option is set to True the entire row will be deleted from the sheet. The default value is False, which means that the deleted row will be limited to the width of the specified range.

pKXWR‖filterformula: The filter to be applied to each row to determine whether or not it will be deleted. The filter is expressed as a Calc formula that should be applied to the first row. When the formula returns True for a row, that row will be deleted. The default filter deletes all empty rows.

2DsWD‖For example, suppose range A1:J200 is selected (width = 10), so the default formula is =(COUNTBLANK(A1:J1)=10). This means that if all 10 cells are empty in the first row (Row 1), then the row is deleted. Note that the formula is expressed with respect to the first row only. Internally the CompactUp method will generalize this formula for all the remaining rows.

note

BxmHj‖The Calc functions used in the formula specified in the filterformula argument must be expressed using their English names. Visit the Wiki page List of Calc Functions for a complete list of Calc functions in English.


EFSA4‖Example:

3aa4B‖In Basic

    GuWzD‖' Delete all empty rows in the range G1:L10 from Sheet1
    GBrKx‖newrange = oDoc.CompactUp("Sheet1.G1:L10")
    FV3Ev‖' The example below is similar, but the entire row is deleted from the sheet
    Y5YVh‖newrange = oDoc.CompactUp("Sheet1.G1:L10", WholeRow := True)
    mFqmA‖' Deletes all rows where the first column is marked with an "X"
    gJQRm‖newrange = oDoc.CompactUp("Sheet1.G1:L10", FilterFormula := "=(G1=""X"")")
    DoDfJ‖' Deletes all rows where the sum of values in the row is odd
    zXErV‖newrange = oDoc.CompactUp("Sheet1.G1:L10", FilterFormula := "=(MOD(SUM(G1:L1);2)=1)")
  
BenDd‖In Python

    Mcwq5‖newrange = myDoc.CompactUp("Sheet1.G1:L10")
    tXmJD‖newrange = myDoc.CompactUp("Sheet1.G1:L10", wholerow = True)
    WZ3XF‖newrange = myDoc.CompactUp("Sheet1.G1:L10", filterformula = '=(G1="X")')
    4DfG9‖newrange = myDoc.CompactUp("Sheet1.G1:L10", filterformula = '=(MOD(SUM(G1:L1);2)=1)')
  

CopySheet

n6vJD‖Copies a specified sheet before an existing sheet or at the end of the list of sheets. The sheet to be copied may be contained inside any open Calc document. Returns True if successful.

FVEx2‖Syntax:

svc.CopySheet(sheetname: any, newname: str, [beforesheet: any]): bool

WADQ4‖Parameters:

YqGL2‖sheetname: The name of the sheet to be copied as a string or its reference as an object.

5cEGG‖newname: The name of the sheet to insert. The name must not be in use in the document.

8sSno‖beforesheet: The name (string) or index (numeric, starting from 1) of the sheet before which to insert the copied sheet. This argument is optional and the default behavior is to add the copied sheet at the last position.

EFSA4‖Example:

3aa4B‖In Basic

yuvEn‖The following example makes a copy of the sheet "SheetX" and places it as the last sheet in the current document. The name of the copied sheet is "SheetY".


    Dim oDoc as Object
    pqVdW‖'Gets the Document object of the active window
    Set oDoc = CreateScriptService("Calc")
    oDoc.CopySheet("SheetX", "SheetY")
  

xUG9G‖The example below copies "SheetX" from "FileA.ods" and pastes it at the last position of "FileB.ods" with the name "SheetY":


      Dim oDocA As Object : Set oDocA = ui.OpenDocument("C:\Documents\FileA.ods", Hidden := True, ReadOnly := True)
      Dim oDocB As Object : Set oDocB = ui.OpenDocument("C:\Documents\FileB.ods")
      oDocB.CopySheet(oDocA.Sheet("SheetX"), "SheetY")
  
BenDd‖In Python

    myDoc.CopySheet("SheetX", "SheetY")
  

    docA = ui.OpenDocument(r"C:\Documents\FileA.ods", hidden = True, readonly = True)
    docB = ui.OpenDocument(r"C:\Documents\FileB.ods")
    docB.CopySheet(docA.Sheet("SheetX"), "SheetY")
  
tip

2AAEx‖To copy sheets between open documents, use CopySheet. To copy sheets from documents that are closed, use CopySheetFromFile.


CopySheetFromFile

5fctt‖Copies a specified sheet from a closed Calc document and pastes it before an existing sheet or at the end of the list of sheets of the file referred to by a Document object.

M9mDA‖If the file does not exist, an error is raised. If the file is not a valid Calc file, a blank sheet is inserted. If the source sheet does not exist in the input file, an error message is inserted at the top of the newly pasted sheet.

FVEx2‖Syntax:

svc.CopySheetFromFile(filename: str, sheetname: str, newname: str, [beforesheet: any]): bool

WADQ4‖Parameters:

tCseT‖filename: Identifies the file to open. It must follow the SF_FileSystem.FileNaming notation. The file must not be protected with a password.

gHjz6‖sheetname: The name of the sheet to be copied as a string.

PeZ4F‖newname: The name of the copied sheet to be inserted in the document. The name must not be in use in the document.

2niVz‖beforesheet: The name (string) or index (numeric, starting from 1) of the sheet before which to insert the copied sheet. This argument is optional and the default behavior is to add the copied sheet at the last position.

EFSA4‖Example:

iEHJy‖The following example copies "SheetX" from "myFile.ods" and pastes it into the document referred to by "oDoc" as "SheetY" at the first position.

3aa4B‖In Basic

    oDoc.CopySheetFromFile("C:\Documents\myFile.ods", "SheetX", "SheetY", 1)
  
BenDd‖In Python

    myDoc.CopySheetFromFile(r"C:\Documents\myFile.ods", "SheetX", "SheetY", 1)
  

CopyToCell

kELHv‖Copies a specified source range (values, formulas and formats) to a destination range or cell. The method reproduces the behaviour of a Copy/Paste operation from a range to a single cell.

KixB2‖It returns a string representing the modified range of cells. The size of the modified area is fully determined by the size of the source area.

KCiyF‖The source range may belong to another open document.

FVEx2‖Syntax:

svc.CopyToCell(sourcerange: any, destinationcell: str): str

WADQ4‖Parameters:

RBQG9‖sourcerange: The source range as a string when it belongs to the same document or as a reference when it belongs to another open Calc document.

3MUwk‖destinationcell: The destination cell where the copied range of cells will be pasted, as a string. If a range is given, only its top-left cell is considered.

EFSA4‖Example:

3aa4B‖In Basic

FbkjF‖Next is an example where the source and destination are in the same file:


      oDoc.CopyToCell("SheetX.A1:F10", "SheetY.C5")
  

Zh3Wp‖The example below illustrates how to copy a range from another open Calc document:


    Dim ui as Variant : ui = CreateScriptService("UI")
    Dim oDocSource As Object, oDocDestination As Object
    uFAEe‖'Open the source document in the background (hidden)
    Set oDocSource = ui.OpenDocument("C:\SourceFile.ods", Hidden := True, ReadOnly := True)
    Set oDocDestination = CreateScriptService("Calc")
    oDocDestination.CopyToCell(oDocSource.Range("Sheet1.C2:C4"), "SheetT.A5")
    PBgwL‖'Do not forget to close the source document because it was opened as hidden
    oDocSource.CloseDocument()
  
BenDd‖In Python

    docSource = ui.OpenDocument(r"C:\Documents\SourceFile.ods", hidden = True, readonly = True)
    docDestination = CreateScriptService("Calc")
    docDestination.CopyToCell(docSource.Range("Sheet1.C2:C4"), "SheetT.A5")
    docSource.CloseDocument()
  
tip

ZzDAQ‖To simulate a Copy/Paste from a range to a single cell, use CopyToCell. To simulate a Copy/Paste from a range to a larger range (with the same cells being replicated several times), use CopyToRange.


CopyToRange

maHke‖Copies downwards and/or rightwards a specified source range (values, formulas and formats) to a destination range. The method imitates the behaviour of a Copy/Paste operation from a source range to a larger destination range.

jYha4‖The method returns a string representing the modified range of cells.

wfzcw‖The source range may belong to another open document.

FVEx2‖Syntax:

svc.CopyToRange(sourcerange: any, destinationrange: str): str

WADQ4‖Parameters:

CEaED‖sourcerange: The source range as a string when it belongs to the same document or as a reference when it belongs to another open Calc document.

v3d3d‖destinationrange: The destination of the copied range of cells, as a string.

EFSA4‖Example:

3aa4B‖In Basic

LsHF6‖Copy within the same document:


    oDoc.CopyToRange("SheetX.A1:F10", "SheetY.C5:J5")
    dNdmJ‖' Returns a range string: "$SheetY.$C$5:$J$14"
  

FBbwi‖Copy from one file to another:


    Dim oDocA As Object : Set oDocA = ui.OpenDocument("C:\Documents\FileA.ods", Hidden := True, ReadOnly := True)
    Dim oDocB As Object : Set oDocB = ui.OpenDocument("C:\Documents\FileB.ods")
    oDocB.CopyToRange(oDocA.Range("SheetX.A1:F10"), "SheetY.C5:J5")
  
BenDd‖In Python

    doc.CopyToRange("SheetX.A1:F10", "SheetY.C5:J5")
  

    docA = ui.OpenDocument(r"C:\Documents\FileA.ods", hidden = True, readonly = True)
    docB = ui.OpenDocument(r"C:\Documents\FileB.ods")
    docB.CopyToRange(docA.Range("SheetX.A1:F10"), "SheetY.C5:J5")
  

CreateChart

L3GHp‖Creates a new chart object showing the data in the specified range. The returned chart object can be further manipulated using the Chart service.

FVEx2‖Syntax:

svc.CreateChart(chartname: str, sheetname: str, range: str, columnheader: bool = False, rowheader: bool = False): obj

WADQ4‖Parameters:

2YZ5H‖chartname: The user-defined name of the chart to be created. The name must be unique in the same sheet.

BBtB3‖sheetname: The name of the sheet where the chart will be placed.

GEiCb‖range: The range to be used as the data source for the chart. The range may refer to any sheet of the Calc document.

L3dSo‖columnheader: When True, the topmost row of the range is used as labels for the category axis or the legend (Default = False).

iyq5m‖rowheader: When True, the leftmost column of the range is used as labels for the category axis or the legend. (Default = False).

EFSA4‖Example:

CKzBZ‖The examples below in Basic and Python create a chart using the data contained in the range "A1:B5" of "Sheet1" and place the chart in "Sheet2".

3aa4B‖In Basic

    Set oChart = oDoc.CreateChart("MyChart", "Sheet2", "Sheet1.A1:B5", RowHeader := True)
    oChart.ChartType = "Donut"
  
BenDd‖In Python

    chart = doc.CreateChart("MyChart", "Sheet2", "Sheet1.A1:B5", rowheader=True)
    chart.ChartType = "Donut"
  
tip

NcUxk‖Refer to the help page about ScriptForge's Chart service to learn more how to further manipulate chart objects. It is possible to change properties as the chart type, chart and axes titles and chart position.


CreatePivotTable

DFCVe‖Creates a new pivot table with the properties defined by the arguments passed to the method.

gouER‖A name must be provided for the pivot table. If a pivot table with the same name already exists in the targeted sheet, it will be replaced without warning.

SnCCg‖This method returns a string containing the range where the new pivot table was placed.

FVEx2‖Syntax:

svc.CreatePivotTable(pivottablename: str, sourcerange: str, targetcell: str, datafields: str[0..*], rowfields: str[0..*], columnfields: str[0..*], filterbutton: bool = true, rowtotals: bool = true, columntotals: bool = true): str

WADQ4‖Parameters:

AKjmT‖pivottablename: The user-defined name of the new pivot table.

vvGTx‖sourcerange: The range containing the raw data, as a string. It is assumed that the first row contains the field names that are used by the pivot table.

twWbD‖targetcell: The top-left cell where the new pivot table will be placed. If a range is specified, only its top-left cell is considered.

YXG64‖datafields: It can be either a single string or an array containing strings that define field names and functions to be applied. When an array is specified, it must follow the syntax Array("FieldName[;Function]", ...).

cKZ3U‖The allowed functions are: Sum, Count, Average, Max, Min, Product, CountNums, StDev, StDevP, Var, VarP and Median. Function names must be provided in English. When all values are numerical, Sum is the default function, otherwise the default function is Count.

JKCoA‖rowfields: A single string or an array with the field names that will be used as the pivot table rows.

8GW5G‖columnfields: A single string or an array with the field names that will be used as the pivot table columns.

iTL7C‖filterbutton: Determines whether a filter button will be displayed above the pivot table (Default = True).

FXyRo‖rowtotals: Specifies if a separate column for row totals will be added to the pivot table (Default = True).

xf8Nt‖columntotals Specifies if a separate row for column totals will be added to the pivot table (Default = True)

EFSA4‖Example:

3aa4B‖In Basic

    Dim vData As Variant, oDoc As Object, ui As Object, sTable As String, sPivot As String
    Set ui = CreateScriptService("UI")
    Set oDoc = ui.CreateDocument("Calc")
    EWpPF‖vData = Array(Array("Item", "State", "Team", "2002", "2003", "2004"), _
    S7S92‖    Array("Books", "Michigan", "Jean", 14788, 30222, 23490), _
    EBYBq‖    Array("Candy", "Michigan", "Jean", 26388, 15641, 32849), _
    PoYhz‖    Array("Pens", "Michigan", "Jean", 16569, 32675, 25396), _
    G9Bcb‖    Array("Books", "Michigan", "Volker", 21961, 21242, 29009), _
    ZDxHN‖    Array("Candy", "Michigan", "Volker", 26142, 22407, 32841))
    sTable = oDoc.SetArray("A1", vData)
    sPivot = oDoc.CreatePivotTable("PT1", sTable, "H1", _
    5RyFZ‖    Array("2002", "2003;count", "2004;average"), _ ' Three data fields
    fvM3F‖    "Item", _ ' A single row field
    UM7u8‖    Array("State", "Team"), False) ' Two column fields
  
BenDd‖In Python

    ui = CreateScriptService("UI")
    doc = ui.CreateDocument("Calc")
    4c6uZ‖vData = [["Item", "State", "Team", "2002", "2003", "2004"],
    vNu6x‖         ["Books", "Michigan", "Jean", 14788, 30222, 23490],
    K55vj‖         ["Candy", "Michigan", "Jean", 26388, 15641, 32849],
    TGBpj‖         ["Pens", "Michigan", "Jean", 16569, 32675, 25396)],
    mqKTy‖         ["Books", "Michigan", "Volker", 21961, 21242, 29009],
    4S8LC‖         ["Candy", "Michigan", "Volker", 26142, 22407, 32841]]
    sTable = doc.SetArray("A1", vData)
    sPivot = doc.CreatePivotTable("PT1", sTable, "H1",
    jAZKV‖                              ["2002", "2003;count", "2004;average"],
    xp2pn‖                              "Item",
    tYyko‖                              ["State", "Team"], False)
  
tip

scaEA‖To learn more about Pivot Tables in LibreOfficeDev Calc, read the Pivot Table help page.


DAvg, DCount, DMax, DMin and DSum

Af2f6‖Apply the functions Average, Count, Max, Min and Sum, respectively, to all the cells containing numeric values on a given range, excluding values from filtered and hidden rows and hidden columns, the same as for the status bar functions.

FVEx2‖Syntax:

svc.DAvg(range: str): float

svc.DCount(range: str): float

svc.DMax(range: str): float

svc.DMin(range: str): float

svc.DSum(range: str): float

WADQ4‖Parameters:

F2UTC‖range: The range to which the function will be applied, as a string.

EFSA4‖Example:

ZhAYY‖The example below applies the Sum function to the range "A1:A1000" of the currently selected sheet:

3aa4B‖In Basic

      result = oDoc.DSum("~.A1:A1000")
  
BenDd‖In Python

    result = myDoc.DSum("~.A1:A1000")
  
note

iTEts‖Cells in the given range that contain text will be ignored by all of these functions. For example, the DCount method will not count cells with text, only numerical cells.


ExportRangeToFile

S6JvC‖Exports the specified range as an image or PDF file.

eKaCo‖This method returns True if the destination file was successfully saved.

note

p6Hg5‖Hidden rows or columns in the specified range are not exported to the destination file.


FVEx2‖Syntax:

svc.ExportRangeToFile(range: str, filename: str, imagetype: str = "pdf", overwrite: bool = False): bool

WADQ4‖Parameters:

DpqDV‖range: A sheet name or a cell range to be exported, as a string.

v5QXP‖filename: The name of the file to be saved. It must follow the SF_FileSystem.FileNaming notation.

3nTsB‖imagetype: Identifies the destination file type. Possible values are "jpeg", "pdf" (default) and "png".

Wx3ea‖overwrite: When set to True, the destination file may be overwritten (Default = False).

EFSA4‖Example:

3aa4B‖In Basic

    twaNW‖' Exports the entire sheet as a PDF file
    oDoc.ExportRangeToFile("SheetX", "C:\Temp\image.pdf")
    RRxag‖' Exports the range as a PNG file and overwrites the destination file if it exists
    oDoc.ExportRangeToFile("SheetX.A1:D10", "C:\Temp\image.png", "png", Overwrite := True)
  
BenDd‖In Python

    doc.ExportRangeToFile("SheetX", r"C:\Temp\image.pdf")
    doc.ExportRangeToFile("SheetX.A1:D10", r"C:\Temp\image.png", "png", overwrite = True)
  

Forms

BVKEy‖Depending on the parameters provided this method will return:

FVEx2‖Syntax:

svc.Forms(sheetname: str): str[0..*]

svc.Forms(sheetname: str, form: str = ''): svc

svc.Forms(sheetname: str, form: int): svc

WADQ4‖Parameters:

YdQaD‖sheetname: The name of the sheet, as a string, from which the form will be retrieved.

BV8GH‖form: The name or index corresponding to a form stored in the specified sheet. If this argument is absent, the method will return a list with the names of all forms available in the sheet.

EFSA4‖Example:

sFFyE‖In the following examples, the first line gets the names of all forms stored in "Sheet1" and the second line retrieves the Form object of the form named "Form_A" which is stored in "Sheet1".

3aa4B‖In Basic

    Set FormNames = oDoc.Forms("Sheet1")
    Set FormA = oDoc.Forms("Sheet1", "Form_A")
  
BenDd‖In Python

    form_names = doc.Forms("Sheet1")
    form_A = doc.Forms("Sheet1", "Form_A")
  

GetColumnName

y9kCE‖Converts a column number ranging between 1 and 1024 into its corresponding letter (column 'A', 'B', ..., 'AMJ'). If the given column number is outside the allowed range, a zero-length string is returned.

FVEx2‖Syntax:

svc.GetColumnName(columnnumber: int): str

WADQ4‖Parameters:

xi3Ex‖columnnumber: The column number as an integer value in the interval 1 ... 16384.

EFSA4‖Example:

3aa4B‖In Basic

6yjtp‖Displays a message box with the name of the third column, which by default is "C".


    MsgBox oDoc.GetColumnName(3)
  
BenDd‖In Python

    bas = CreateScriptService("Basic")
    bas.MsgBox(myDoc.GetColumnName(3))
  
note

SyQ5w‖The maximum number of columns allowed on a Calc sheet is 16384.


GetFormula

ksYoG‖Get the formula(s) stored in the given range of cells as a single string, a 1D or a 2D array of strings.

note

P4bPd‖The names of Calc functions used in the returned formulas are expressed in English. Visit the Wiki page List of Calc Functions for a complete list of Calc functions in English.


FVEx2‖Syntax:

svc.GetFormula(range: str): any

WADQ4‖Parameters:

KDFkQ‖range: The range where to get the formulas from, as a string.

EFSA4‖Example:

3aa4B‖In Basic

tBeSN‖The following example returns a 3 by 2 array with the formulas in the range "A1:B3" (3 rows by 2 columns):


    arrFormula = oDoc.GetFormula("~.A1:B3")
  
BenDd‖In Python

    arrFormula = myDoc.GetFormula("~.A1:B3")
  

GetValue

AoHGB‖Get the value(s) stored in the given range of cells as a single value, a 1D array or a 2D array. All values are either doubles or strings.

FVEx2‖Syntax:

svc.GetValue(range: str): any

WADQ4‖Parameters:

XACNZ‖range: The range where to get the values from, as a string.

EFSA4‖Example:

3aa4B‖In Basic

      arrValues = oDoc.GetValue("~.B1:C100")
  
BenDd‖In Python

    arrValues = myDoc.GetValue("~.B1:C100")
  
note

dw2RT‖If a cell contains a date, the number corresponding to that date will be returned. To convert numeric values to dates in Basic scripts, use the Basic CDate builtin function. In Python scripts, use the CDate function from the Basic service.


ImportFromCSVFile

YYMuH‖Imports the contents of a CSV-formatted text file and places it on a given destination cell.

cxrHr‖The destination area is cleared of all contents and formats before inserting the contents of the CSV file. The size of the modified area is fully determined by the contents of the input file.

D2w2A‖The method returns a string representing the modified range of cells.

FVEx2‖Syntax:

svc.ImportFromCSVFile(filename: str, destinationcell: str, [filteroptions: str]): str

WADQ4‖Parameters:

GrquM‖filename: Identifies the file to open. It must follow the SF_FileSystem.FileNaming notation.

VdTtY‖destinationcell: The destination cell to insert the imported data, as a string. If instead a range is given, only its top-left cell is considered.

BrTfu‖filteroptions: The arguments for the CSV input filter. The default filter makes following assumptions:

EFSA4‖Example:

3aa4B‖In Basic

    oDoc.ImportFromCSVFile("C:\Temp\myCSVFile.csv", "SheetY.C5")
  
BenDd‖In Python

    myDoc.ImportFromCSVFile(r"C:\Temp\myCSVFile.csv", "SheetY.C5")
  
tip

AXK5G‖To learn more about the CSV Filter Options, refer to the CSV Filter Options help page.


ImportFromDatabase

vPPYx‖Imports the contents of a database table, query or resultset, i.e. the result of a SELECT SQL command, inserting it on a destination cell.

DorV6‖The destination area is cleared of all contents and formats before inserting the imported contents. The size of the modified area is fully determined by the contents in the table or query.

tfp3o‖The method returns True when the import was successful.

FVEx2‖Syntax:

svc.ImportFromDatabase(filename: str = "", registrationname: str = "", destinationcell: str = "", sqlcommand: str = "", directsql: bool): bool

WADQ4‖Parameters:

rgoAd‖filename: Identifies the file to open. It must follow the SF_FileSystem.FileNaming notation.

j2J5e‖registrationname: The name to use to find the database in the databases register. This argument is ignored if a filename is provided.

2hSHw‖destinationcell: The destination of the imported data, as a string. If a range is given, only its top-left cell is considered.

aMfVw‖sqlcommand: A table or query name (without surrounding quotes or square brackets) or a SELECT SQL statement in which table and field names may be surrounded by square brackets or quotes to improve its readability.

wFpLr‖directsql: When True, the SQL command is sent to the database engine without pre-analysis. Default is False. The argument is ignored for tables. For queries, the applied option is the one set when the query was defined.

EFSA4‖Example:

3aa4B‖In Basic

    oDoc.ImportFromDatabase("C:\Temp\myDbFile.odb", , "SheetY.C5", "SELECT * FROM [Employees] ORDER BY [LastName]")
  
BenDd‖In Python

    myDoc.ImportFromDatabase(r"C:\Temp\myDbFile.odb", , "SheetY.C5", "SELECT * FROM [Employees] ORDER BY [LastName]")
  

ImportStylesFromFile

DAPvU‖This method loads all the styles belonging to one or more style families from a closed file into the actual document. The actual document must be a Calc or a Writer document.

rUCrN‖Are always imported together:

csQsA‖Returns True if styles were successfully imported.

FVEx2‖Syntax:

svc.ImportStylesFromFile(filename: str, families: str[1..*], overwrite = False): bool

WADQ4‖Parameters:

9MPqf‖filename: The file from which to load the styles in the FileSystem notation. The file is presumed to be of the same document type as the actual document.

FfUzE‖families: One of the style families present in the actual document, as a case-sensitive string or an array of such strings. Leave this argument blank to import all families.

yZYQv‖overwrite: When True, the actual styles may be overwritten. Default is False.

EFSA4‖Example:

3aa4B‖In Basic

    oDoc.ImportStylesFromFile("C:\User\Documents\myFile.ods", "ParagraphStyles", True)
  
BenDd‖In Python

    doc.ImportStylesFromFile('C:\User\Documents\myFile.ods', ("ParagraphStyles",), False)
  

InsertSheet

toj8z‖Inserts a new empty sheet before an existing sheet or at the end of the list of sheets.

FVEx2‖Syntax:

svc.InsertSheet(sheetname: str, [beforesheet: any]): bool

WADQ4‖Parameters:

Xbm7k‖sheetname: The name of the new sheet.

XbXNM‖beforesheet: The name (string) or index (numeric, starting from 1) of the sheet before which to insert the new sheet. This argument is optional and the default behavior is to insert the sheet at the last position.

EFSA4‖Example:

UCmit‖The following example inserts a new empty sheet named "SheetX" and places it before "SheetY":

3aa4B‖In Basic

    oDoc.InsertSheet("SheetX", "SheetY")
  
BenDd‖In Python

    myDoc.InsertSheet("SheetX", "SheetY")
  

MoveRange

DcrWC‖Moves a specified source range to a destination range of cells. The method returns a string representing the modified range of cells. The dimension of the modified area is fully determined by the size of the source area.

FVEx2‖Syntax:

svc.MoveRange(source: str, destination: str): str

WADQ4‖Parameters:

UqxZv‖source: The source range of cells, as a string.

G6BSW‖destination: The destination cell, as a string. If a range is given, its top-left cell is considered as the destination.

EFSA4‖Example:

3aa4B‖In Basic

    oDoc.MoveRange("SheetX.A1:F10", "SheetY.C5")
  
BenDd‖In Python

    myDoc.MoveRange("SheetX.A1:F10", "SheetY.C5")
  

MoveSheet

NorEd‖Moves an existing sheet and places it before a specified sheet or at the end of the list of sheets.

FVEx2‖Syntax:

svc.MoveSheet(sheetname: str, [beforesheet: any]): bool

WADQ4‖Parameters:

dgAxB‖sheetname: The name of the sheet to move. The sheet must exist or an exception is raised.

fevuS‖beforesheet: The name (string) or index (numeric, starting from 1) of the sheet before which the original sheet will be placed. This argument is optional and the default behavior is to move the sheet to the last position.

EFSA4‖Example:

pd5t4‖The example below moves the existing sheet "SheetX" and places it before "SheetY":

3aa4B‖In Basic

    oDoc.MoveSheet("SheetX", "SheetY")
  
BenDd‖In Python

    myDoc.MoveSheet("SheetX", "SheetY")
  

Offset

Q9iwN‖Returns a new range (as a string) offset by a certain number of rows and columns from a given range.

AgdZe‖This method has the same behavior as the homonymous Calc's Offset function.

FVEx2‖Syntax:

svc.Offset(reference: str, rows: int = 0, columns: int = 0, [height: int], [width: int]): str

WADQ4‖Parameters:

G2oD2‖reference: The range, as a string, that the method will use as reference to perform the offset operation.

Ra7aW‖rows: The number of rows by which the initial range is offset upwards (negative value) or downwards (positive value). Use 0 (default) to stay in the same row.

FvqjV‖columns: The number of columns by which the initial range is offset to the left (negative value) or to the right (positive value). Use 0 (default) to stay in the same column.

VzgGM‖height: The vertical height for an area that starts at the new range position. Omit this argument when no vertical resizing is needed.

JxENN‖width: The horizontal width for an area that starts at the new range position. Omit this argument when no horizontal resizing is needed.

t9QDN‖Arguments rows and columns must not lead to zero or negative start row or column.

JAxEm‖Arguments height and width must not lead to zero or negative count of rows or columns.

EFSA4‖Example:

3aa4B‖In Basic

    oDoc.Offset("A1", 2, 2)
    BkCDz‖'SheetX.$C$3 (A1 moved by two rows and two columns down)
    oDoc.Offset("A1", 2, 2, 5, 6)
    8ukCQ‖'SheetX.$C$3:$H$7 (A1 offset by two rows and columns with width of 5 rows and 6 columns)
  
BenDd‖In Python

    myDoc.Offset("A1", 2, 2)
    myDoc.Offset("A1", 2, 2, 5, 6)
  

OpenRangeSelector

GwPQh‖Opens a non-modal dialog that can be used to select a range in the document and returns a string containing the selected range.

note

CWn2A‖This method opens the same dialog that is used by LibreOfficeDev when the Shrink button is pressed. For example, the Tools - Goal Seek dialog has a Shrink button to the right of the Formula cell field.


XUoah‖This method does not change the current selection.

FVEx2‖Syntax:

svc.OpenRangeSelector(opt title: str, opt selection: str, singlecell: bool = False, closeafterselect: bool = True): str

WADQ4‖Parameters:

tAHiV‖title: The title of the dialog, as a string.

Yyn74‖selection: An optional range that is initially selected when the dialog is displayed.

zo7VK‖singlecell: When True (default) only single-cell selection is allowed. When False range selection is allowed.

SqEWv‖closeafterselect: When True (default) the dialog is closed immediately after the selection is made. When False the user can change the selection as many times as needed and then manually close the dialog.

EFSA4‖Example:

3aa4B‖In Basic

    Dim sRange as String
    sRange = oDoc.OpenRangeSelector(Title := "Select a range")
  
BenDd‖In Python

    sRange = myDoc.OpenRangeSelector(title = "Select a range")
  

Printf

yDiCm‖Returns the input string after substituting its token characters by their values in a given range.

Qu4DK‖This method does not change the current selection.

tip

eEqCY‖This method can be used to quickly extract specific parts of a range name, such as the sheet name or first cell column and row, and use them to compose a new range address.


FVEx2‖Syntax:

svc.Printf(inputstr: str, range: str, tokencharacter: str = "%"): str

WADQ4‖Parameters:

RAAVz‖inputstr: The string containing the tokens that will be replaced by the corresponding values in range.

NJdUy‖range: A RangeName from which values will be extracted. If it contains a sheet name, the sheet must exist.

BgCCD‖tokencharacter: Character used to identify tokens. By default "%" is the token character. The following tokens are accepted:

EFSA4‖Example:

3aa4B‖In Basic

gpmpG‖The example below extracts each element of the RangeName defined in sRange and uses them to compose a message.


    Dim sRange as String, sInputStr as String
    sRange = "Sheet1.A1:E10"
    sInputStr = "Sheet name: %S" & Chr(10) & _
                "First row: %R1" & Chr(10) & _
                "First column %C1" & Chr(10) & _
                "Last row %R2" & Chr(10) & _
                "Last column %C2"
    MsgBox oDoc.Printf(sInputStr, sRange)
  

nbJ59‖The Printf method can be combined with SetFormula to create formulas over multiple cells. For instance, consider a table with numeric values in the range "A1:E10" from which formulas are to be created to sum the values in each row and place the results in the range "F1:F10":


    Dim sFormula as String, sRange as String
    sRange = "A1:E10"
    foAvd‖' Note the use of the "$" character
    sFormula = "=SUM($%C1%R1:$%C2%R1)"
    oDoc.SetFormula("F1:F10", oDoc.Printf(sFormula, sRange))
  
BenDd‖In Python

    sRange = "Sheet1.A1:E10"
    sInputStr = "Sheet name: %S\n" \
                "First row: %R1\n" \
                "First column %C1\n" \
                "Last row %R2\n" \
                "Last column %C2"
    bas = CreateScriptService("Basic")
    bas.MsgBox(myDoc.Printf(sInputStr, sRange))
  

    sRange = "A1:E10
    sFormula = "=SUM($%C1%R1:$%C2%R1)"
    myDoc.SetFormula("F1:F10", myDoc.Printf(sFormula, sRange))
  

PrintOut

wBpRw‖This method sends the contents of the given sheet to the default printer or to the printer defined by the SetPrinter method of the Document service.

BaDL9‖Returns True if the sheet was successfully printed.

FVEx2‖Syntax:

svc.PrintOut(opt sheetname: str, pages: str = "", copies: num = 1): bool

WADQ4‖Parameters:

CnNEC‖sheetname: The sheet to print, default is the active sheet.

xk3k3‖pages: The pages to print as a string, like in the user interface. Example: "1-4;10;15-18". Default is all pages.

DBFDA‖copies: The number of copies. Default is 1.

EFSA4‖Example:

3aa4B‖In Basic

    If oDoc.PrintOut("SheetX", "1-4;10;15-18", Copies := 2) Then
        ' ...
    End If
  
BenDd‖In Python

    if doc.PrintOut('SheetX', copies=3, pages='45-88'):
        # ...
  

RemoveDuplicates

64f3B‖Removes duplicate rows from a specified range. The comparison to determine if a given row is a duplicate is done based on a subset of columns in the range.

2Fj4F‖This method returns a string containing the resulting range.

note

py5XZ‖The removal of duplicate rows is done starting at the first row in the range moving downwards, meaning that if two or more rows are duplicates then only the first one is kept.


FVEx2‖Syntax:

svc.RemoveDuplicates(range: str, opt columns: int[0..*], header: bool = False, casesensitive: bool = False, mode: str = "COMPACT"): str

WADQ4‖Parameters:

UxCsB‖range: The range from which duplicates will be removed, as a string.

WBeEc‖columns: An array containing column numbers indicating which columns will be considered to determine if a row is a duplicate or not. If this argument is left blank, then only the first column is used. Items in this array must be in the interval between 1 and the range width.

C4DUZ‖header: Specifies whether the first row is a header row (Default = False).

sFJ5x‖casesensitive: Specifies whether string comparisons are case-sensitive (Default = False).

zhBuK‖mode: Specifies what to do with duplicate rows. If mode = "CLEAR" then duplicates are simply removed from the sheet leaving the cells blank. If mode = "COMPACT" then duplicates are removed and empty rows are compacted up (Default = "COMPACT").

EFSA4‖Example:

3aa4B‖In Basic

    CvYHu‖' Removes duplicate rows where values in column A are duplicate
    wMXKK‖' Note that all optional arguments use their default value
    oDoc.RemoveDuplicates("A1:B10")
    Dzbis‖' Removes duplicate rows considering that the first row contains headers
    H5o2W‖' Columns A and B are used to determine if a row is a duplicate
    vgiBA‖' Cells containing duplicate values are left blank
    oDoc.RemoveDuplicates("A1:D10", columns := Array(1, 2), header := True, mode := "CLEAR")
  
BenDd‖In Python

    myDoc.RemoveDuplicates("A1:B10")
    myDoc.RemoveDuplicates("A1:D10", columns = (1, 2), header = True, mode = "CLEAR")
  

RemoveSheet

C8abL‖Removes an existing sheet from the document.

FVEx2‖Syntax:

svc.RemoveSheet(sheetname: str): bool

WADQ4‖Parameters:

dVxiA‖sheetname: The name of the sheet to remove.

EFSA4‖Example:

3aa4B‖In Basic

    oDoc.RemoveSheet("SheetY")
  
BenDd‖In Python

    myDoc.RemoveSheet("SheetY")
  

RenameSheet

GwKHr‖Renames the given sheet and returns True if successful.

FVEx2‖Syntax:

svc.RenameSheet(sheetname: str, newname: str): bool

WADQ4‖Parameters:

ofAiN‖sheetname: The name of the sheet to rename.

JHEDe‖newname: the new name of the sheet. It must not exist yet.

EFSA4‖Example:

bwtAA‖This example renames the active sheet to "SheetY":

3aa4B‖In Basic

    oDoc.RenameSheet("~", "SheetY")
  
BenDd‖In Python

    mydoc.RenameSheet("~", "SheetY")
  

SetArray

qEM6N‖Stores the given value starting from a specified target cell. The updated area expands itself from the target cell or from the top-left corner of the given range to accommodate the size of the input value argument. Vectors are always expanded vertically.

tm6AR‖The method returns a string representing the modified area as a range of cells.

FVEx2‖Syntax:

svc.SetArray(targetcell: str, value: any): str

WADQ4‖Parameters:

FAuKq‖targetcell: The cell or a range as a string from where to start to store the given value.

aK7EZ‖value: A scalar, a vector or an array (in Python, one or two-dimensional lists and tuples) with the new values to be stored from the target cell or from the top-left corner of the range if targetcell is a range. The new values must be strings, numeric values or dates. Other types will cause the corresponding cells to be emptied.

EFSA4‖Example:

3aa4B‖In Basic

eAuMT‖The following example uses the builtin DimArray function to create an array and then store it in cell "A1":


    Dim arrData as Variant
    arrData = DimArray(2, 1)
    arrData(0, 0) = 1 : arrData(1, 0) = 2 : arrData(2, 0) = 3
    arrData(0, 1) = "One" : arrData(1, 1) = "Two" : arrData(2, 1) = "Three"
    oDoc.SetArray("Sheet1.A1", arrData)
  

AheUb‖This example uses the RangeInit method of the ScriptForge Array service to create an array with values that are then stored from cell "A1" and downwards.


    kmatN‖'Fill 1st column with values from 1 to 1000
    oDoc.SetArray("Sheet1.A1", SF_Array.RangeInit(1, 1000))
  
BenDd‖In Python

    arrData = ((1, "One"), (2, "Two"), (3, "Three"))
    myDoc.SetArray("Sheet1.A1", arrData)
  

    myDoc.SetArray("Sheet1.A1", tuple(i + 1 for i in range(1000)))
  
tip

YNGtV‖To dump the full contents of an array in a sheet, use SetArray. To dump the contents of an array only within the boundaries of the targeted range of cells, use SetValue.


SetCellStyle

g8mER‖Applies the specified cell style to the given target range. The full range is updated and the remainder of the sheet is left untouched. If the cell style does not exist, an error is raised.

nxDCd‖The method returns a string representing the modified area as a range of cells.

FVEx2‖Syntax:

svc.SetCellStyle(targetrange: str, style: str, opt filterformula: str, opt filterscope: str): str

WADQ4‖Parameters:

FtFpL‖targetrange: The range to which the style will be applied, as a string.

aAGcy‖style: The name of the cell style to apply.

Bq7qT‖filterformula: A Calc formula that shall be applied to the given range to determine which cells will be affected. The specified formula must return True or False. If this argument is not specified, then all cells in the range are affected.

Lvzwc‖filterscope: Determines how filterformula is expanded to the given range. This argument is mandatory if a filterformula is specified. The following values are accepted:

EFSA4‖Example:

3aa4B‖In Basic

    oDoc.SetCellStyle("A1:J1", "Heading 1")
    oDoc.SetCellStyle("A2:J100", "Neutral")
  
BenDd‖In Python

    myDoc.SetCellStyle("A1:J1", "Heading 1")
    myDoc.SetCellStyle("A2:J100", "Neutral")
  
tip

oU8ui‖Refer to the ClearAll method documentation for examples on how to use the arguments filterformula and filterscope.


SetFormula

DCAWV‖Inserts the given (array of) formula(s) in the specified range. The size of the modified area is equal to the size of the range.

d8CAU‖The method returns a string representing the modified area as a range of cells.

FVEx2‖Syntax:

svc.SetFormula(targetrange: str, formula: any): str

WADQ4‖Parameters:

F5XDi‖targetrange: The range to insert the formulas, as a string.

A2UQF‖formula: A string, a vector or an array of strings with the new formulas for each cell in the target range.

746E8‖The full range is updated and the remainder of the sheet is left unchanged.

Wot7x‖If the given formula is a string, the unique formula is pasted along the whole range with adjustment of the relative references.

zr47n‖If the size of formula is smaller than the size of targetrange, then the remaining cells are emptied.

LwoGL‖If the size of formula is larger than the size of targetrange, then the formulas are only partially copied until it fills the size of targetrange.

GQC3N‖Vectors are always expanded vertically, except if targetrange has a height of exactly 1 row.

note

9csnd‖Calc functions used in the formula argument must be expressed using their English names. Visit the Wiki page List of Calc Functions for a complete list of Calc functions in English.


EFSA4‖Example:

3aa4B‖In Basic

    oDoc.SetFormula("A1", "=A2")
    rNEEY‖'Horizontal vector, partially empty
    oDoc.SetFormula("A1:F1", Array("=A2", "=B2", "=C2+10"))
    52GZX‖'D2 contains the formula "=H2"
    oDoc.SetFormula("A1:D2", "=E1")
  
BenDd‖In Python

    myDoc.SetFormula("A1", "=A2")
    myDoc.SetFormula("A1:F1", ("=A2", "=B2", "=C2+10"))
    myDoc.SetFormula("A1:D2", "=E1")
  

SetValue

ecovS‖Stores the given value in the specified range. The size of the modified area is equal to the size of the target range.

PeoKo‖The method returns a string representing the modified area as a range of cells.

FVEx2‖Syntax:

svc.SetValue(targetrange: str, value: any): str

WADQ4‖Parameters:

xYrHQ‖targetrange: The range where to store the given value, as a string.

dydXF‖value: A scalar, a vector or an array with the new values for each cell of the range. The new values must be strings, numeric values or dates. Other types will cause the corresponding cells to be emptied.

CgwVF‖The full range is updated and the remainder of the sheet is left unchanged. If the size of value is smaller than the size of targetrange, then the remaining cells will be emptied.

QFkLr‖If the size of value is larger than the size of targetrange, then value is only partially copied until it fills the size of targetrange.

ykBk6‖Vectors are expanded vertically, except if targetrange has a height of exactly 1 row.

EFSA4‖Example:

3aa4B‖In Basic

    oDoc.SetValue("A1", 2)
    FJCPf‖'Below the Value array is smaller than the TargetRange (remaining cells are emptied)
    oDoc.SetValue("A1:F1", Array(1, 2, 3))
    vuu9B‖'Below the Value and TargetRange have the same size
    oDoc.SetValue("A1:D2", SF_Array.AppendRow(Array(1, 2, 3, 4), Array(5, 6, 7, 8)))
  

4LFnH‖If you want to fill a single row with values, you can use the Offset function. In the example below, consider that arrData is a one-dimensional array:


    Dim firstCell As String : firstCell = "A1"
    Dim lenArray As Integer : lenArray = UBound(arrData) - LBound(arrData) + 1
    Dim newRange As String : newRange = oDoc.Offset(firstCell, width = lenArray)
    oDoc.SetValue(newRange, arrData)
  
BenDd‖In Python

    myDoc.SetValue("A1", 2)
    myDoc.SetValue("A1:F1", (1, 2, 3))
    myDoc.SetValue("A1:D2", ((1, 2, 3, 4), (5, 6, 7, 8)))
  

    firstCell = "A1"
    newRange = doc.Offset(firstCell, width = len(arrData))
    doc.SetValue(newRange, arrData)
  

ShiftDown

gF7Gb‖Moves a given range of cells downwards by inserting empty rows. The current selection is not affected.

5qm5w‖Depending on the value of the wholerow argument the inserted rows can either span the width of the specified range or span all columns in the row.

uvH4j‖This method returns a string representing the new location of the initial range.

note

cvqws‖If the shifted range exceeds the sheet edges, then nothing happens.


FVEx2‖Syntax:

svc.ShiftDown(range: str, wholerow: bool = False, opt rows: int): str

WADQ4‖Parameters:

bUdZp‖range: The range above which rows will be inserted, as a string.

fVYpB‖wholerow: If set to False (default), then the width of the inserted rows will be the same as the width of the specified range. Otherwise, the inserted row will span all columns in the sheet.

rXzZX‖rows: The number of rows to be inserted. The default value is the height of the original range. The number of rows must be a positive number.

EFSA4‖Example:

3aa4B‖In Basic

    dacHK‖' Moves the range "A3:D3" down by one row; affects only columns A to D
    oDoc.ShiftDown("A3:D3")
    v4w3P‖' The inserted row spans all columns in the sheet
    oDoc.ShiftDown("A3:D3", WholeRow := True)
    vsryg‖' Moves the range "A3:D3" down by five rows
    oDoc.ShiftDown("A3:D3", Rows := 5)
    pwuUG‖' Moves the range "A3:D10" down by two rows and shows the new location of the original range
    Dim sNewRange as String
    sNewRange = oDoc.ShiftDown("A3:D10", Rows := 2)
    MsgBox sNewRange   ' $Sheet1.$A$5:$D$12
  
BenDd‖In Python

    myDoc.ShiftDown("A3:D3")
    myDoc.ShiftDown("A3:D3", wholerow = True)
    myDoc.ShiftDown("A3:D3", rows = 5)
    sNewRange = myDoc.ShiftDown("A3:D10", rows = 2)
    bas = CreateScriptService("Basic")
    bas.MsgBox(sNewRange)
  

ShiftLeft

hVfv3‖Deletes the leftmost columns of a given range and moves to the left all cells to the right of the affected range. The current selection is not affected.

EzzWo‖Depending on the value of the wholecolumn argument the deleted columns can either span the height of the specified range or span all rows in the column.

BXEkG‖This method returns a string representing the location of the remaining portion of the initial range. If all cells in the original range have been deleted, then an empty string is returned.

FVEx2‖Syntax:

svc.ShiftLeft(range: str, wholecolumn: bool = False, opt columns: int): str

WADQ4‖Parameters:

CyRpL‖range: The range from which cells will be deleted, as a string.

zWG3Y‖wholecolumn: If set to False (default), then the height of the deleted columns will be the same as the height of the specified range. Otherwise, the deleted columns will span all rows in the sheet.

JLdBr‖columns: The number of columns to be deleted from the specified range. The default value is the width of the original range, which is also the maximum value of this argument.

EFSA4‖Example:

3aa4B‖In Basic

    8UycD‖' Deletes the range "B3:B6"; moves left all cells to the right
    oDoc.ShiftLeft("B3:B6")
    vM8hB‖' Deletes the first column in the range "A3:D6"
    oDoc.ShiftLeft("A3:D6", Columns := 1)
    FPVSg‖' The deleted columns (A to D) spans all rows in the sheet
    oDoc.ShiftLeft("A3:D6", WholeColumn := True)
  
BenDd‖In Python

    myDoc.ShiftLeft("B3:B6")
    myDoc.ShiftLeft("A3:D6", Columns = 1)
    myDoc.ShiftLeft("A3:D6", WholeColumn = True)
  

ShiftUp

TAB2b‖Deletes the topmost rows of a given range and moves upwards all cells below the affected range. The current selection is not affected.

zkYo7‖Depending on the value of the wholerow argument the deleted rows can either span the width of the specified range or span all columns in the row.

s9Nfb‖This method returns a string representing the location of the remaining portion of the initial range. If all cells in the original range have been deleted, then an empty string is returned.

FVEx2‖Syntax:

svc.ShiftUp(range: str, wholerow: bool = False, opt rows: int): str

WADQ4‖Parameters:

H5EtV‖range: The range from which cells will be deleted, as a string.

JQtGb‖wholerow: If set to False (default), then the width of the deleted rows will be the same as the width of the specified range. Otherwise, the deleted row will span all columns in the sheet.

ueo8E‖rows: The number of rows to be deleted from the specified range. The default value is the height of the original range, which is also the maximum value of this argument.

EFSA4‖Example:

3aa4B‖In Basic

    jHP9x‖' Deletes the range "A3:D3"; moves all cells below it by one row up
    oDoc.ShiftUp("A3:D3")
    Make5‖' Deletes the first row in the range "A3:D6"
    oDoc.ShiftUp("A3:D6", Rows := 1)
    APQKA‖' The deleted rows spans all columns in the sheet
    oDoc.ShiftUp("A3:D6", WholeRow := True)
  
BenDd‖In Python

    myDoc.ShiftUp("A3:D3")
    myDoc.ShiftUp("A3:D6", rows = 1)
    myDoc.ShiftUp("A3:D6", wholerow = True)
  

ShiftRight

gKkbB‖Moves a given range of cells to the right by inserting empty columns. The current selection is not affected.

CDi3E‖Depending on the value of the wholecolumn argument the inserted columns can either span the height of the specified range or span all rows in the column.

Fh33o‖This method returns a string representing the new location of the initial range.

note

pLAHD‖If the shifted range exceeds the sheet edges, then nothing happens.


FVEx2‖Syntax:

svc.ShiftRight(range: str, wholecolumn: bool = False, opt columns: int): str

WADQ4‖Parameters:

SeAGD‖range: The range which will have empty columns inserted to its left, as a string.

KtD6Y‖wholecolumn: If set to False (default), then the height of the inserted columns will be the same as the height of the specified range. Otherwise, the inserted columns will span all rows in the sheet.

fBzCG‖columns: The number of columns to be inserted. The default value is the width of the original range.

EFSA4‖Example:

3aa4B‖In Basic

    nmXTU‖' Moves the range "A3:A6" right by one column; affects only rows 3 to 6
    oDoc.ShiftRight("A3:A6")
    5mWBq‖' Moves the range "A3:A6" right by five columns
    oDoc.ShiftRight("A3:A6", Columns := 5)
    G53xT‖' The inserted column spans all rows in the sheet
    oDoc.ShiftRight("A3:A6", WholeColumn := True)
  
BenDd‖In Python

    myDoc.ShiftRight("A3:A6")
    myDoc.ShiftRight("A3:A6", columns = 5)
    myDoc.ShiftRight("A3:A6", wholecolumn = True)
  

SortRange

D4fh3‖Sort the given range on any number of columns/rows. The sorting order may vary by column/row. If the number of sort keys is > 3 then the range is sorted several times, by groups of 3 keys, starting from the last key. It returns a string representing the modified range of cells. The size of the modified area is fully determined by the size of the source area.

FVEx2‖Syntax:

svc.SortRange(range: str, sortkeys: any, sortorder: any = "ASC", destinationcell: str = "", containsheader: bool = False, casesensitive: bool = False, sortcolumns: bool = False): str

WADQ4‖Parameters:

MVGBC‖range: The range to be sorted, as a string.

pDQbJ‖sortkeys: A scalar (if 1 column/row) or an array of column/row numbers starting from 1.

k5CZ4‖sortorder: A scalar or an array of strings containing the values "ASC" (ascending), "DESC" (descending). Each item is paired with the corresponding item in sortkeys. If the sortorder array is shorter than sortkeys, the remaining keys are sorted in ascending order.

GVpuf‖destinationcell: The destination cell of the sorted range of cells, as a string. If a range is given, only its top-left cell is considered. By default the source Range is overwritten.

QyaTf‖containsheader: When True, the first row/column is not sorted.

AbVtY‖casesensitive: Only for string comparisons. Default = False

CL5Gm‖sortcolumns: When True, the columns are sorted from left to right. Default = False : rows are sorted from top to bottom.

EFSA4‖Example:

3aa4B‖In Basic

    LvjpD‖'Sort range based on columns A (ascending) and C (descending)
    oDoc.SortRange("A2:J200", Array(1, 3), Array("ASC", "DESC"), CaseSensitive := True)
  
BenDd‖In Python

    myDoc.SortRange("A2:J200", (1, 3), ("ASC", "DESC"), casesensitive = True)
  
warning

uzETY‖All ScriptForge Basic routines or identifiers that are prefixed with an underscore character "_" are reserved for internal use. They are not meant be used in Basic macros or Python scripts.