Servizio SFDocuments.Calc

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

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.

The Calc service is focused on:

note

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


Invocare il servizio

Il servizio Calc è strettamente collegato al servizio UI della libreria ScriptForge. Di seguito sono riportati alcuni esempi di come il servizio Calc può essere invocato.

In Basic

Il frammento di codice sottostante crea l'istanza a un servizio Calc che corrisponde al documento di Calc attualmente attivo.


    Set oDoc = CreateScriptService("Calc")
  

Un altro modo di creare un'istanza del servizio Calc è quello di usare il servizio UI. Nell'esempio seguente viene creato un nuovo documento di Calc e oDoc è un'istanza del servizio Calc:


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

Oppure usando il metodo OpenDocument del servizio UI:


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

È anche possibile istanziare il servizio Calc usando il metodo CreateScriptService:


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

Nell'esempio sopra riportato, "MyFile.ods" è il nome di una finestra di apertura di un documento. Se l'argomento non è fornito, viene considerata la finestra attiva.

Si raccomanda di liberare le risorse dopo l'uso:


    Set oDoc = oDoc.Dispose()
  

In ogni caso, se il documento è stato chiuso usando il metodo CloseDocument, non si rende più necessario liberare le risorse usando il comando descritto sopra.

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()
  
tip

L'uso del prefisso "SFDocuments." nella chiamata al servizio è opzionale.


Definizioni

Molti metodi richiedono un "Foglio" o un "Area di celle" come argomento. Le celle singole sono considerate come un caso speciale di Area di celle.

Entrambi possono essere espressi sia come stringa o come riferimento (= oggetto) a seconda della situazione:

Esempio:

L'esempio sottostante copia dati dal documento A (aperto in sola lettura e nascosto) al documento B.

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)
  
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

Sia il nome del foglio come stringa o un oggetto creato dalla proprietà .Sheet.

La scorciatoia "~" (tilde) rappresenta il foglio corrente.

RangeName

Sia una stringa che individua un insieme di celle contigue posizionate in un foglio dell'istanza corrente o un oggetto creato dalla proprietà .Range.

La scorciatoia "~" (tilde) rappresenta la selezione corrente o la prima area di celle selezionata, quando sono selezionate più aree.

La scorciatoia "*" rappresenta tutte le celle usate.

Il nome del foglio è opzionale per un'area (predefinito = il foglio attivo). Il suo inserimento tra virgolette singole e l'uso del simbolo $ sono permessi, ma vengono ignorati.

tip

Ad eccezione della proprietà CurrentSelection, il servizio Calc considera solamente singole aree di celle.


Esempio di aree valide

1) '$FoglioX'.D2
2) $D$2

Una cella singola

1) '$FoglioX'.D2:F6
2) D2:D10

Una singola area con più celle

'$FoglioX'.*

Tutte le celle usate del foglio specificato

1) '$FoglioX'.A:A (colonna A)
2) 3:5 (righe da 3 a 5)

Tutte le celle di colonne o righe contigue fino all'ultima cella usata

miaArea

Un'area denominata "miaArea" a livello di foglio di calcolo

1) ~.unArea
2) FoglioX.unArea

Un nome di area a livello di foglio

myDoc.Range("FoglioX.D2:F6")

Un'area all'interno del foglio FoglioX nel file associato all'istanza myDoc di Calc

~.~ o ~

La selezione corrente nel foglio attivo


Proprietà

Tutte le proprietà generiche di ogni documento sono implicitamente applicabili anche ai documenti di Calc. Per maggiori informazioni, leggete la pagina dell'Aiuto in linea del servizio Document.

Le proprietà sono applicabili specificatamente ai documenti di Calc sono:

Nome

Sola lettura

Argomento

Return type

Descrizione

CurrentSelection

No

Nessuno

Stringa o matrice di stringhe

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

FirstCell

Yes

SheetName or RangeName as String

String

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

FirstColumn

Yes

SheetName or RangeName as String

Long

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

FirstRow

Yes

SheetName or RangeName as String

Long

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

Height

NomeArea come Stringa

Long

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

LastCell

SheetName or RangeName as String

String

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

LastColumn

SheetName or RangeName as String

Long

The last used column in a given range or sheet.

LastRow

SheetName or RangeName as String

Long

The last used row in a given range or sheet.

Range

NomeArea come Stringa

Object

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

Region

Yes

RangeName As String

String

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

NomeFoglio come stringa

Object

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

Sheets

Nessuno

Matrice di stringhe

The list with the names of all existing sheets.

Width

NomeArea come Stringa

Long

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

XCellRange

NomeArea come Stringa

Object

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

XSheetCellCursor

Yes

RangeName As String

Object

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

NomeFoglio come stringa

Object

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


tip

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


Metodi

Elenco dei metodi del servizio Calc

A1Style
Activate
Charts
ClearAll
ClearFormats
ClearValues
CopySheet
CopySheetFromFile
CopyToCell
CopyToRange
CreateChart
DAvg
DCount
DMax

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

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


A1Style

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

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.

Sintassi:

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

Parametri:

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.

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.

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.

Esempio:

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

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
  
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

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

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.

Sintassi:

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

Parametri:

sheetname: il nome del foglio da attivare nel documento. Il valore predefinito è una stringa vuota, ciò significa che verrà attivata la finestra del documento senza cambiare il foglio attivo.

Esempio:

L'esempio seguente attiva il foglio denominato "Foglio4" nel documento attualmente attivo.

In Basic

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

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

L'attivazione di un foglio ha senso solo se eseguita su di un documento di Calc. Per assicurarvi di avere a che fare con un documento di Calc potete a usare la proprietà isCalc dell'oggetto document, che restituisce True se il documento è di Calc e False in caso contrario.


Charts

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

Sintassi:

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

Parametri:

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

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

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


Esempio:

In Basic

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"
  

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
  
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

Vuota tutti i contenuti e i formati dell'area specificata.

Sintassi:

svc.ClearAll(range: str)

Parametri:

range: l'area da vuotare, in formato stringa.

Esempio:

In Basic

      oDoc.ClearAll("SheetX.A1:F10")
  
In Python

    myDoc.ClearAll("SheetX.A1:F10")
  

ClearFormats

Vuota tutti i formati e gli stili dell'area specificata.

Sintassi:

svc.ClearFormats(range: str)

Parametri:

range: l'area i cui formati e stili devono essere vuotati, in formato stringa.

Esempio:

In Basic

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

    myDoc.ClearFormats("SheetX.*")
  

ClearValues

Vuota i valori e le formule nell'area specificata.

Sintassi:

svc.ClearValues(range: str)

Parametri:

range: l'area i cui valori e formule devono essere vuotati, in formato stringa.

Esempio:

In Basic

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

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

CopySheet

Copia il foglio specificato prima di un foglio esistente o alla fine dell'elenco dei fogli. Il foglio da copiare può essere contenuto in qualsiasi documento aperto di Calc. Restituisce True se l'operazione viene eseguita correttamente.

Sintassi:

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

Parametri:

sheetname: il nome del foglio da copiare in formato stringa o il suo riferimento come oggetto.

newname: il nome del foglio da inserire. Il nome non deve essere già in uso nel documento.

beforesheet: il nome (stringa) o l'indice (numerico, a partire da 1) del foglio prima del quale inserire il foglio copiato. Questo argomento è opzionale e il comportamento predefinito è quello di aggiungere il foglio nell'ultima posizione.

Esempio:

In Basic

L'esempio seguente crea una copia del foglio "FoglioX" e la posiziona come ultimo foglio del documento corrente. Il nome del foglio risultante dalla copia è "FoglioY".


    Dim oDoc as Object
    'Ottiene l'oggetto Document della finestra attiva
    Set oDoc = CreateScriptService("Calc")
    oDoc.CopySheet("SheetX", "SheetY")
  

L'esempio seguente copia "FoglioX" dal file "FileA.ods" e lo incolla nell'ultima posizione del file "FileB.ods" con il nome "FoglioY":


      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")
  
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

Per copiare fogli tra documenti aperti, usate CopySheet. Per copiare fogli da documenti che sono chiusi, usate CopySheetFromFile.


CopySheetFromFile

Copia il foglio specificato da un documento chiuso di Calc e lo incolla prima di un foglio esistente o alla fine dell'elenco dei fogli del file a cui fa riferimento l'oggetto Document.

Se il file non esiste, viene sollevato un errore. Se il file non è un file di Calc valido, viene inserito un foglio vuoto. Se il foglio da copiare non esiste nel file di partenza, viene inserito un messaggio di errore in cima al nuovo foglio appena incollato.

Sintassi:

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

Parametri:

filename: identifica il file da aprire. Deve seguire la notazione SF_FileSystem.FileNaming. Il file non deve essere protetto da una password.

sheetname: il nome del foglio da copiare in formato stringa.

newname: il nome del foglio copiato da inserire nel documento. Il nome non deve essere già in uso nel documento.

beforesheet: Il nome (stringa) o l'indice (numerico, a partire da 1) del foglio prima del quale inserire il foglio copiato. Questo argomento è opzionale e il comportamento predefinito è quello di aggiungere il foglio nell'ultima posizione.

Esempio:

L'esempio seguente copia "FoglioX" dal file "mioFile.ods" e lo incolla come "FoglioY" in prima posizione nel documento a cui fa riferimento "oDoc".

In Basic

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

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

CopyToCell

Copia l'area di celle specificata (valori, formule e formati) in un'area o una cella di destinazione. Il metodo riproduce il comportamento dell'operazione di Copia/Incolla da un'area a una singola cella.

Restituisce una stringa che rappresenta l'area di celle modificate. Le dimensioni dell'area modificata sono determinate completamente dalle dimensioni dell'area di partenza.

L'area di partenza può appartenere a un altro documento aperto.

Sintassi:

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

Parametri:

sourcerange: l'area di partenza in formato stringa se appartiene allo stesso documento, o come riferimento se appartiene a un altro documento aperto di Calc.

destinationcell: la cella di destinazione nella quale sarà incollata l'area di celle copiate, in formato stringa. Se è specificata un'area, verrà considerata solo la sua prima cella in alto a sinistra.

Esempio:

In Basic

Qui di seguito un esempio in cui sorgente e destinazione sono nello stesso file:


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

L'esempio sottostante illustra come copiare un'area da un altro documento aperto di Calc:


    Dim ui as Variant : ui = CreateScriptService("UI")
    Dim oDocSource As Object, oDocDestination As Object
    'Apre il documento sorgente in background (nascosto)
    Set oDocSource = ui.OpenDocument("C:\SourceFile.ods", Hidden := True, ReadOnly := True)
    Set oDocDestination = CreateScriptService("Calc")
    oDocDestination.CopyToCell(oDocSource.Range("Sheet1.C2:C4"), "SheetT.A5")
    'Non dimenticate di chiudere il documento sorgente, dato che è stato aperto come nascosto
    oDocSource.CloseDocument()
  
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

Per simulare il Copia/Incolla da un'area a una singola cella, usate CopyToCell. Per simulare il Copia/Incolla da un'area a un'area più ampia (con le stesse celle ripetute più volte), usate CopyToRange.


CopyToRange

Copia verso il basso e/o verso destra un'area specificata (valori, formule e formati) in un'area di destinazione. Il metodo imita il comportamento di un'operazione di Copia/Incolla da un'area di partenza a un'area di destinazione più ampia.

Il metodo restituisce una stringa che rappresenta l'area di celle modificata.

L'area di partenza può appartenere a un altro documento aperto.

Sintassi:

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

Parametri:

sourcerange: L'area di partenza in formato stringa se appartiene allo stesso documento, o come riferimento se appartiene ad un altro documento aperto di Calc.

destinationrange: la destinazione dell'area di celle copiate, in formato stringa.

Esempio:

In Basic

Copia all'interno dello stesso documento:


    oDoc.CopyToRange("SheetX.A1:F10", "SheetY.C5:J5")
    ' Restituisce l'area in formato stringa: "$FoglioY.$C$5:$J$14"
  

Copia da un file a un altro:


    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")
  
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

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

Sintassi:

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

Parametri:

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

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

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

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

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

Esempio:

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".

In Basic

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

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

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.


DAvg, DCount, DMax, DMin and DSum

Applica le funzioni Media, Conta, Max, Min e Somma, rispettivamente, a tutte le celle di una determinata area che contengono valori numerici.

Sintassi:

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

Parametri:

range: l'area sulla quale la funzione sarà applicata, in formato stringa.

Esempio:

L'esempio sottostante applica la funzione Somma all'area "A1:A1000" del foglio correntemente selezionato:

In Basic

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

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

Le celle dell'area specificata che contengono testo saranno ignorate da tutte queste funzioni. Per esempio, il metodo DCount non conterà le celle di testo, solo quelle numeriche.


Forms

A seconda dei parametri forniti questo metodo restituirà:

Sintassi:

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

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

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

Parametri:

sheetname: Il nome del foglio, in formato stringa, dal quale il formulario sarà recuperato.

form: il nome o l'indice corrispondente a un formulario memorizzato nel foglio specificato. Se questo argomento è assente, il metodo restituirà un elenco con i nomi di tutti i formulari disponibili nel foglio.

Esempio:

Negli esempi seguenti la prima riga ricava i nomi di tutti i formulari memorizzati nel "Foglio1" e la seconda recupera l'oggetto Form del formulario denominato "Form_A" che è memorizzato nel "Foglio1".

In Basic

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

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

GetColumnName

Converte il numero di una colonna compreso tra 1 e 1024 nella lettera corrispondente (colonna 'A', 'B', ..., 'AMJ'). Se il numero di colonna specificato è al di fuori dell'intervallo ammesso, viene restituita una stringa di lunghezza pari a zero.

Sintassi:

svc.GetColumnName(columnnumber: int): str

Parametri:

columnnumber: il numero di colonna come numero intero nell'intervallo 1 ... 1024.

Esempio:

In Basic

Visualizza una finestra di dialogo col nome della terza colonna, il cui valore predefinito è "C".


    MsgBox oDoc.GetColumnName(3)
  
In Python

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

Il numero massimo di colonne consentite in un foglio di Calc è 1024.


GetFormula

Ottiene le formule memorizzate nell'area di celle specificata, in formato stringa singola, o matrice di stringhe a 1D o 2D.

Sintassi:

svc.GetFormula(range: str): any

Parametri:

range: l'area dalla quale recuperare le formule, in formato stringa.

Esempio:

In Basic

Gli esempi che seguono restituiscono una matrice di 3 per 2 con le formule dell'area "A1:B3" (3 righe per 2 colonne):


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

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

GetValue

Ricava i valori memorizzati nell'area di celle specificata come valore singolo, o come matrice a 1D o 2D. Tutti i valori sono numeri a precisione doppia o stringhe.

Sintassi:

svc.GetValue(range: str): any

Parametri:

range: l'area da cui ricavare i valori, in formato stringa.

Esempio:

In Basic

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

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

Se una cella contiene una data, verrà restituito il numero corrispondente a quella data. Per convertire i valori numerici in date negli script in Basic, usate la funzione incorporata di Basic CDate. Negli script in Python, usate la funzione CDate del servizio Basic.


ImportFromCSVFile

Importa i contenuti di un file di testo formattato come CSV e li inserisce nella cella di destinazione specificata.

L'area di destinazione viene vuotata di tutti i contenuti e formati prima dell'inserimento del contenuto del file CSV. La dimensione dell'area modificata dipende completamente dai contenuti del file inserito.

Il metodo restituisce una stringa che rappresenta l'area di celle modificate.

Sintassi:

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

Parametri:

filename: identifica il file da aprire. Deve rispettare la notazione SF_FileSystem.FileNaming.

destinationcell: la cella di destinazione in cui inserire i dati importati, in formato stringa. Se invece viene specificata un'area, viene considerata solamente la sua prima cella in alto a sinistra.

filteroptions: gli argomenti per il filtro di importazione CSV. Il filtro predefinito presume quanto segue:

Esempio:

In Basic

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

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

Per saperne di più sulle opzioni del filtro CSV, fate riferimento alla pagina wiki sulle Opzioni dei filtri (in inglese).


ImportFromDatabase

Importa i contenuti da un database prendendoli da una tabella, una query o un insieme di risultati, ad esempio i risultati di un comando SQL SELECT, e inserendoli in una cella di destinazione.

L'area di destinazione viene vuotata di tutti i contenuti e formati prima dell'inserimento dei contenuti importati. Le dimensioni dell'area modificata dipende completamente dai contenuti della tabella o della query.

Il metodo restituisce True, se l'importazione ha avuto successo.

Sintassi:

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

Parametri:

filename: Identifica il file da aprire. Deve rispettare la notazione SF_FileSystem.FileNaming.

registrationname: il nome da usare per individuare il database tra quelli registrati. Questo argomento viene ignorato se viene specificato un filename.

destinationcell: la destinazione dei dati importati, in formato stringa. Se viene specificata un'area, viene considerata solamente la sua prima cella in alto a sinistra.

sqlcommand: il nome di una tabella o di una query (senza virgolette o parentesi quadre) o un'istruzione SQL SELECT, nella quale i nomi di tabella e dei campi possono essere racchiusi tra parentesi quadre o virgolette al fine di migliorare la leggibilità.

directsql: se True, il comando SQL viene inviato al motore di database senza una pre-analisi. Il valore predefinito è False. L'argomento viene ignorato per le tabelle. Per le query, l'opzione applicata è una quella impostata al momento della creazione della query.

Esempio:

In Basic

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

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

InsertSheet

Inserisce un nuovo foglio vuoto prima di un foglio esistente o alla fine dell'elenco dei fogli.

Sintassi:

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

Parametri:

sheetname: il nome del nuovo foglio.

beforesheet: il nome (stringa) o l'indice (numerico, a partire da 1) del foglio prima del quale inserire il nuovo foglio. Questo argomento è opzionale e il comportamento predefinito è quello di inserire un foglio nell'ultima posizione.

Esempio:

L'esempio seguente inserisce un nuovo foglio vuoto denominato "FoglioX" e lo posiziona prima del "FoglioY":

In Basic

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

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

MoveRange

Sposta l'area di celle di partenza specificata in un'area di destinazione. Il metodo restituisce una stringa che rappresenta l'area di celle modificata. Le dimensioni dell'area modificata è totalmente determinata dalle dimensioni dell'area di partenza.

Sintassi:

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

Parametri:

source: l'area di celle di partenza, in formato stringa.

destination: la cella di destinazione, in formato stringa. Se viene specificata un'area, viene considerata come destinazione la sua prima cella in alto a sinistra.

Esempio:

In Basic

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

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

MoveSheet

Sposta un foglio esistente e lo posiziona prima di un determinato foglio, o alla fine dell'elenco dei fogli.

Sintassi:

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

Parametri:

sheetname: il nome del foglio da spostare. Il foglio deve esistere, altrimenti viene sollevata un'eccezione.

beforesheet: il nome (stringa) o l'indice (numerico, a partire da 1) del foglio prima del quale verrà posizionato il foglio originale. Questo argomento è opzionale e il comportamento predefinito è quello di spostare il foglio all'ultima posizione.

Esempio:

L'esempio seguente sposta il foglio esistente "FoglioX" e lo posiziona prima del "FoglioY":

In Basic

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

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

Offset

Restituisce una nuova area (in formato stringa) spostata di un determinato numero di righe e colonne rispetto all'area specificata.

Questo metodo ha lo stesso comportamento della funzione Scarto di Calc.

Sintassi:

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

Parametri:

reference: l'area, in formato stringa, che il metodo userà come riferimento per eseguire l'operazione di "scarto".

rows: il numero di righe di cui l'area iniziale è spostata in alto (valore negativo), o in basso (valore positivo). Usate 0 (predefinito) per rimanere nella stessa riga.

columns: il numero di colonne di cui l'area iniziale è spostata a sinistra (valore negativo), o a destra (valore positivo). Usate 0 (predefinito) per rimanere nella stessa colonna.

height: l'altezza verticale per un'area che inizia dalla nuova posizione dell'area. Omettete questo argomento se non è necessario alcun ridimensionamento verticale.

width: la larghezza orizzontale per un'area che inizia dalla nuova posizione dell'area. Omettete questo argomento se non è necessario alcun ridimensionamento orizzontale.

Gli argomenti righe e colonne non devono condurre a un inizio di riga o colonna pari a zero o negativo.

Gli argomenti altezza e larghezza non devono condurre a un conteggio di righe o colonne pari a zero o negativo.

Esempio:

In Basic

    oDoc.Offset("A1", 2, 2)
    'FoglioX.$C$3 (A1 spostato in basso di due righe e due colonne)
    oDoc.Offset("A1", 2, 2, 5, 6)
    'FoglioX.$C$3:$H$7 (A1 spostato di due righe e colonne con una larghezza di 5 righe e 6 colonne)
  
In Python

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

OpenRangeSelector

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

This method opens the same dialog that is used by LibreOffice 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.


This method does not change the current selection.

Sintassi:

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

Parametri:

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

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

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

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.

Esempio:

In Basic

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

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

Printf

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

This method does not change the current selection.

tip

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.


Sintassi:

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

Parametri:

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

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

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

Esempio:

In Basic

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)
  

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"
    ' Note the use of the "$" character
    sFormula = "=SUM($%C1%R1:$%C2%R1)"
    oDoc.SetFormula("F1:F10", oDoc.Printf(sFormula, sRange))
  
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

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.

Returns True if the sheet was successfully printed.

Sintassi:

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

Parametri:

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

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

copies: The number of copies. Default is 1.

Esempio:

In Basic

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

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

RemoveSheet

Elimina un foglio esistente dal documento.

Sintassi:

svc.RemoveSheet(sheetname: str): bool

Parametri:

sheetname: il nome del foglio da eliminare.

Esempio:

In Basic

    oDoc.RemoveSheet("SheetY")
  
In Python

    myDoc.RemoveSheet("SheetY")
  

RenameSheet

Rinomina il foglio specificato e restituisce True se l'operazione va a buon fine.

Sintassi:

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

Parametri:

sheetname: il nome del foglio da rinominare.

newname: il nuovo nome del foglio. Non deve essere esistere già.

Esempio:

Questo esempio rinomina in "FoglioY" il foglio attivo:

In Basic

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

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

SetArray

Memorizza il valore indicato a partire dalla cella di destinazione specificata. L'area aggiornata si espande dalla cella di destinazione o dall'angolo in alto a sinistra dell'area indicata al fine di adeguarsi alle dimensioni dell'argomento inserito come valore. I vettori si espandono sempre verticalmente.

Il metodo restituisce una stringa che rappresenta l'area modificata come un intervallo di celle.

Sintassi:

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

Parametri:

targetcell: la cella o l'area, in formato stringa, dalla quale iniziare a memorizzare il valore indicato.

value: uno scalare, un vettore o una matrice (in Python, liste e tuple a una o due dimensioni) con i nuovi valori da memorizzare a partire dalla cella di destinazione o dall'angolo in alto a sinistra dell'intervallo di celle quando targetcell è un'area. I nuovi valori devono essere stringhe, valori numerici o date. Altri tipi comporteranno lo svuotamento delle celle corrispondenti.

Esempio:

In Basic

Il seguente esempio fa uso della funzione incorporata DimArray per creare una matrice e poi memorizzarla nella cella "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)
  

Questo esempio usa il metodo RangeInit del servizio Array di ScriptForge per creare una matrice con i valori da memorizzare poi a partire dalla cella "A1" verso il basso.


    'Riempie la prima colonna con valori da 1 a 1000
    oDoc.SetArray("Sheet1.A1", SF_Array.RangeInit(1, 1000))
  
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

Per salvare l'intero contenuto di una matrice in un foglio, usate SetArray. Per salvare i contenuti di una matrice solo entro i limiti dell'intervallo di celle di destinazione, usate SetValue.


SetValue

Memorizza il valore indicato nell'area specificata. Le dimensioni dell'area modificata sono uguali alle dimensioni dell'area di destinazione.

Il metodo restituisce una stringa che rappresenta l'area modificata come un intervallo di celle.

Sintassi:

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

Parametri:

targetrange: l'area in cui memorizzare il valore indicato, in formato stringa.

value: uno scalare, un vettore o una matrice con i nuovi valori per ciascuna cella dell'area. I nuovi valori devono essere stringhe, valori numerici o date. Altri tipi comporteranno lo svuotamento delle celle corrispondenti.

L'intera area viene aggiornata e il resto del foglio non viene modificato. Se le dimensioni di value sono inferiori a quelle di targetrange, le celle rimanenti saranno vuotate.

Se la dimensione di value è maggiore di quella di targetrange, allora value viene copiato solo parzialmente fino a riempire la dimensione di targetrange.

I Vettori si estendono verticalmente, eccetto quando targetrange ha un'altezza pari esattamente a una riga.

Esempio:

In Basic

    oDoc.SetValue("A1", 2)
    'Qui sotto la matrice Value è più piccola di TargetRange (le celle rimanenti vengono svuotate)
    oDoc.SetValue("A1:F1", Array(1, 2, 3))
    'Qui sotto Value e TargetRange hanno le stesse dimensioni
    oDoc.SetValue("A1:D2", SF_Array.AppendRow(Array(1, 2, 3, 4), Array(5, 6, 7, 8)))
  

Se volete riempire una singola riga con dei valori, potete usare la funzione Offset. Nell'esempio seguente, considerate che arrData è una matrice unidimensionale:


    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)
  
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)
  

SetCellStyle

Applica lo stile di cella specificato all'area di destinazione indicata. L'intera area viene aggiornata e il resto del foglio non viene modificato. Se lo stile di cella non esiste, viene generato un errore.

Il metodo restituisce una stringa che rappresenta l'area modificata come un intervallo di celle.

Sintassi:

svc.SetCellStyle(targetrange: str, style: str): str

Parametri:

targetrange: l'area a cui sarà applicato lo stile, in formato stringa.

style: il nome dello stile di cella da applicare.

Esempio:

In Basic

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

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

SetFormula

Inserisce la formula (o la matrice di formule) precisata nell'intervallo di celle specificato. Le dimensioni dell'area modificata sono uguali a quelle dell'intervallo di celle.

Il metodo restituisce una stringa che rappresenta l'area modificata come un intervallo di celle.

Sintassi:

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

Parametri:

targetrange: l'intervallo di celle in cui inserire le formule, in formato stringa.

formula: una stringa, un vettore o una matrice di stringhe con le nuove formule per ciascuna delle celle nell'area di destinazione.

L'intera area viene aggiornata e il resto del foglio non viene modificato.

Se la formula indicata è una stringa, quella singola formula viene copiata in tutta l'area con la regolazione dei riferimenti relativi.

Se la dimensione di formula è inferiore a quella di targetrange, le celle rimanenti vengono svuotate.

Se la dimensione di formula è maggiore di quella di targetrange, le formule sono copiate solo parzialmente fino a riempire la dimensione di targetrange.

I Vettori si estendono sempre in verticale, eccetto quando targetrange ha un'altezza pari esattamente a una riga.

Esempio:

In Basic

    oDoc.SetFormula("A1", "=A2")
    'Vettore orizzontale, parzialmente vuoto
    oDoc.SetFormula("A1:F1", Array("=A2", "=B2", "=C2+10"))
    'D2 contiene la formula "=H2"
    oDoc.SetFormula("A1:D2", "=E1")
  
In Python

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

ShiftDown

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

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

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

note

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


Sintassi:

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

Parametri:

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

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.

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.

Esempio:

In Basic

    ' Moves the range "A3:D3" down by one row; affects only columns A to D
    oDoc.ShiftDown("A3:D3")
    ' The inserted row spans all columns in the sheet
    oDoc.ShiftDown("A3:D3", WholeRow := True)
    ' Moves the range "A3:D3" down by five rows
    oDoc.ShiftDown("A3:D3", Rows := 5)
    ' 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
  
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

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.

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

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.

Sintassi:

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

Parametri:

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

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.

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.

Esempio:

In Basic

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

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

ShiftUp

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

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

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.

Sintassi:

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

Parametri:

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

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.

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.

Esempio:

In Basic

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

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

ShiftRight

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

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

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

note

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


Sintassi:

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

Parametri:

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

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.

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

Esempio:

In Basic

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

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

SortRange

Ordina l'intervallo di celle indicato in base a un massimo di tre colonne/righe. Il tipo di ordinamento può variare per colonna/riga. Restituisce una stringa che rappresenta l'area modificata. La dimensione dell'area modificata è determinata interamente da quella dell'area di partenza.

Sintassi:

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

Parametri:

range: l'area da ordinare, in formato stringa.

sortkeys: uno scalare (se di una colonna/riga) o una matrice di colonne/righe numerate a partire da 1. Il numero massimo di chiavi è 3.

sortorder: uno scalare o una matrice di stringhe che contiene i valori "ASC" (ascendente), "DESC" (discendente) o "" (per il valore predefinito ascendente). Ogni elemento è accoppiato al corrispondente in sortkeys. Se sortorder è una matrice più corta di sortkeys, le chiavi rimanenti vengono ordinate in modo ascendente.

destinationcell: la cella di destinazione per l'intervallo di celle riordinate, in formato stringa. Se è indicata un'area, viene considerata solo la cella nell'angolo in alto a sinistra. Per impostazione predefinita viene sovrascritta l'area di partenza.

containsheader: quando è True, la prima riga/colonna non viene riordinata.

casesensitive: solo per il confronto di stringhe. Predefinito = False

sortcolumns: quando è True, le colonne sono riordinate da sinistra a destra. Predefinito = False : le righe sono riordinate dall'alto verso il basso.

Esempio:

In Basic

    'Ordina un'area in base alle colonne A (ascendente) e C (discendente)
    oDoc.SortRange("A2:J200", Array(1, 3), Array("ASC", "DESC"), CaseSensitive := True)
  
In Python

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

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.