Ajuda del LibreOffice 7.2
Ofereix una col·lecció de mètodes per manipular i transformar matrius d’una dimensió (vectors) i matrius de dues dimensions (matrius). Això inclou les operacions de configuració, ordenació, importació i exportació de fitxers de text.
No es poden utilitzar matrius amb més de dues dimensions amb els mètodes d’aquest servei, l'única excepció és el mètode CountDims que accepta matrius amb qualsevol nombre de dimensions
Els elements de matriu poden contenir qualsevol tipus de valor, incloent (sub) matrius.
Abans d'utilitzar el servei Array, la biblioteca ScriptForge s'ha de carregar utilitzant:
GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")
Carregar la llibreria crearà l'objecte SF_Array que poden utilitzar-se cridant els mètodes del servei Matriu.
Els fragments de codi següents mostren diverses maneres de cridar als mètodes del servei Matriu (el mètode Append s'utilitza com exemple):
SF_Array.Append(...)
Dim arr : arr = SF_Array
arr.Append(...)
Dim arr : arr = CreateScriptService("Array")
arr.Append(...)
El mètode CreateScriptService només està disponible un cop carregada la biblioteca ScriptForge.
El primer argument de la majoria de mètodes és l’objecte matriu a considerar. Sempre es passa per referència i es deixa sense canvis. Mètodes com ara Append, Prepend, etc. retornen un nou objecte array després de la seva execució.
Afegeix els elements llistats com a arguments al final de la matriu d'entrada.
SF_Array.Append(Array_1D As Variant, arg0 As Variant, [arg1 As Variant], ...) As Variant
Array_1D: la matriu preexistent, pot estar buida.
arg0, ... : una llista d’elements per afegir a Array_1D.
Sub Example_Append()
Dim a As Variant
a = SF_Array.Append(Array(1, 2, 3), 4, 5)
' (1, 2, 3, 4, 5)
End Sub
Afegeix una nova columna a la part dreta d'una matriu bidimensional. La matriu resultant té els mateixos límits inferiors que la matriu bidimensional inicial.
SF_Array.AppendColumn(Array_2D As Variant, New_Column As Variant) As Variant
Array_2D : la matriu preexistent pot estar buida. Si aquesta matriu només té una dimensió, es considera la primera columna de la matriu bidimensional resultant.
New_Column : una matriu unidimensional amb tants elements com files hi ha a Array_2D.
Sub Example_AppendColumn()
Dim a As Variant, b As variant
a = SF_Array.AppendColumn(Array(1, 2, 3), Array(4, 5, 6))
' ((1, 4), (2, 5), (3, 6))
b = SF_Array.AppendColumn(a, Array(7, 8, 9))
' ((1, 4, 7), (2, 5, 8), (3, 6, 9))
c = SF_Array.AppendColumn(Array(), Array(1, 2, 3))
' ∀ i ∈ {0 ≤ i ≤ 2} : b(0, i) ≡ i
End Sub
Afegeix a la part inferior d'una matriu de dues dimensions una fila nova. La matriu resultant té els mateixos límits inferiors que la matriu inicial de dues dimensions.
SF_Array.AppendRow(Array_2D As Variant, Row As Variant) As Variant
Array_2D : la matriu preexistent pot estar buida. Si aquesta matriu té 1 dimensió, es considera com la primera fila de la matriu de 2 dimensions resultant.
Row : una matriu 1D amb tants elements com columnes hi ha a Array_2D.
Sub Example_AppendRow()
Dim a As Variant, b As variant
a = SF_Array.AppendRow(Array(1, 2, 3), Array(4, 5, 6))
' ((1, 2, 3), (4, 5, 6))
b = SF_Array..AppendRow(Array(), Array(1, 2, 3))
' ∀ i ∈ {0 ≤ i ≤ 2} : b(i, 0) ≡ i
End Sub
Comproveu si una matriu d'una dimensió conté un nombre, un text o una data determinats. La comparació pot distingir entre majúscules i minúscules.
Les matrius d'entrada ordenades s'han d'omplir de manera homogènia, és a dir, tots els elements han de ser escalars del mateix tipus (elements Buits i Nuls estan prohibits).
El resultat del mètode és imprevisible quan la matriu s'assenyala com a ordenada i, en realitat, no ho està.
Una cerca binària es fa quan s’ordena la matriu, en cas contrari, simplement s’escaneja de dalt a baix ii els elements Buits i Nuls s'ignoren.
SF_Array.Contains(Array_1D, ToFind As Variant, [CaseSensitive As Boolean], [SortOrder As String]) As Boolean
Array_1D : matriu a analitzar.
ToFind : un número, una data o una cadena a cercar.
CaseSensitive :Tan sols per comparar cadenes, per defecte = Fals.
SortOrder : "ASC", "DESC" o "" (= no ordenat, per defecte)
Sub Example_Contains()
Dim a As Variant
a = SF_Array.Contains(Array("A","B","c","D"), "C", SortOrder := "ASC") ' True
SF_Array.Contains(Array("A","B","c","D"), "C", CaseSensitive := True) ' False
End Sub
Emmagatzemeu el contingut d'una matriu de 2 columnes en un objecte ScriptForge.Dictionary.
La clau s’extreurà de la primera columna, l’element de la segona.
SF_Array.ConvertToDictionary(Array_2D As Variant) As Variant
Array_1D : la primera columna ha de contenir exclusivament cadenes amb una longitud > 0, en qualsevol ordre.
Sub Example_ConvertToDictionary()
Dim a As Variant, b As Variant
a = SF_Array.AppendColumn(Array("a", "b", "c"), Array(1, 2, 3))
b = SF_Array.ConvertToDictionary(a)
MsgBox b.Item("c") ' 3
End Sub
Compteu el nombre de dimensions d'una matriu. El resultat pot ser superior a dos.
Si l'argument no és una matriu, retorna -1
Si la matriu no està inicialitzada, retorna 0.
SF_Array.CountDims(Array_ND As Variant) As Integer
Array_ND : la matriu a examinar.
Sub Example_CountDims()
Dim a(1 To 10, -3 To 12, 5)
MsgBox SF_Array.CountDims(a) ' 3
End Sub
Construir un conjunt, com una matriu zero, aplicant l’operador diferència a dues matrius d’entrada. Els elements resultants provenen de la primera matriu i no de la segona.
La matriu resultant s'ordena de forma ascendent.
Les dues matrius d’entrada s’han d’omplir de manera homogènia, els seus elements han de ser escalars del mateix tipus. Els elements buits i nuls estan prohibits.
La comparació entre texts pot distingir entre majúscules o minúscules.
SF_Array.Difference(Array1_1D As Variant, Array2_1D As Variant[, CaseSensitive As Boolean]) As Variant
Array1_1D : En una matriu de referència d'una dimensió, els ítems que s'examinen per eliminar.
Array2_1D : En una matriu d'una dimensió, els ítems que es substreuen des de la primera matriu.
CaseSensitive : Tan sols si les matrius s'han poblat amb cadenes text, de forma predeterminada = Fals.
Sub Example_Difference()
Dim a As Variant
a = SF_Array.Difference(Array("A", "C", "A", "b", "B"), Array("C", "Z", "b"), True)
' ("A", "B")
End Sub
Escriviu tots els elements de la matriu de manera seqüencial en un fitxer de text. Si el fitxer ja existeix, se sobreescriurà sense previ avís.
SF_Array.ExportToTextFile(Array_1D As Variant, FileName As String, [Encoding As String]) As Boolean
Array_1D : Matriu a exportar. Tan sols pot contenir cadenes de text..
FileName : the name of the text file containing the data. The name is expressed as given by the current FileNaming property of the SF_FileSystem service. Default = any (both the URL format and the native operating system format are admitted).
Encoding : The character set that should be used. Use one of the names listed in IANA character sets. Note that LibreOffice may not implement all existing character sets. Default is "UTF-8".
Sub Example_ExportToTextFile()
SF_Array.ExportToTextFile(Array("A","B","C","D"), "C:\Temp\A short file.txt")
End Sub
Extreu d'una matriu de dues dimensions una columna específica com a nova matriu. Els límits
InferiorLBound i superior UBound són idèntics als de la primera dimensió de la matriu d'entrada.
SF_Array.ExtractColumn(Array_2D As Variant, ColumnIndex As Long) As Variant
Array_2D : La matriu a partir de la qual extreure.
ColumnIndex : El número de columna que s'ha d'extreure ha de pertanyer a l'interval [LBound, UBound].
Sub Example_ExtractColumn
'Crea una matriu 3x3: |1, 2, 3|
' |4, 5, 6|
' |7, 8, 9|
Dim mat as Variant, col as Variant
mat = SF_Array.AppendRow(Array(), Array(1, 2, 3))
mat = SF_Array.AppendRow(mat, Array(4, 5, 6))
mat = SF_Array.AppendRow(mat, Array(7, 8, 9))
'Extreu la tercera columna: |3, 6, 9|
col = SF_Array.ExtractColumn(mat, 2)
End Sub
Extract from a two dimension array a specific row as a new array.
Its lower LBound and upper UBound boundaries are identical to that of the second dimension of the input array.
SF_Array.ExtractRow(Array_2D As Variant, RowIndex As Long) As Variant
Array_2D : La matriu a partir de la qual extreure.
RowIndex : El número de fila que cal extreure ha de pertànyer a l'interval [LBound, UBound].
Sub Example_ExtractRow
'Crea una matriu 3x3: |1, 2, 3|
' |4, 5, 6|
' |7, 8, 9|
Dim mat as Variant, row as Variant
mat = SF_Array.AppendRow(Array(), Array(1, 2, 3))
mat = SF_Array.AppendRow(mat, Array(4, 5, 6))
mat = SF_Array.AppendRow(mat, Array(7, 8, 9))
'Extreu la primera fila: |1, 2, 3|
row = SF_Array.ExtractRow(mat, 0)
End Sub
Apila tots els elements individuals d’una matriu i tots els elements de les seves submatrius en una nova matriu sense submatrius. Les submatrius buides s'ignoren i les submatrius amb un nombre de dimensions superior a un no s'aplanen.
SF_Array.Flatten(Array_1D As Variant) As Variant
Array_1D : la matriu preexistent, pot estar buida.
Sub Example_Flatten()
Dim a As Variant
a = SF_Array.Flatten(Array(Array(1, 2, 3), 4, 5))
' (1, 2, 3, 4, 5)
End Sub
You can use the Flatten method along with other methods such as Append or Prepend to concatenate a set of 1D arrays into a single 1D array.
Next is an example of how the methods Flatten and Append can be combined to concatenate three arrays.
Sub Concatenate_Example
'Creates three arrays for this example
Dim a as Variant, b as Variant, c as Variant
a = Array(1, 2, 3)
b = Array(4, 5)
c = Array(6, 7, 8, 9)
'Concatenates the three arrays into a single 1D array
Dim arr as Variant
arr = SF_Array.Flatten(SF_Array.Append(a, b, c))
'(1, 2, 3, 4, 5, 6, 7, 8, 9)
End Sub
Import the data contained in a comma-separated values (CSV) file. The comma may be replaced by any character.
The applicable CSV format is described in IETF Common Format and MIME Type for CSV Files.
Each line in the file contains a full record (line splitting is not allowed).
However sequences like \n, \t, ... are left unchanged. Use SF_String.Unescape() method to manage them.
The method returns a two dimension array whose rows correspond to a single record read in the file and whose columns correspond to a field of the record. No check is made about the coherence of the field types across columns. A best guess will be made to identify numeric and date types.
If a line contains less or more fields than the first line in the file, an exception will be raised. Empty lines however are simply ignored. If the size of the file exceeds the number of items limit (see inside the code), a warning is raised and the array is truncated.
SF_Array.ImportFromCSVFile(FileName As String, [Delimiter As String], [DateFormat As String]) As Variant
FileName : the name of the text file containing the data. The name is expressed as given by the current FileNaming property of the SF_FileSystem service. Default = any (both the URL format and the native operating system format are admitted).
Delimiter : A single character, usually, a comma, a semicolon or a TAB character. Default = ",".
DateFormat : A special mechanism handles dates when DateFormat is either "YYYY-MM-DD", "DD-MM-YYYY" or "MM-DD-YYYY". The dash (-) may be replaced by a dot (.), a slash (/) or a space. Other date formats will be ignored. Dates defaulting to "" are considered as normal text.
Given this CSV file:
Name,DateOfBirth,Address,City
Anna,2002/03/31,"Rue de l'église, 21",Toulouse
Fred,1998/05/04,"Rue Albert Einstein, 113A",Carcassonne
Sub Example_ImportFromCSVFile()
Dim a As Variant
a = SF_Array.ImportFromCSVFile("C:\Temp\myFile.csv", DateFormat := "YYYY/MM/DD")
MsgBox a(0, 3) ' City
MsgBox TypeName(a(1, 2)) ' Date
MsgBox a(2, 2) ' Rue Albert Einstein, 113A
End Sub
Look in a one dimension array for a number, a string or a date. Text comparison can be case-sensitive or not.
If the array is sorted it must be filled homogeneously, which means that all items must be scalars of the same type (Empty and Null items are forbidden).
The result of the method is unpredictable when the array is announced as sorted and actually is not.
A binary search is performed on sorted arrays. Otherwise, arrays are simply scanned from top to bottom and Empty and Null items are ignored.
The method returns LBound(input array) - 1 if the search was not successful.
SF_Array.IndexOf(Array_1D, ToFind As Variant, [CaseSensitive As Boolean], [SortOrder As String]) As Long
Array_1D : the array to scan.
ToFind : a number, a date or a string to find.
CaseSensitive : Only for string comparisons, default = False.
SortOrder : "ASC", "DESC" or "" (= not sorted, default)
Sub Example_IndexOf()
MsgBox SF_Array.IndexOf(Array("A","B","c","D"), "C", SortOrder := "ASC") ' 2
MsgBox SF_Array.IndexOf(Array("A","B","c","D"), "C", CaseSensitive := True) ' -1
End Sub
Insert before a given index of the input array the items listed as arguments.
Arguments are inserted blindly. Each of them might be either a scalar of any type or a subarray.
SF_Array.Insert(Array_1D As Variant, Before As Long, arg0 As Variant, [arg1 As Variant], ...) As Variant
Array_1D : the pre-existing array, may be empty.
Before : the index before which to insert; must be in the interval [LBound, UBound + 1].
arg0, ... : a list of items to insert inside Array_1D.
Sub Example_Insert()
Dim a As Variant
a = SF_Array.Insert(Array(1, 2, 3), 2, "a", "b")
' (1, 2, "a", "b", 3)
End Sub
Insert in a sorted array a new item on its place.
The array must be filled homogeneously, meaning that all items must be scalars of the same type.
Empty and Null items are forbidden.
SF_Array.InsertSorted(Array_1D As Variant, Item As Variant, SortOrder As String, CaseSensitive As Boolean) As Variant
Array_1D : The array to sort.
Item : The scalar value to insert, of the same type as the existing array items.
SortOrder : "ASC" (default) or "DESC".
CaseSensitive : Only for string comparisons, default = False.
Sub Example_InsertSorted()
Dim a As Variant
a = SF_Array.InsertSorted(Array("A", "C", "a", "b"), "B", CaseSensitive := True)
' ("A", "B", "C", "a", "b")
End Sub
Build a set, as a zero-based array, by applying the intersection set operator on the two input arrays. Resulting items are contained in both arrays.
The resulting array is sorted in ascending order.
Both input arrays must be filled homogeneously, in other words all items must be scalars of the same type. Empty and Null items are forbidden.
Text comparison can be case sensitive or not.
SF_Array.Intersection(Array1_1D As Variant, Array2_1D As Variant[, CaseSensitive As Boolean]) As Variant
Array1_1D : The first input array.
Array2_1D : The second input array.
CaseSensitive : Applies to arrays populated with text items, default = False.
Sub Example_Intersection()
Dim a As Variant
a = SF_Array.Intersection(Array("A", "C", "A", "b", "B"), Array("C", "Z", "b"), True)
' ("C", "b")
End Sub
Join a two-dimensional array with two delimiters, one for the columns, one for the rows.
SF_Array.Join2D(Array_2D As Variant, ColumnDelimiter As String, RowDelimiter As String, Quote As Boolean) As String
Array_2D : Each item must be either text, a number, a date or a boolean.
Dates are transformed into the YYYY-MM-DD hh:mm:ss format.
Invalid items are replaced by a zero-length string.
ColumnDelimiter : Delimits each column (default = Tab/Chr(9)).
RowDelimiter: delimits each row (default = LineFeed/Chr(10))
Quote : if True, protect strings with double quotes. The default is False.
Sub Example_Join2D()
- | 1, 2, "A", [2020-02-29], 5 |
- SF_Array.Join_2D(| 6, 7, "this is a string", 9, 10 |, ",", "/")
- ' "1,2,A,2020-02-29 00:00:00,5/6,7,this is a string,9,10"
End Sub
Prepend at the beginning of the input array the items listed as arguments.
SF_Array.Prepend(Array_1D As Variant, arg0 As Variant, [arg1 As Variant], ...) As Variant
Array_1D : the pre-existing array, may be empty.
arg0, ... : a list of items to prepend to Array_1D.
Sub Example_Prepend()
Dim a As Variant
a = SF_Array.Prepend(Array(1, 2, 3), 4, 5)
' (4, 5, 1, 2, 3)
End Sub
Prepend to the left side of a two dimension array a new column. The resulting array has the same lower boundaries as the initial two dimension array.
SF_Array.PrependColumn(Array_2D As Variant, Column As Variant) As Variant
Array_2D : the pre-existing array, may be empty. If that array has 1 dimension, it is considered as the last column of the resulting 2 dimension array.
Column : a 1 dimension array with as many items as there are rows in Array_2D.
Sub Example_PrependColumn()
Dim a As Variant, b As variant
a = SF_Array.PrependColumn(Array(1, 2, 3), Array(4, 5, 6))
' ((4, 1), (5, 2), (6, 3))
b = SF_Array.PrependColumn(Array(), Array(1, 2, 3))
' ∀ i ∈ {0 ≤ i ≤ 2} : b(0, i) ≡ i
End Sub
Prepend at the beginning of a two dimension array a new row. The resulting array has the same lower boundaries as the initial two dimension array.
SF_Array.PrependRow(Array_2D As Variant, Row As Variant) As Variant
Array_2D : the pre-existing array, may be empty. If that array has 1 dimension, it is considered as the last row of the resulting 2 dimension array.
Row : a 1 dimension array containing as many items as there are rows in Array_2D.
Sub Example_PrependRow()
Dim a As Variant, b As variant
a = SF_Array.PrependRow(Array(1, 2, 3), Array(4, 5, 6))
' ((4, 5, 6), (1, 2, 3))
b = SF_Array.PrependRow(Array(), Array(1, 2, 3))
' ∀ i ∈ {0 ≤ i ≤ 2} : b(i, 0) ≡ i
End Sub
Initialize a new zero-based array with numeric values.
SF_Array.RangeInit(From As [number], UpTo As [number] [, ByStep As [number]]) As Variant
From : value of the first item.
UpTo : The last item should not exceed UpTo.
ByStep : The difference between two successive items (default = 1).
Sub Example_RangeInit()
Dim a As Variant
a = SF_Array.RangeInit(10, 1, -1)
' (10, 9, 8, 7, 6, 5, 4, 3, 2, 1)
End Sub
Return the reversed one dimension input array.
SF_Array.Reverse(Array_1D As Variant) As Variant
Array_1D : The array to reverse.
Sub Example_Reverse()
Dim a As Variant
a = SF_Array.Reverse(Array("a", 2, 3, 4))
' (4, 3, 2, "a")
End Sub
Return a random permutation of a one dimension array.
SF_Array.Shuffle(Array_1D As Variant) As Variant
Array_1D : The array to shuffle.
Sub Example_Shuffle()
Dim a As Variant
a = SF_Array.Shuffle(Array(1, 2, 3, 4))
' Unpredictable
End Sub
Return a subset of a one dimension array.
SF_Array.Slice(Array_1D As Variant, From As Long, [UpTo As Long]) As Variant
Array_1D : The array to slice.
From : The lower index in Array_1D of the subarray to extract (From included)
UpTo : The upper index in Array_1D of the subarray to extract (UpTo included). Default = upper bound of Array_1D. If UpTo < From then the returned array is empty.
Sub Example_Slice()
Dim a As Variant
a = SF_Array.Slice(Array(1, 2, 3, 4, 5), 1, 3) ' (2, 3, 4)
End Sub
Sort a one dimension array in ascending or descending order. Text comparisons can be case-sensitive or not.
The array must be filled homogeneously, which means that items must be scalars of the same type.
Empty and Null items are allowed. Conventionally Empty < Null < any other scalar value.
SF_Array.Sort(Array_1D As Variant, SortOrder As String, CaseSensitive As Boolean) As Variant
Array_1D : The array to sort.
SortOrder : "ASC" (default) or "DESC".
CaseSensitive : Only for string comparisons, default = False.
Sub Example_Sort()
Dim a As Variant
a = SF_Array.Sort(Array("a", "A", "b", "B", "C"), CaseSensitive := True)
' ("A", "B", "C", "a", "b")
End Sub
Return a permutation of the columns of a two dimension array, sorted on the values of a given row.
The row must be filled homogeneously, which means that all items must be scalars of the same type.
Empty and Null items are allowed. Conventionally Empty < Null < any other scalar value.
SF_Array.SortColumns(Array_1D As Variant, RowIndex As Long, SortOrder As String, CaseSensitive As Boolean) As Variant
Array_1D : The array to sort.
RowIndex : The index of the row to sort the columns on.
SortOrder : "ASC" (default) or "DESC".
CaseSensitive : Only for string comparisons, default = False.
Sub Example_SortColumns()
- | 5, 7, 3 | ' | 7, 5, 3 |
- SF_Array.SortColumns(| 1, 9, 5 |, 2, "ASC") ' | 9, 1, 5 |
- | 6, 1, 8 | ' | 1, 6, 8 |
End Sub
Return a permutation of the rows of a two dimension array, sorted on the values of a given column.
The column must be filled homogeneously, therefore all items must be scalars of the same type.
Empty and Null items are allowed. Conventionally Empty < Null < any other scalar value.
SF_Array.SortRows(Array_1D As Variant, ColumnIndex As Long, SortOrder As String, CaseSensitive As Boolean) As Variant
Array_1D : The array to sort.
RowIndex : The index of the column to sort the rows on.
SortOrder : "ASC" (default) or "DESC".
CaseSensitive : Only for string comparisons, default = False.
Sub Example_SortRows()
- | 5, 7, 3 | ' | 1, 9, 5 |
- SF_Array.SortRows(| 1, 9, 5 |, 2, "ASC") ' | 5, 7, 3 |
- | 6, 1, 8 | ' | 6, 1, 8 |
End Sub
Swap rows and columns in a two dimension array.
SF_Array.Transpose(Array_2D As Variant) As Variant
Array_2D : The array to transpose.
Sub Example_Transpose()
- | 1, 2 | ' | 1, 3, 5 |
- SF_Array.Transpose(| 3, 4 |) ' | 2, 4, 6 |
- | 5, 6 |
End Sub
Remove from a one dimension array all Null, Empty and zero-length entries.
String items are trimmed with LibreOffice Basic Trim() function.
SF_Array.TrimArray(Array_1D As Variant) As Variant
Array_1D : The array to scan.
Sub Example_TrimArray()
Dim a As Variant
a = SF_Array.TrimArray(Array("A","B",Null," D "))
' ("A","B","D")
End Sub
Build a set, as a zero-based array, by applying the union operator on the two input arrays. Resulting items originate from both arrays.
The resulting array is sorted in ascending order.
Both input arrays must be filled homogeneously, their items must be scalars of the same type. Empty and Null items are forbidden.
Text comparison can be case sensitive or not.
SF_Array.Union(Array1_1D As Variant, Array2_1D As Variant[, CaseSensitive As Boolean]) As Variant
Array1_1D : The first input array.
Array2_1D : The second input array.
CaseSensitive : Only if the arrays are populated with strings, default = False.
Sub Example_Union()
Dim a As Variant
a = SF_Array.Union(Array("A", "C", "A", "b", "B"), Array("C", "Z", "b"), True)
' ("A", "B", "C", "Z", "b")
End Sub
Build a set of unique values derived from the input array.
The input array must be filled homogeneously, its items must be scalars of the same type. Empty and Null items are forbidden.
Text comparison can be case sensitive or not.
SF_Array.Unique(Array_1D As Variant, CaseSensitive As Boolean]) As Variant
Array_1D : The input array.
CaseSensitive : Only if the array is populated with texts, default = False.
Sub Example_Unique()
Dim a As Variant
a = SF_Array.Unique(Array("A", "C", "A", "b", "B"), CaseSensitive := True)
' ("A", "B", "C", "b")
End Sub