Aide LibreOffice 7.2
Fournit une collection de méthodes pour manipuler et transformer des matrices d'une dimension (vecteurs) et des matrices de deux dimensions (matrices). Cela inclut les opérations d'ensemble, le tri, l'import et l'export à partir de fichiers texte.
Les matrices avec plus de deux dimensions ne peuvent pas être utilisées avec les méthodes de ce service, la seule exception étant la méthode CountDims qui accepte les matrices avec un nombre quelconque de dimensions.
Les éléments de matrice peuvent contenir n'importe quel type de valeur, y compris des (sous) matrices.
Avant de pouvoir utiliser le service Array, la bibliothèque ScriptForge doit être chargée en utilisant :
GlobalScope.BasicLibraries.LoadLibrary("ScriptForge")
Charger la bibliothèque créera l'objet SF_Array qui peut être utilisé pour appeler les méthode dans le service Array.
Les extraits de code suivants montrent les différentes façons d'appeler des méthodes dans le service Array (la méthode Append est utilisée comme exemple) :
SF_Array.Append(...)
Dim arr : arr = SF_Array
arr.Append(...)
Dim arr : arr = CreateScriptService("Array")
arr.Append(...)
La méthode CreateScriptService n'est disponible qu'après avoir chargé la bibliothèque ScriptForge.
Le premier argument de la plupart des méthodes est l'objet matrice à prendre en compte. Il est toujours passé par référence et laissé inchangé. Les méthodes telles que Append, Prepend, etc. renvoient un nouvel objet matrice après leur exécution.
Ajoute les éléments répertoriés comme arguments à la fin de la matrice d'entrée.
SF_Array.Append(Array_1D As Variant, arg0 As Variant, [arg1 As Variant], ...) As Variant
Array_1D : la matrice préexistante peut être vide.
arg0, ... : une liste d'éléments à ajouter à 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
Ajoute une nouvelle colonne sur le côté droit d'une matrice à deux dimensions. La matrice résultante a les mêmes limites inférieures que la matrice bidimensionnelle initiale.
SF_Array.AppendColumn(Array_2D As Variant, New_Column As Variant) As Variant
Array_2D: la matrice préexistante, peut être vide. Si cette matrice n'a qu'une seule dimension, elle est considérée comme la première colonne de la matrice bidimensionnelle résultante.
New_Column : une matrice à 1 dimension avec autant d'éléments qu'il y a de lignes dans 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
Ajoutez une nouvelle ligne au bas d'une matrice à deux dimensions. La matrice résultante a les mêmes limites inférieures que la matrice initiale à deux dimensions.
SF_Array.AppendRow(Array_2D As Variant, Row As Variant) As Variant
Array_2D: la matrice préexistante, peut être vide. Si cette matrice a 1 dimension, elle est considérée comme la première ligne de la matrice à 2 dimensions résultante.
Row: une matrice 1D avec autant d'éléments qu'il y a de colonnes dans 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
Vérifier si un tableau à une dimension contient un certain nombre, du texte ou une date. La comparaison de texte peut être sensible à la casse ou non.
Les matrices d'entrée triées doivent être remplies de manière homogène, ce qui signifie que tous les éléments doivent être des scalaires du même type (les éléments Empty et Null sont interdits).
Le résultat de la méthode est imprévisible lorsque la matrice est annoncée comme triée et ne l'est pas en réalité.
Une recherche binaire est effectuée lorsque la matrice est triée, sinon, elle est simplement scannée de haut en bas et les éléments Empty et Null sont ignorés.
SF_Array.Contains(Array_1D, ToFind As Variant, [CaseSensitive As Boolean], [SortOrder As String]) As Boolean
Array_1D : la matrice à scanner.
ToFind : un nombre, une date ou une chaîne à trouver.
CaseSensitive : uniquement pour une comparaison de chaînes, par défaut = False.
SortOrder : "ASC", "DESC" ou "" (= non trié, par défaut)
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
Stocker le contenu d'une matrice de deux colonnes dans un objet ScriptForge.Dictionary . Les clés seront extraites de la première colonne et les éléments de la seconde.
SF_Array.ConvertToDictionary(Array_2D As Variant) As Variant
Array_1D : la première colonne doit contenir exclusivement des chaînes dont la longueur est > 0, dans n'importe quel 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
Compter le nombre de dimensions d'une matrice. Le résultat peut être supérieur à deux.
Si l'argument n'est pas une matrice, renvoie -1
Si la matrice n'est pas initialisée, renvoie 0.
SF_Array.CountDims(Array_ND As Variant) As Integer
Array_ND : la matrice à examiner.
Sub Example_CountDims()
Dim a(1 To 10, -3 To 12, 5)
MsgBox SF_Array.CountDims(a) ' 3
End Sub
Construisez un ensemble, dont la matrice est basée sur 0, en utilisant l'opérateur de différence sur les deux matrices d'entrée. Les éléments résultants viendront du premier tableau et non du second.
La matrice résultante est triée par ordre croissant.
Les deux matrices d'entrée doivent être remplies avec homogénéité, leurs éléments doivent être des scalaires de même type. Les valeurs Empty et Null ne sont pas permises.
La comparaison de texte peut être sensible à la casse ou non.
SF_Array.Difference(Array1_1D As Variant, Array2_1D As Variant[, CaseSensitive As Boolean]) As Variant
Array1_1D : A 1 dimension reference array, whose items are examined for removal.
Array2_1D : A 1 dimension array, whose items are subtracted from the first input array.
CaseSensitive : Only if the arrays are populated with strings, default = False.
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
Write all items of the array sequentially to a text file. If the file exists already, it will be overwritten without warning.
SF_Array.ExportToTextFile(Array_1D As Variant, FileName As String, [Encoding As String]) As Boolean
Array_1D : The array to export. It must contain only strings.
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
Extract from a two dimension array a specific column as a new array.
Its lower LBound and upper UBound boundaries are identical to that of the first dimension of the input array.
SF_Array.ExtractColumn(Array_2D As Variant, ColumnIndex As Long) As Variant
Array_2D : The array from which to extract.
ColumnIndex : The column number to extract - must be in the interval [LBound, UBound].
Sub Example_ExtractColumn
'Creates a 3x3 matrix: |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))
'Extracts the third column: |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 : The array from which to extract.
RowIndex : The row number to extract - must be in the interval [LBound, UBound].
Sub Example_ExtractRow
'Creates a 3x3 matrix: |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))
'Extracts the first row: |1, 2, 3|
row = SF_Array.ExtractRow(mat, 0)
End Sub
Stack all single items of an array and all items in its subarrays into one new array without subarrays. Empty subarrays are ignored and subarrays with a number of dimensions greater than one are not flattened.
SF_Array.Flatten(Array_1D As Variant) As Variant
Array_1D : the pre-existing array, may be empty.
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