Ricerca…


Dichiarazione di una matrice in VBA

Dichiarare una matrice è molto simile alla dichiarazione di una variabile, tranne che è necessario dichiarare la dimensione della matrice subito dopo il suo nome:

Dim myArray(9) As String 'Declaring an array that will contain up to 10 strings

Per impostazione predefinita, gli array in VBA sono indicizzati da ZERO , quindi il numero all'interno della parentesi non si riferisce alla dimensione dell'array, ma piuttosto all'indice dell'ultimo elemento

Accesso agli elementi

L'accesso a un elemento dell'array viene effettuato utilizzando il nome dell'array, seguito dall'indice dell'elemento, tra parentesi:

myArray(0) = "first element"
myArray(5) = "sixth element"
myArray(9) = "last element"

Indicizzazione delle matrici

Puoi modificare l'indicizzazione degli array posizionando questa riga nella parte superiore di un modulo:

Option Base 1

Con questa linea, tutti gli array dichiarati nel modulo verranno indicizzati da ONE .

Indice specifico

È inoltre possibile dichiarare ciascuna matrice con il proprio indice utilizzando la parola chiave To e il limite inferiore e superiore (= indice):

Dim mySecondArray(1 To 12) As String 'Array of 12 strings indexed from 1 to 12
Dim myThirdArray(13 To 24) As String 'Array of 12 strings indexed from 13 to 24

Dichiarazione Dinamica

Quando non si conosce la dimensione della matrice prima della sua dichiarazione, è possibile utilizzare la dichiarazione dinamica e la parola chiave ReDim :

Dim myDynamicArray() As Strings 'Creates an Array of an unknown number of strings
ReDim myDynamicArray(5) 'This resets the array to 6 elements

Nota che l'uso della parola chiave ReDim cancellerà qualsiasi contenuto precedente della tua matrice. Per evitare ciò, è possibile utilizzare la parola chiave Preserve dopo ReDim :

Dim myDynamicArray(5) As String
myDynamicArray(0) = "Something I want to keep"

ReDim Preserve myDynamicArray(8) 'Expand the size to up to 9 strings
Debug.Print myDynamicArray(0) ' still prints the element

Uso di Split per creare una matrice da una stringa

Funzione Split

restituisce una matrice monodimensionale a base zero contenente un numero specificato di sottostringhe.

Sintassi

Dividi (espressione [, delimitatore [, limite [, confronta ]]] )

Parte Descrizione
espressione Necessario. Espressione di stringhe contenente sottostringhe e delimitatori. Se expression è una stringa di lunghezza zero ("" o vbNullString), Split restituisce un array vuoto che non contiene elementi e nessun dato. In questo caso, l'array restituito avrà un LBound di 0 e un UBound di -1.
delimitatore Opzionale. Carattere stringa utilizzato per identificare i limiti della sottostringa. Se omesso, si assume che il carattere dello spazio ("") sia il delimitatore. Se il delimitatore è una stringa di lunghezza zero, viene restituito un array a elemento singolo contenente l'intera stringa di espressione .
limite Opzionale. Numero di sottostringhe da restituire; -1 indica che tutte le sottostringhe vengono restituite.
confrontare Opzionale. Valore numerico che indica il tipo di confronto da utilizzare quando si valutano le sottostringhe. Vedi la sezione Impostazioni per i valori.

impostazioni

L'argomento di confronto può avere i seguenti valori:

Costante Valore Descrizione
Descrizione -1 Esegue un confronto utilizzando l'impostazione dell'istruzione Option Compare .
vbBinaryCompare 0 Esegue un confronto binario.
vbTextCompare 1 Esegue un confronto testuale.
vbDatabaseCompare 2 Solo Microsoft Access. Esegue un confronto in base alle informazioni nel database.

Esempio

In questo esempio è dimostrato come funziona Split mostrando diversi stili. I commenti mostreranno il set di risultati per ciascuna delle diverse opzioni di divisione eseguite. Infine, viene dimostrato come eseguire il looping sull'array di stringhe restituito.

Sub Test
    
    Dim textArray() as String

    textArray = Split("Tech on the Net")
    'Result: {"Tech", "on", "the", "Net"}

    textArray = Split("172.23.56.4", ".")
    'Result: {"172", "23", "56", "4"}

    textArray = Split("A;B;C;D", ";")
    'Result: {"A", "B", "C", "D"}

    textArray = Split("A;B;C;D", ";", 1)
    'Result: {"A;B;C;D"}

    textArray = Split("A;B;C;D", ";", 2)
    'Result: {"A", "B;C;D"}

    textArray = Split("A;B;C;D", ";", 3)
    'Result: {"A", "B", "C;D"}

    textArray = Split("A;B;C;D", ";", 4)
    'Result: {"A", "B", "C", "D"}

    'You can iterate over the created array
    Dim counter As Long

    For counter = LBound(textArray) To UBound(textArray)
        Debug.Print textArray(counter)
    Next
 End Sub

Iterazione di elementi di un array

Per il prossimo

L'uso della variabile iteratore come numero indice è il modo più veloce per iterare gli elementi di un array:

Dim items As Variant
items = Array(0, 1, 2, 3)

Dim index As Integer
For index = LBound(items) To UBound(items)
    'assumes value can be implicitly converted to a String:
    Debug.Print items(index) 
Next

I loop annidati possono essere utilizzati per iterare gli array multidimensionali:

Dim items(0 To 1, 0 To 1) As Integer
items(0, 0) = 0
items(0, 1) = 1
items(1, 0) = 2
items(1, 1) = 3

Dim outer As Integer
Dim inner As Integer
For outer = LBound(items, 1) To UBound(items, 1)
    For inner = LBound(items, 2) To UBound(items, 2)
        'assumes value can be implicitly converted to a String:
        Debug.Print items(outer, inner)
    Next
Next

Per ogni ... Avanti

Un ciclo For Each...Next può anche essere utilizzato per iterare gli array, se le prestazioni non contano:

Dim items As Variant
items = Array(0, 1, 2, 3)

Dim item As Variant 'must be variant
For Each item In items
    'assumes value can be implicitly converted to a String:
    Debug.Print item
Next

A For Each ciclo, itererà tutte le dimensioni da esterno a interno (lo stesso ordine con cui gli elementi sono disposti in memoria), quindi non c'è bisogno di cicli annidati:

Dim items(0 To 1, 0 To 1) As Integer
items(0, 0) = 0
items(1, 0) = 1
items(0, 1) = 2
items(1, 1) = 3

Dim item As Variant 'must be Variant
For Each item In items
    'assumes value can be implicitly converted to a String:
    Debug.Print item
Next

Si noti che For Each ciclo I cicli vengono utilizzati al meglio per iterare gli oggetti Collection , se le prestazioni sono importanti.


Tutti e 4 i frammenti sopra producono lo stesso risultato:

 0
 1
 2
 3

Array dinamici (ridimensionamento della matrice e gestione dinamica)

Matrici dinamiche

Aggiungere e ridurre variabili su un array in modo dinamico è un enorme vantaggio per quando le informazioni che si stanno trattando non hanno un determinato numero di variabili.

Aggiunta di valori in modo dinamico

Puoi semplicemente ridimensionare l'array con l'istruzione ReDim , questo ridimensionerà l'array ma se tu che conservi le informazioni già memorizzate nell'array avrai bisogno della parte Preserve .

Nell'esempio seguente creiamo una matrice e la aumentiamo di un'altra variabile in ogni iterazione, preservando i valori già presenti nella matrice.

Dim Dynamic_array As Variant
' first we set Dynamic_array as variant

For n = 1 To 100

    If IsEmpty(Dynamic_array) Then
        'isempty() will check if we need to add the first value to the array or subsequent ones
    
        ReDim Dynamic_array(0)
        'ReDim Dynamic_array(0) will resize the array to one variable only
        Dynamic_array(0) = n

    Else
        ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) + 1)
        'in the line above we resize the array from variable 0 to the UBound() = last variable, plus one effectivelly increeasing the size of the array by one
        Dynamic_array(UBound(Dynamic_array)) = n
        'attribute a value to the last variable of Dynamic_array
    End If

Next

Rimozione dei valori in modo dinamico

Possiamo utilizzare la stessa logica per diminuire la matrice. Nell'esempio il valore "last" sarà rimosso dall'array.

Dim Dynamic_array As Variant
Dynamic_array = Array("first", "middle", "last")
    
ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) - 1)
' Resize Preserve while dropping the last value

Ripristino di una matrice e riutilizzo dinamico

Possiamo anche riutilizzare gli array che creiamo per non avere molti in memoria, il che rallenterebbe il tempo di esecuzione. Questo è utile per gli array di varie dimensioni. Uno snippet che è possibile utilizzare per riutilizzare l'array è ReDim l'array a (0) , attribuire una variabile all'array e aumentare nuovamente l'array.

Nello snippet seguente costruisco un array con i valori da 1 a 40, svuota l'array e riempi l'array con valori da 40 a 100, il tutto fatto dinamicamente.

Dim Dynamic_array As Variant

For n = 1 To 100

    If IsEmpty(Dynamic_array) Then
        ReDim Dynamic_array(0)
        Dynamic_array(0) = n
    
    ElseIf Dynamic_array(0) = "" Then
        'if first variant is empty ( = "") then give it the value of n
        Dynamic_array(0) = n
    Else
        ReDim Preserve Dynamic_array(0 To UBound(Dynamic_array) + 1)
        Dynamic_array(UBound(Dynamic_array)) = n
    End If
    If n = 40 Then
        ReDim Dynamic_array(0)
        'Resizing the array back to one variable without Preserving,
        'leaving the first value of the array empty
    End If

Next

Array frastagliati (array di array)

Matrici frastagliate senza matrici multidimensionali

Le matrici di array (matrici frastagliate) non sono le stesse di matrici multidimensionali se si pensa a esse visivamente le matrici multidimensionali apparirebbero come matrici (rettangolari) con un numero definito di elementi sulle loro dimensioni (all'interno di matrici), mentre l'array frastagliato sarebbe come un anno calendario con gli array interni che hanno un numero diverso di elementi, come i giorni in diversi mesi.

Sebbene gli Jagged Array siano piuttosto disordinati e difficili da usare a causa dei livelli nidificati e non hanno molta sicurezza di tipo, ma sono molto flessibili, ti permettono di manipolare diversi tipi di dati abbastanza facilmente, e non c'è bisogno di contenere inutilizzati o elementi vuoti.

Creazione di una matrice seghettata

Nell'esempio seguente inizializzeremo un array frastagliato contenente due array uno per Names e un altro per Numbers, e quindi accedendo a un elemento di ciascun

Dim OuterArray() As Variant
Dim Names() As Variant
Dim Numbers() As Variant
'arrays are declared variant so we can access attribute any data type to its elements

Names = Array("Person1", "Person2", "Person3")
Numbers = Array("001", "002", "003")

OuterArray = Array(Names, Numbers)
'Directly giving OuterArray an array containing both Names and Numbers arrays inside

Debug.Print OuterArray(0)(1)
Debug.Print OuterArray(1)(1)
'accessing elements inside the jagged by giving the coordenades of the element

Creare e leggere dinamicamente array frastagliati

Possiamo anche essere più dinamici nella nostra approssimazione per costruire gli array, immaginare di avere una scheda tecnica del cliente in Excel e vogliamo costruire una matrice per produrre i dettagli del cliente.

   Name -   Phone   -  Email  - Customer Number 
Person1 - 153486231 - 1@STACK - 001
Person2 - 153486242 - 2@STACK - 002
Person3 - 153486253 - 3@STACK - 003
Person4 - 153486264 - 4@STACK - 004
Person5 - 153486275 - 5@STACK - 005

Costruiremo dinamicamente un array Header e un array Customers, l'intestazione conterrà i titoli delle colonne e l'array Customers conterrà le informazioni di ogni cliente / riga come array.

Dim Headers As Variant
' headers array with the top section of the customer data sheet
    For c = 1 To 4
        If IsEmpty(Headers) Then
            ReDim Headers(0)
            Headers(0) = Cells(1, c).Value
        Else
            ReDim Preserve Headers(0 To UBound(Headers) + 1)
            Headers(UBound(Headers)) = Cells(1, c).Value
        End If
    Next
    
Dim Customers As Variant
'Customers array will contain arrays of customer values
Dim Customer_Values As Variant
'Customer_Values will be an array of the customer in its elements (Name-Phone-Email-CustNum)
    
    For r = 2 To 6
    'iterate through the customers/rows
        For c = 1 To 4
        'iterate through the values/columns
            
            'build array containing customer values
            If IsEmpty(Customer_Values) Then
                ReDim Customer_Values(0)
                Customer_Values(0) = Cells(r, c).Value
            ElseIf Customer_Values(0) = "" Then
                Customer_Values(0) = Cells(r, c).Value
            Else
                ReDim Preserve Customer_Values(0 To UBound(Customer_Values) + 1)
                Customer_Values(UBound(Customer_Values)) = Cells(r, c).Value
            End If
        Next
        
        'add customer_values array to Customers Array
        If IsEmpty(Customers) Then
            ReDim Customers(0)
            Customers(0) = Customer_Values
        Else
            ReDim Preserve Customers(0 To UBound(Customers) + 1)
            Customers(UBound(Customers)) = Customer_Values
        End If
        
        'reset Custumer_Values to rebuild a new array if needed
        ReDim Customer_Values(0)
    Next

    Dim Main_Array(0 To 1) As Variant
    'main array will contain both the Headers and Customers
    
    Main_Array(0) = Headers
    Main_Array(1) = Customers

To better understand the way to Dynamically construct a one dimensional array please check Dynamic Arrays (Array Resizing and Dynamic Handling) on the Arrays documentation.

Il risultato del frammento di cui sopra è un Jagged Array con due array uno di quegli array con 4 elementi, 2 livelli di indention, e l'altro essendo esso stesso un altro Jagged Array contenente 5 array di 4 elementi ciascuno e 3 livelli di indention, vedi sotto la struttura:

Main_Array(0) - Headers - Array("Name","Phone","Email","Customer Number")
          (1) - Customers(0) - Array("Person1",153486231,"1@STACK",001)
                Customers(1) - Array("Person2",153486242,"2@STACK",002)
                ...
                Customers(4) - Array("Person5",153486275,"5@STACK",005)

Per accedere alle informazioni devi tenere a mente la struttura del Jagged Array che crei, nell'esempio sopra puoi vedere che l' Main Array contiene una Array di Headers e una Matrice di Array ( Customers ) quindi con diversi modi di accedere agli elementi.

Ora leggeremo le informazioni del Main Array e stamperemo ciascuna informazione del cliente come Info Type: Info .

For n = 0 To UBound(Main_Array(1))
    'n to iterate from fisrt to last array in Main_Array(1)
    
    For j = 0 To UBound(Main_Array(1)(n))
        'j will iterate from first to last element in each array of Main_Array(1)
        
        Debug.Print Main_Array(0)(j) & ": " & Main_Array(1)(n)(j)
        'print Main_Array(0)(j) which is the header and Main_Array(0)(n)(j) which is the element in the customer array
        'we can call the header with j as the header array has the same structure as the customer array
    Next
Next

RICORDA di tenere traccia della struttura del tuo Jagged Array, nell'esempio sopra per accedere al Nome di un cliente è accedendo a Main_Array -> Customers -> CustomerNumber -> Name che è di tre livelli, per restituire "Person4" cui avrai bisogno la posizione dei clienti nell'array principale, quindi la posizione del cliente quattro nell'array Jagged dei clienti e infine la posizione dell'elemento necessario, in questo caso Main_Array(1)(3)(0) che è Main_Array(Customers)(CustomerNumber)(Name) .

Array multidimensionali

Array multidimensionali

Come indica il nome, gli array multidimensionali sono matrici che contengono più di una dimensione, di solito due o tre, ma possono avere fino a 32 dimensioni.

Un multi array funziona come una matrice con vari livelli, prendi ad esempio un confronto tra una, due e tre dimensioni.

Una dimensione è la tipica matrice, sembra una lista di elementi.

Dim 1D(3) as Variant

*1D - Visually*
(0)
(1)
(2)

Due dimensioni apparirebbero come una griglia Sudoku o un foglio Excel, quando inizializzando l'array si definirebbe quante righe e colonne avrebbe la matrice.

Dim 2D(3,3) as Variant
'this would result in a 3x3 grid 

*2D - Visually*
(0,0) (0,1) (0,2)
(1,0) (1,1) (1,2)
(2,0) (2,1) (2,2)

Tre dimensioni comincerebbero ad assomigliare a Cubo di Rubik, quando inizializzando l'array si definirebbero righe e colonne e livelli / profondità che l'array avrebbe.

Dim 3D(3,3,2) as Variant
'this would result in a 3x3x3 grid

*3D - Visually*
       1st layer                 2nd layer                  3rd layer
         front                     middle                     back
(0,0,0) (0,0,1) (0,0,2) ¦ (1,0,0) (1,0,1) (1,0,2) ¦ (2,0,0) (2,0,1) (2,0,2)
(0,1,0) (0,1,1) (0,1,2) ¦ (1,1,0) (1,1,1) (1,1,2) ¦ (2,1,0) (2,1,1) (2,1,2)
(0,2,0) (0,2,1) (0,2,2) ¦ (1,2,0) (1,2,1) (1,2,2) ¦ (2,2,0) (2,2,1) (2,2,2)

Ulteriori dimensioni potrebbero essere pensate come la moltiplicazione del 3D, quindi un 4D (1,3,3,3) sarebbe costituito da due array 3D affiancati.


Matrice a due dimensioni

Creazione

L'esempio seguente sarà una raccolta di un elenco di dipendenti, ciascun dipendente avrà una serie di informazioni sulla lista (Nome, Cognome, Indirizzo, Email, Telefono ...), l'esempio sarà essenzialmente memorizzato sull'array ( dipendente, informazione) essendo il (0,0) è il primo nome del primo dipendente.

Dim Bosses As Variant
'set bosses as Variant, so we can input any data type we want

Bosses = [{"Jonh","Snow","President";"Ygritte","Wild","Vice-President"}]
'initialise a 2D array directly by filling it with information, the redult wil be a array(1,2) size 2x3 = 6 elements

Dim Employees As Variant
'initialize your Employees array as variant
'initialize and ReDim the Employee array so it is a dynamic array instead of a static one, hence treated differently by the VBA Compiler
ReDim Employees(100, 5)
'declaring an 2D array that can store 100 employees with 6 elements of information each, but starts empty
'the array size is 101 x 6 and contains 606 elements

For employee = 0 To UBound(Employees, 1)
'for each employee/row in the array, UBound for 2D arrays, which will get the last element on the array
'needs two parameters 1st the array you which to check and 2nd the dimension, in this case 1 = employee and 2 = information
    For information_e = 0 To UBound(Employees, 2)
    'for each information element/column in the array
        
        Employees(employee, information_e) = InformationNeeded ' InformationNeeded would be the data to fill the array
        'iterating the full array will allow for direct attribution of information into the element coordinates
    Next
Next

Ridimensionamento

Ridimensionare o ReDim Preserve un Multi-Array come la norma per un array a una dimensione otterrebbe un errore, invece le informazioni devono essere trasferite in un array temporaneo con le stesse dimensioni dell'originale più il numero di righe / colonne da aggiungere. Nell'esempio seguente vedremo come inizializzare un array di temp, trasferire le informazioni dall'array originale, riempire gli elementi vuoti rimanenti e sostituire l'array temp con l'array originale.

Dim TempEmp As Variant
'initialise your temp array as variant
ReDim TempEmp(UBound(Employees, 1) + 1, UBound(Employees, 2))
'ReDim/Resize Temp array as a 2D array with size UBound(Employees)+1 = (last element in Employees 1st dimension) + 1,
'the 2nd dimension remains the same as the original array. we effectively add 1 row in the Employee array

'transfer
For emp = LBound(Employees, 1) To UBound(Employees, 1)
    For info = LBound(Employees, 2) To UBound(Employees, 2)
        'to transfer Employees into TempEmp we iterate both arrays and fill TempEmp with the corresponding element value in Employees
        TempEmp(emp, info) = Employees(emp, info)
    
    Next
Next

'fill remaining
'after the transfers the Temp array still has unused elements at the end, being that it was increased
'to fill the remaining elements iterate from the last "row" with values to the last row in the array
'in this case the last row in Temp will be the size of the Employees array rows + 1, as the last row of Employees array is already filled in the TempArray

For emp = UBound(Employees, 1) + 1 To UBound(TempEmp, 1)
    For info = LBound(TempEmp, 2) To UBound(TempEmp, 2)
        
        TempEmp(emp, info) = InformationNeeded & "NewRow"
    
    Next
Next

'erase Employees, attribute Temp array to Employees and erase Temp array
Erase Employees
Employees = TempEmp
Erase TempEmp

Modifica dei valori degli elementi

Per cambiare / modificare i valori in un determinato elemento si può fare semplicemente chiamando la coordinata per cambiarla e assegnandole un nuovo valore: Employees(0, 0) = "NewValue"

In alternativa, scorrere le coordinate per utilizzare le condizioni per abbinare i valori corrispondenti ai parametri necessari:

For emp = 0 To UBound(Employees)
    If Employees(emp, 0) = "Gloria" And Employees(emp, 1) = "Stephan" Then
    'if value found
        Employees(emp, 1) = "Married, Last Name Change"
        Exit For
        'don't iterate through a full array unless necessary
    End If
Next

Lettura

L'accesso agli elementi dell'array può essere fatto con un ciclo annidato (iterando ogni elemento), loop e coordinate (iterare le righe e accedere direttamente alle colonne) o accedere direttamente con entrambe le coordinate.

'nested loop, will iterate through all elements
For emp = LBound(Employees, 1) To UBound(Employees, 1)
    For info = LBound(Employees, 2) To UBound(Employees, 2)
        Debug.Print Employees(emp, info)
    Next
Next

'loop and coordinate, iteration through all rows and in each row accessing all columns directly
For emp = LBound(Employees, 1) To UBound(Employees, 1)
    Debug.Print Employees(emp, 0)
    Debug.Print Employees(emp, 1)
    Debug.Print Employees(emp, 2)
    Debug.Print Employees(emp, 3)
    Debug.Print Employees(emp, 4)
    Debug.Print Employees(emp, 5)
Next

'directly accessing element with coordinates
Debug.Print Employees(5, 5)

Ricorda , è sempre utile mantenere una mappa di array quando si usano array multidimensionali, possono facilmente diventare confusione.


Matrice a tre dimensioni

Per l'array 3D, utilizzeremo la stessa premessa dell'array 2D, con l'aggiunta non solo di memorizzazione di Employee e Information ma anche di Building in cui lavorano.

L'array 3D avrà i Dipendenti (possono essere considerati come Righe), le Informazioni (Colonne) e Edificio che possono essere pensati come fogli diversi su un documento Excel, hanno le stesse dimensioni tra di loro, ma ogni foglio ha un diverso insieme di informazioni nelle sue cellule / elementi. L'array 3D conterrà n numero di array 2D.

Creazione

Un array 3D necessita di 3 coordinate da inizializzare. Dim 3Darray(2,5,5) As Variant la prima coordinata dell'array sarà il numero di Building / Sheets (diversi gruppi di righe e colonne), la seconda coordinata definirà Rows e il terzo colonne. La Dim sopra si tradurrà in un array 3D con 108 elementi ( 3*6*6 ), con 3 diversi set di array 2D.

Dim ThreeDArray As Variant
'initialise your ThreeDArray array as variant
ReDim ThreeDArray(1, 50, 5)
'declaring an 3D array that can store two sets of 51 employees with 6 elements of information each, but starts empty
'the array size is 2 x 51 x 6 and contains 612 elements

For building = 0 To UBound(ThreeDArray, 1)
    'for each building/set in the array
    For employee = 0 To UBound(ThreeDArray, 2)
    'for each employee/row in the array
        For information_e = 0 To UBound(ThreeDArray, 3)
        'for each information element/column in the array
            
            ThreeDArray(building, employee, information_e) = InformationNeeded ' InformationNeeded would be the data to fill the array
        'iterating the full array will allow for direct attribution of information into the element coordinates
        Next
    Next
Next

Ridimensionamento

Il ridimensionamento di un array 3D è simile al ridimensionamento di un 2D, in primo luogo creare un array temporaneo con le stesse dimensioni dell'originale aggiungendo uno nella coordinata del parametro per aumentare, la prima coordinata aumenterà il numero di set nell'array, il secondo e le terze coordinate aumenteranno il numero di righe o colonne in ciascun set.

L'esempio seguente aumenta il numero di Righe in ciascun set di uno e riempie gli elementi aggiunti di recente con nuove informazioni.

Dim TempEmp As Variant
'initialise your temp array as variant
ReDim TempEmp(UBound(ThreeDArray, 1), UBound(ThreeDArray, 2) + 1, UBound(ThreeDArray, 3))
'ReDim/Resize Temp array as a 3D array with size UBound(ThreeDArray)+1 = (last element in Employees 2nd dimension) + 1,
'the other dimension remains the same as the original array. we effectively add 1 row in the for each set of the 3D array

'transfer
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
    For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
        For info = LBound(ThreeDArray, 3) To UBound(ThreeDArray, 3)
            'to transfer ThreeDArray into TempEmp by iterating all sets in the 3D array and fill TempEmp with the corresponding element value in each set of each row
            TempEmp(building, emp, info) = ThreeDArray(building, emp, info)
        
        Next
    Next
Next

'fill remaining
'to fill the remaining elements we need to iterate from the last "row" with values to the last row in the array in each set, remember that the first empty element is the original array Ubound() plus 1
For building = LBound(TempEmp, 1) To UBound(TempEmp, 1)
    For emp = UBound(ThreeDArray, 2) + 1 To UBound(TempEmp, 2)
        For info = LBound(TempEmp, 3) To UBound(TempEmp, 3)
            
            TempEmp(building, emp, info) = InformationNeeded & "NewRow"
        
        Next
    Next
Next

'erase Employees, attribute Temp array to Employees and erase Temp array
Erase ThreeDArray
ThreeDArray = TempEmp
Erase TempEmp

Modifica dei valori degli elementi e lettura

Leggere e modificare gli elementi sull'array 3D può essere fatto in modo simile al modo in cui facciamo l'array 2D, basta regolarlo per il livello extra nei loop e nelle coordinate.

Do
' using Do ... While for early exit
    For building = 0 To UBound(ThreeDArray, 1)
        For emp = 0 To UBound(ThreeDArray, 2)
            If ThreeDArray(building, emp, 0) = "Gloria" And ThreeDArray(building, emp, 1) = "Stephan" Then
            'if value found
                ThreeDArray(building, emp, 1) = "Married, Last Name Change"
                Exit Do
                'don't iterate through all the array unless necessary
            End If
        Next
    Next
Loop While False

'nested loop, will iterate through all elements
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
    For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
        For info = LBound(ThreeDArray, 3) To UBound(ThreeDArray, 3)
            Debug.Print ThreeDArray(building, emp, info)
        Next
    Next
Next

'loop and coordinate, will iterate through all set of rows and ask for the row plus the value we choose for the columns
For building = LBound(ThreeDArray, 1) To UBound(ThreeDArray, 1)
    For emp = LBound(ThreeDArray, 2) To UBound(ThreeDArray, 2)
        Debug.Print ThreeDArray(building, emp, 0)
        Debug.Print ThreeDArray(building, emp, 1)
        Debug.Print ThreeDArray(building, emp, 2)
        Debug.Print ThreeDArray(building, emp, 3)
        Debug.Print ThreeDArray(building, emp, 4)
        Debug.Print ThreeDArray(building, emp, 5)
    Next
Next

'directly accessing element with coordinates
Debug.Print Employees(0, 5, 5)


Modified text is an extract of the original Stack Overflow Documentation
Autorizzato sotto CC BY-SA 3.0
Non affiliato con Stack Overflow