In diesem Artikel
- Verwendung einer VBA-Array-Liste
- Verteilen Ihrer Excel-Anwendung, die eine Array-Liste enthält
- Umfang eines Array-Listenobjekts
- Auffüllen und Auslesen Ihrer Array-Liste
- Elemente in einer Array-Liste bearbeiten und ändern
- Ein Array von Werten zu einer Array-Liste hinzufügen
- Einen Bereich von Elementen aus einer Array-Liste auslesen/abrufen
- Suche nach Elementen innerhalb einer Array-Liste
- Elemente einfügen und entfernen
- Eine Array-Liste sortieren
- Eine Array-Liste klonen
- Eine Array-Liste in ein herkömmliches VBA-Array-Objekt hineinkopieren
- Eine Array-Liste in einen Arbeitsblattbereich hineinkopieren
- Alle Elemente aus einer Array-Liste löschen
- Methoden der Array-Liste – Zusammenfassung für Excel VBA
Verwendung einer VBA-Array-Liste
Eine Array-Liste ist ein VBA-Objekt, das zum Speichern von Werten verwendet werden kann. Es ist einemSammlungsobjektähnlich, ist aber aus programmiertechnischer Sicht wesentlich flexibler. Lassen Sie uns einige Unterschiede zwischen Array-Listen,Sammlungen undArraysdiskutieren.
- Das Sammlungsobjekt hat nur zwei Methoden (Add, Remove) und zwei Eigenschaften (Count, Item), während eine Array-Liste über viel mehr verfügt.
- Das Sammlungsobjekt ist schreibgeschützt. Sobald Werte hinzugefügt wurden, kann der indizierte Wert nicht mehr geändert werden, während eine Bearbeitung bei einer Array-Liste möglich ist.
- Das Array-Listenobjekt vergrößert und verkleinert sich je nach Anzahl der darin enthaltenen Elemente. Es muss vor der Verwendung nicht wie ein Array dimensioniert werden.
- Die Array-Liste ist eindimensional (wie das Sammlungsobjekt) und der Standard-Datentyp istVariante, was bedeutet, dass sie jeden Datentyp akzeptiert, egal ob es sich um Zahlen, Text oder Datum handelt.
In vielerlei Hinsicht behebt die Array-Liste eine Reihe von Mängeln des Sammlungsobjekts. Sie ist sicherlich viel flexibler in ihren Möglichkeiten.
Das Array-Listenobjekt ist nicht Teil der Standard-VBA-Bibliothek. Sie können es in Ihrem Excel-VBA-Code verwenden, indem Sie diespäte oder frühe Bindungnutzen.
Sub SpaeteBindungBeispiel()Dim MeineListe As ObjectSet MeineListe = CreateObject("System.Collections.ArrayList")End Sub
Sub FrueheBindungBeispiel()Dim MeineListe As New ArrayListEnd Sub
Um das Beispiel zur frühen Bindung zu verwenden, müssen Sie zunächstin VBAeinenVerweisauf die Datei „mscorlib.tlb“ eingeben.
Wählen Sie dazu im Fenster desVisual Basic-Editor (VBE)die Option „Extras | Verweise“. Es erscheint ein Pop-up-Fenster mit allen verfügbaren Verweisen. Scrollen Sie nach unten zu ‚mscorlib.dll‘ und markieren Sie das Kästchen daneben. Klicken Sie auf OK und diese Bibliothek ist nun Teil Ihres Projekts:
Einer der großen Nachteile eines Array-Listenobjekts ist die Tatsache, dass es keine „IntelliSense“ hat. Normalerweise sehen Sie bei der Verwendung eines Objekts in VBA, z. B. eines Bereichs, eine Popup-Liste mit allen verfügbaren Eigenschaften und Methoden. Bei einem Array-Listenobjekt ist dies nicht der Fall und manchmal müssen Sie sorgfältig prüfen, ob Sie die Methode oder Eigenschaft richtig geschrieben haben.
Auch wenn Sie im VBE-Fenster die Taste F2 drücken und nach „arraylist“ suchen, wird nichts angezeigt, was für den Entwickler nicht sehr hilfreich ist.
Ihr Code wird mit der frühen Bindung wesentlich schneller laufen, da alles im Voraus kompiliert wird. Bei der späten Bindung muss das Objekt kompiliert werden, während der Code aufgeführt wird.
Verteilen Ihrer Excel-Anwendung, die eine Array-Liste enthält
Wie bereits erwähnt, ist das Array-Listenobjekt nicht Teil von Excel VBA. Das bedeutet, dass jeder Ihrer Kollegen, an den Sie die Anwendung weitergeben, Zugriff auf die Datei ‚mscorlib.tlb‘ haben muss.
Diese Datei befindet sich normalerweise unter:C:\Windows\Microsoft.NET\Framework\v4.0.30319
Es könnte sich lohnen, etwas Code zu schreiben (unter Verwendung derDir-Methode), einszu prüfen, ob diese Datei vorhanden ist, wenn ein Benutzer die Anwendung lädt, damit er eine „weiche Landung“ erlebt, wenn sie nicht gefunden wird. Wenn sie nicht vorhanden ist und der Code ausgeführt wird, treten Fehler auf.
Außerdem muss der Benutzer die richtige Version von .Net Framework installiert haben. Selbst wenn der Benutzer eine neuere Version hat, muss V3.5 installiert sein, sonst funktioniert Ihre Anwendung nicht.
Umfang eines Array-Listenobjekts
Das Array-Listenobjekt ist nur verfügbar, solange die Arbeitsmappe geöffnet ist. Es wird nicht gespeichert, wenn die Arbeitsmappe gespeichert wird. Wenn die Arbeitsmappe erneut geöffnet wird, muss das Array-Listenobjekt mit VBA-Code neu erstellt werden.
Wenn Sie möchten, dass Ihre Array-Liste für den gesamten Code in Ihrem Code-Modul zur Verfügung steht, müssen Sie das Array-Listenobjekt im Declare-Abschnitt ganz oben im Modulfenster deklarieren
Dadurch wird sichergestellt, dass der gesamte Code in diesem Modul auf die Array-Liste zugreifen kann. Wenn Sie möchten, dass jedes Modul innerhalb Ihrer Arbeitsmappe auf das Array-Listenobjekt zugreifen kann, dann definieren Sie es alsglobales Objekt.
Global MeineSammlung As New ArrayList
Auffüllen und Auslesen Ihrer Array-Liste
Die grundlegendeste Aktion, die Sie durchführen möchten, besteht darin, eine Array-Liste zu erstellen, einige Daten darin zu speichern und dann nachzuweisen, dass die Daten gelesen werden können. Alle Codebeispiele in diesem Artikel gehen davon aus, dass Sie die frühe Bindung verwenden und „mscorlib.tlb“ zu den VBA-Verweisen wie oben beschrieben hinzugefügt haben.
Sub ArrayListeBeispiel()'Neues Array-Listenobjekt erstellenDim MeineListe As New ArrayList'Elemente zur Liste hinzufügenMeineListe.Add "Element1"MeineListe.Add "Element2"MeineListe.Add "Element3"'Durch die Array-Liste iterieren, um Werte zu prüfenFor N = 0 To MeineListe.Count - 1 MsgBox MeineListe(N)Next NEnd Sub
In diesem Beispiel wird ein neues Array-Listenobjekt erstellt, das mit 3 Elementen aufgefüllt wird, und dann wird die Liste durchlaufen, wobei jedes Element angezeigt wird.
Beachten Sie, dass der Array-Listenindex bei 0 und nicht bei 1 beginnt, so dass Sie 1 vom Count-Wert subtrahieren müssen.
Sie können auch eine‚Für…Jeden‘-Schleifeverwenden, um die Werte auszulesen:
Sub ArrayListeBeispiel()'Neues ArrayList-Objekt erstellenDim MeineListe As New ArrayList'Elemente zur Liste hinzufügenMeineListe.Add "Element1"MeineListe.Add "Element2"MeineListe.Add "Element3"'Durch die Array-Liste iterieren, um Werte zu prüfenFor Each I In MeineListe MsgBox INext IEnd Sub
Elemente in einer Array-Liste bearbeiten und ändern
Ein großer Vorteil einer Array-Liste gegenüber einer Sammlung besteht darin, dass die Elemente in der Liste innerhalb Ihres Codes bearbeitet und geändert werden können. Das Sammlungsobjekt ist nur lesbar, während das Array-Listenobjekt schreib- und lesefähig ist.
Sub ArrayListeBeispiel()'Neues Array-Listenobjekt erstellenDim MeineListe As New ArrayList'Elemente zur Liste hinzufügenMeineListe.Add "Element1"MeineListe.Add "Element2"MeineListe.Add "Element3"'Eintrag 1 von 'Eintrag2' auf 'Geändert' ändernMeineListe(1) = "Geändert"'Durch die Array-Liste iterieren, um nachzuweisen, dass die Änderung stattgefunden hatFor Each I In MeineListe 'Name des Elements anzeigen MsgBox INext IEnd Sub
In diesem Beispiel wird das zweite Element („Element2“) auf den Wert „Geändert“ geändert (der Index beginnt bei 0). Wenn die Iteration am Ende des Codes ausgeführt wird, wird der neue Wert angezeigt.
Ein Array von Werten zu einer Array-Liste hinzufügen
Sie können Werte in Ihre Array-Liste einfügen, indem Sie ein Array, das eine Liste dieser Werte oder Verweise auf Zellenwerte in einem Arbeitsblatt enthält, verwenden.
Sub ArrayHinzufuegenBeispiel()'Array-Listenobjekt erstellenDim MeineListe As New ArrayList'Durch Array-Werte iterieren und sie der Array-Liste hinzufügenFor Each W In Array("A1", "A2", "A3") 'Jeden Array-Wert zur Liste hinzufügen MeineListe.Add WNext'Array-Werte mit Arbeitsblattverweisen durchlaufen und zur Array-Liste hinzufügenFor Each W In Array(Range("A5").Value, Range("A6").Value) MeineListe.Add WNext'Durch die Array-Liste iterieren, um die Werte zu prüfenFor N = 0 To MeineListe.Count - 1 'Listenelement anzeigen MsgBox MeineListe.Item(N)Next NEnd Sub
Einen Bereich von Elementen aus einer Array-Liste auslesen/abrufen
Durch Anwendung der GetRange-Methode an einer Array-Liste können Sie einen Bereich von aufeinanderfolgenden Elementen, die abgerufen werden sollen, angeben. Die beiden erforderlichen Parameter sind die Startindexposition und die Anzahl der abzurufenden Elemente. Der Code füllt ein zweites Array-Listenobjekt mit der Teilmenge von Elementen, die dann separat gelesen werden können.
Sub BereichLesenExample()'Objekte definierenDim MeineListe As New ArrayList, MeineListe1 As Object'Elemente zum Objekt 'MeineListe' hinzufügenMeineListe.Add "Element1"MeineListe.Add "Element2"MeineListe.Add "Element3"MeineListe.Add "Element6"MeineListe.Add "Element4"MeineListe.Add "Element7"'4 Elementen in 'MeineListe' ab Indexposition 2 erfassenSet MeineListe1 = MeineListe.GetRange(2, 4)'Durch das Objekt "MeineListe1" iterieren, um die Teilmenge der Elemente anzuzeigenFor Each I In MeineListe1 'Name des Elements anzeigen MsgBox INext IEnd Sub
Suche nach Elementen innerhalb einer Array-Liste
Mit der Contains-Methode können Sie prüfen, ob ein bestimmtes Element in Ihrer Liste enthalten ist. Diese Methode gibtWAHRoderFALSCHzurück
MsgBox MeineListe.Contains("Element2")
Sie können auch die tatsächliche Indexposition mit der IndexOf-Methode ermitteln. Sie müssen den Startindex für die Suche angeben (normalerweise 0). Der Rückgabewert ist der Index der ersten Instanz des gesuchten Elements. Sie können dann eine Schleife verwenden, um den Startpunkt auf den nächsten Indexwert zu ändern, um weitere Instanzen zu finden, wenn es mehrere doppelte Werte gibt.
Wenn der Wert nicht gefunden wird, wird der Wert -1 zurückgegeben.
Dieses Beispiel demonstriert die Verwendung von ‚Contains‘, Element nicht gefunden und Durchlaufen der Array-Liste, um die Positionen aller doppelten Elemente zu finden:
Sub SucheInListeBeispiel()'Array-Liste und Variablen definierenDim MeineListe As New ArrayList, Sp As Integer, Pos As Integer'Neue Elemente einschließlich eines Duplikats hinzufügenMeineListe.Add "Element1"MeineListe.Add "Element2"MeineListe.Add "Element3"MeineListe.Add "Element1"'Prüfen, ob "Element2" in der Liste enthalten ist - gibt True zurückMsgBox MeineListe.Contains("Element2")'Index eines nicht vorhandenen Wertes ermitteln - gibt -1 zurückMsgBox MeineListe.IndexOf("Element", 0)'Die Startposition für die Suche auf Null setzenSp = 0'Durch die Liste iterieren, um alle Positionen von "Element1" zu erhaltenDo 'Die Indexposition vom nächsten 'Element1' anhand der Position in der Variablen 'Sp' ermitteln Pos = MeineListe.IndexOf("Element1", Sp) 'Wenn keine weiteren Instanzen von 'Element1' gefunden werden, dann die Schleife verlassen If Pos = -1 Then Exit Do 'Die nächste gefundene Instanz und die Indexposition anzeigen MsgBox MeineListe(Pos) & " bei Index " & Pos '1 zum letzten gefundenen Indexwert hinzuaddieren - dies wird nun die neue Startposition für die nächste Suche Sp = Pos + 1LoopEnd Sub
Beachten Sie, dass der verwendete Suchtext zwischen Groß- und Kleinschreibung unterscheidet und Platzhalter nicht zulässig sind.
Elemente einfügen und entfernen
Wenn Sie Ihre Elemente nicht am Ende der Liste hinzufügen möchten, können Sie sie an einer bestimmten Indexposition einfügen, so dass das neue Element in der Mitte der Liste steht. Die Indexnummern werden für die nachfolgenden Einträge automatisch angepasst.
Sub EinfuegenBeispiel()'Array-Listenobjekt definierenDim MeineListe As New ArrayList'Elemente zur Array-Liste hinzufügenMeineListe.Add "Element1"MeineListe.Add "Element2"MeineListe.Add "Element3"MeineListe.Add "Element1"' 'Element6' an der Indexposition 2 einfügenMeineListe.Insert 2, "Element6"'Durch die Elemente in der Array-Liste iterieren, um die neue Reihenfolge und Indexpositionen anzuzeigenFor N = 0 To MeineListe.Count - 1 MsgBox MeineListe(N) & " Index " & NNext NEnd Sub
In diesem Beispiel wird „Element6“ an der Indexposition 2 in die Liste eingefügt, so dass „Element3“, das sich an der Indexposition 2 befand, nun an die Indexposition 3 verschoben wird.
Ein einzelnes Element kann mit der Remove-Methode entfernt werden.
MeineListe.Remove "Element"
Es ist zu beachten, dass es keinen Fehler gibt, wenn der Name des Elements nicht gefunden wird. Alle nachfolgenden Indexnummern werden gemäß diesem Entfernvorgang geändert.
Wenn Sie die Indexposition des Elements kennen, können Sie die RemoveAt-Methode verwenden, z. B.
MeineListe.RemoveAt 2
Beachten Sie, dass ein Fehler zurückgegeben wird, wenn die angegebene Indexposition größer als die Anzahl der Elemente in der Array-Liste ist.
Sie können einen Wertebereich aus der Liste entfernen, indem Sie die RemoveRange-Methode verwenden. Die Parameter sind der Startindex und dann die Anzahl der zu entfernenden Elemente, z.B.
MeineListe.RemoveRange 3, 2
Beachten Sie, dass Sie einen Fehler in Ihrem Code erhalten, wenn die Anzahl der Elemente ab dem Startwert größer ist als die Anzahl der Elemente in der Array-Liste ist.
Sowohl bei der RemoveAt- als auch bei der RemoveRange-Methode wäre es ratsam zu prüfen, ob die angegebenen Indexzahlen größer als die Gesamtzahl der Elemente in der Array-Liste sind, um mögliche Fehler abzufangen. Die Count-Eigenschaft gibt die Gesamtzahl der Elemente in der Array-Liste an.
Sub EntfernenBeispiel()'Array-Listenobjekt definierenDim MeineListe As New ArrayList'Elemente zur Array-Liste hinzufügenMeineListe.Add "Element1"MeineListe.Add "Element2"MeineListe.Add "Element3"MeineListe.Add "Element1"MeineListe.Add "Element4"MeineListe.Add "Element5"' 'Element6' an Indexposition 2 einfügenMeineListe.Insert 2, "Element6"'Element2' entfernenMeineListe.Remove "Element2"' 'Element' entfernen - dieses existiert nicht in der Array-Liste, macht aber keinen FehlerMeineListe.Remove "Element"'Das Element an der Indexposition 2 entfernenMeineListe.RemoveAt 2'2 aufeinanderfolgende Elemente ab der Indexposition 2 entfernenMeineListe.RemoveRange 3, 2'Durch die Array-Liste iterieren, um zu zeigen, was übrig ist und an welcher Indexposition es sich jetzt befindetFor N = 0 To MeineListe.Count - 1 MsgBox MeineListe(N) & " Index " & NNext NEnd Sub
Beachten Sie bei der Verwendung von „RemoveAt“ zum Entfernen eines Elements an einer bestimmten Position, dass alle nachfolgenden Indexpositionen geändert werden, sobald dieses Element entfernt wurde. Wenn Sie mehrere Elemente über die Indexposition entfernen, ist es eine gute Idee, mit der höchsten Indexnummer zu beginnen und rückwärts bis zur Position Null zu gehen, damit Sie immer das richtige Element entfernen. Auf diese Weise haben Sie das Problem nicht
Eine Array-Liste sortieren
Ein weiterer großer Vorteil gegenüber einer Sammlung ist die Tatsache, dass Sie die Elemente in aufsteigender oder absteigender Reihenfolge sortieren können.
Das Array-Listenobjekt ist das einzige Objekt inExcel-VBAmit einer Sortiermethode. Die Sortiermethode ist sehr schnell und dies kann ein wichtiger Aspekt bei der Verwendung einer Array-Liste sein.
Beim Sammlungsobjekt musste man sich etwas einfallen lassen, um alle Elemente zu sortieren, aber mit einer Array-Liste ist das sehr einfach.
Die Sort-Methode sortiert in aufsteigender Reihenfolge und die Reverse-Methode in absteigender Reihenfolge.
Sub ArrayListeBeispiel()'Array-Listenobjekt erstellenDim MeineListe As New ArrayList'Elemente in unsortierter Reihenfolge hinzufügenMeineListe.Add "Element1"MeineListe.Add "Element3"MeineListe.Add "Element2"'Die Elemente in aufsteigender Reihenfolge sortierenMeineListe.Sort'Durch die Elemente iterieren, um die aufsteigende Reihenfolge anzuzeigenFor Each I In MeineListe 'Name des Elements anzeigen MsgBox INext I'Die Elemente in absteigender Reihenfolge sortierenMeineListe.Reverse'Durch die Elemente iterieren, um die absteigende Reihenfolge anzuzeigenFor Each I In MeineListe 'Name des Elements anzeigen MsgBox INext IEnd Sub
Eine Array-Liste klonen
Eine Array-Liste hat die Möglichkeit, einen Klon oder eine Kopie von sich selbst zu erstellen. Dies ist nützlich, wenn der Benutzer über ein Frontend und Ihren VBA-Code Änderungen an den Elementen vornimmt, Sie aber eine Kopie der Elemente in ihrem ursprünglichen Zustand als Backup behalten müssen.
Dies könnte dem Benutzer eine Undo-Funktion bieten. Möglicherweise hat er die Änderungen vorgenommen und möchte zur ursprünglichen Liste zurückkehren.
Sub KlonenBeispiel()'Zwei Objekte definieren - eine Array-Liste und ein ObjektDim MeineListe As New ArrayList, MeineListe1 As Object'Erstes Objekt mit Elementen auffüllenMeineListe.Add "Element1"MeineListe.Add "Element2"MeineListe.Add "Element3"'MeineListe in MeineListe1 kopierenSet MeineListe1 = MeineListe.Clone'Durch MeineListe1 iterieren, um das Klonen nachzuweisenFor Each I In MeineListe1 'Namen des Elements anzeigen MsgBox INext IEnd Sub
MeineListe1″ enthält nun alle Elemente von „MeineListe“ in der gleichen Reihenfolge
Eine Array-Liste in ein herkömmliches VBA-Array-Objekt hineinkopieren
Sie können eine einfache Methode verwenden, um die Array-Liste in ein normales VBA-Array zu kopieren:
Sub ArrayBeispiel()'Array-Listenobjekt und ein Standard-Array-Objekt erstellenDim MeineListe As New ArrayList, NeuesArray As Variant'Array-Liste mit Elementen auffüllenMeineListe.Add "Element1"MeineListe.Add "Element2"MeineListe.Add "Element3"'Die Array-Liste in das neue Array kopierenNeuesArray = MeineListe.ToArray'Durch das neue Array Iterieren - beachten Sie, dass die Anzahl der Array-Listen den maximalen Index liefertFor N = 0 To MeineListe.Count - 1 'Namen des Elements anzeigen MsgBox NeuesArray(N)Next NEnd Sub
Eine Array-Liste in einen Arbeitsblattbereich hineinkopieren
Sie können Ihre Array-Liste in ein bestimmtes Arbeitsblatt und einen Zellenbezug hineinkopieren, ohne diese durchlaufen zu müssen. Sie müssen nur den ersten Zellenbezug angeben
Sub BereichBeispiel()'Neues Array-Listenobjekt erstellenDim MeineListe As New ArrayList'Elemente zur Liste hinzufügenMeineListe.Add "Element1"MeineListe.Add "Element2"MeineListe.Add "Element3"'Das Zielblatt leerenSheets("Tabelle1").UsedRange.Clear'Elemente in eine Zeile kopierenSheets("Tabelle1").Range("A1").Resize(1, MeineListe.Count).Value = MeineListe.toArray'Elemente in eine Spalte kopierenSheets("Tabelle1").Range("A5").Resize(MeineListe.Count, 1).Value = _WorksheetFunction.Transpose(MeineListe.toArray)End Sub
Alle Elemente aus einer Array-Liste löschen
Es gibt eine einfache Funktion (Clear), um die Array-Liste vollständig zu leeren.
Sub ListeLeerenBeispiel()'Array-Listenobjekt erstellenDim MeineListe As New ArrayList'Neue Elemente hinzufügenMeineListe.Add "Element1"MeineListe.Add "Element2"MeineListe.Add "Element3"'Anzahl der Elemente anzeigenMsgBox MeineListe.Count'Alle Einträge löschenMeineListe.Clear'Die Anzahl der Elemente anzeigen, um nachzuweisen, dass das Löschen funktioniert hatMsgBox MeineListe.CountEnd Sub
In diesem Beispiel werden Elemente in einer Array-Liste erstellt und dann wird diese geleert. Meldungsboxen zeigen Die Anzahl der Elemente in der Array-Liste von vorher und nachher.
Methoden derArray-Liste – Zusammenfassung für Excel VBA
Aufgabe | Parameter | Beispiele |
Element hinzufügen/bearbeiten | Wert | MeineListe.Add „Element1“ |
MeineListe(4)= „Element2“ | ||
Eine Array-Liste klonen | Keine | Dimmen Sie MyList als Objekt |
Set MeineListe2 = MeineListe.Clone | ||
In Array kopieren | Keine | Dim MeinArray als Variante |
MeinArray = MeineListe.ToArray | ||
In einen Arbeitsblattbereich (Zeile) kopieren | Keine | Sheets("Tabelle1").Range("A1").Resize(1, MeineListe.Count).Value = MeineListe.ToArray |
In einen Arbeitsblattbereich (Spalte) kopieren | Keine | Sheets("Tabelle1").Range("A3").Resize(MeineListe.Count, 1).Value = WorksheetFunction.Transpose(MeineListe.ToArray) |
Erstellen | „System.Collections.ArrayList“ | Dimmen Sie MyList als Objekt |
Setze MeineListe = CreateObject(„System.Collections.ArrayList“) | ||
Deklarieren | N / A | Dimmen Sie MyList als Objekt |
Suchen / Prüfen, ob Element existiert | Zu suchendes Element | MeineListe.Contains(„Element2“) |
Suche nach der Position eines Elements in der Array-Liste | 1. Zu suchendes Element. | Dim IndexNo As Long |
2. Position, ab der die Suche beginnen soll. | IndexNo = MeineListe.IndexOf(„Element3“, 0) | |
IndexNo = MeineListe.IndexOf(„Element5“, 3) | ||
Anzahl der Elemente ermitteln | Keine | MsgBox MeineListe.Count |
Element einfügen | 1. Index – Position, an der eingefügt werden soll. | MeineListe.Insert 0, „Element5“ |
2 Value – Objekt oder Wert, der eingefügt werden soll. | MeineListe.Insert 4, „Element7“ | |
Element lesen | Index – lange Ganzzahl | MsgBox MeineListe.Item(0) |
MsgBox MeineListe.Item(4) | ||
Zuletzt hinzugefügtes Element lesen | Index – lange Ganzzahl | MsgBox MeineListe.Item(list.Count – 1) |
Erstes hinzugefügtes Element lesen | Index – lange Ganzzahl | MsgBox MeineListe.Eintrag(0) |
Alle Elemente auslesen (For Each) | N / A | Element als Variante dimmen |
For Each Element In MeineListe | ||
MsgBox-Element | ||
Nächstes Element | ||
Alle Elemente auslesen (For) | Index – lange Ganzzahl | Dim i As Long |
Für i = 0 bis MeineListe.Count – 1 | ||
MsgBox i | ||
Als nächstes i | ||
Alle Elemente entfernen | Keine | MeineListe.Clear |
Element an Position entfernen | Indexposition, an der sich das Element befindet | MeineListe.RemoveAt 5 |
Element nach Namen entfernen | Das zu entfernende Element aus der Array-Liste | MeineListe.Remove „Element3“ |
Einen Bereich von Elementen entfernen | 1. Index – Anfangsposition. | MeineListe.RemoveRange 4,3 |
2. Count – die Anzahl der zu entfernenden Elemente. | ||
In absteigender Reihenfolge sortieren | Keine | MeineListe.Reverse |
In aufsteigender Reihenfolge sortieren | Keine | MeineListe.Sort |
FAQs
How to use ArrayList in Excel VBA? ›
- Go to “Tools” > “References.”
- Object library reference window will appear in front of you. Select the option “mscorlib. dll.”
- Click on “OK.” Now, we can access the VBA ArrayList.
- 1 - Open your VBA code editor: ...
- 2 - Understand the structure of a VBA project: ...
- 3 - Play with the code: ...
- 4 - Play with the macro recorder: ...
- 5 - Add some variables and constants: ...
- 6 - Add some conditions: ...
- 7 - Create a template and make your life easier:
To Fill a Dynamic Array
On the Tools menu, point to Macro and then click Macros. In the Macro dialog box, click fill_array, and then click Run.
The VBA ArrayList is a much better alternative to the built-in VBA Collection. It contains much richer functionality such as sorting, converting to an array, removing all items etc. Check out the quick guide for an overview of what the ArrayList does. The rest of this post provides examples of how to use the ArrayList.
What is the difference between ArrayList and collection in Excel VBA? ›Using a VBA ArrayList
The Collection object only has two methods (Add, Remove) and two properties (Count, Item) whereas an Array List has many more. The Collection object is read only. Once values have been added, the indexed value cannot be changed, whereas on an Array List, editing is possible.
The time it takes for most learners to gain a solid understanding of VBA falls somewhere within the range of one to eight weeks. While this number depends on many factors, most learners who devote several solid weeks to working with VBA will be able to write basic code.
Is Python faster than Excel VBA? ›In general, if you perform complex matrix calculations you can do with numpy and scipy, python will be faster than VBA. In other cases, VBA is faster. In python, you can also use Numba, which adds a bit of complexity to the code, but it helps generating compiled code and handles running it in the GPU.
How do I create a dynamic list in Excel VBA? ›- Go to Formulas ➜ Defined Names ➜ Name Manager ➜ Click New.
- In the name input box enter a name for the named range (Here I am using “monthList2003”).
- Enter the below formula in “Refers To” and click OK.
- Application.WorksheetFunction.vlookup(lookup_value, table_array, col_index_num, range_lookup) ...
- student_id = 11004. ...
- Set myrange = Range(“B4:D8”) ...
- marks = Application.WorksheetFunction.VLookup(student_id, myrange, 3, False)
- Range (“A1”): What are the cells to identify the pattern of the fill series.
- Destination: Till what cell do you want to continue the fill series pattern. Here, we need to mention the full range of cells.
- Type as xlAutoFillType: Here, we can select the series fill type.
How do you autofill an array in Excel? ›
Press Ctrl+Shift+Enter. Excel fills each of the cells you selected with the result.
How do you dynamically populate an array? ›It's easy to initialize a dynamic array to 0. Syntax: int *array{ new int[length]{} }; In the above syntax, the length denotes the number of elements to be added to the array.
What are the array methods in VBA? ›There are nine array functions in VBA: ARRAY, ERASE, FILTER, ISARRAY, JOIN, LBOUND, REDIM, SPLIT, and UBOUND. All of these are built-in functions for the array in VBA. Array function gives us the value for the given argument.
Why would you use an ArrayList instead of an array? ›The array is a fixed sized data structure thus, the array always needs to mention the size of the elements. On the other hand, ArrayList is not a fixed sized data structure, thus there is no need to mention the size of the ArrayList especially creating its object.
When would you use an ArrayList instead of an array? ›Since an array is static in nature i.e. you cannot change the size of an array once created, So, if you need an array which can resize itself then you should use the ArrayList. This is the fundamental difference between an array and an ArrayList.
How to compare ArrayList and list? ›You can compare two array lists using the equals() method of the ArrayList class, this method accepts a list object as a parameter, compares it with the current object, in case of the match it returns true and if not it returns false.
What is the difference between array and collection in VBA? ›Collections in VBA are objects that can store groups of related items, much like an array. Unlike arrays, a single collection can store items of different types because each item in a collection is stored as a Variant.
What is the difference between array and list and collection? ›Arrays can hold both object and primitive type data. On the other hand, collection can hold only object types but not the primitive type of data. Arrays due to its storage and internal implementation better in performance. Collection on the other hand with respect to performance is not recommended to use.
Is Excel VBA a valuable skill? ›It enables you to automate processes and make the job less labour-intensive. You can use VBA to create prompts for users to encourage them to take a particular action or interact with the document. You can use VBA systems to transfer data between different Office applications quickly.
Is Excel VBA still in demand? ›Is VBA Still In Demand? Yes, VBA is still useful and used by individuals interacting with Microsoft products. However, newer languages such as Python, C#, or R can be used to code in place of VBA.
Is Microsoft ending VBA? ›
The software giant now plans to start auto-disabling VBA macros in popular Office apps (such as PowerPoint, Excel, Access, Word, and Visio) from July 27, 2022.
Is Excel VBA harder than Python? ›Python is easier to learn and master, unlike Excel, which includes a personalized language known as VBA that is complex to master and execute.
Should I learn VBA in 2023? ›Yes, VBA is worth learning in 2022. It's a broad programming language that encompasses several topics of data analytics. VBA's usefulness lies in its simple to advanced applications, such as analytics projects, binary codes, and Microsoft Office scripts.
Is Python going to replace VBA? ›Yes, absolutely! VBA is commonly used to automate Excel with macros, add new user defined worksheet functions (UDFs) and react to Excel events. Everything you would previously have done in Excel using VBA can be achieved with Python. Using Python as a VBA replacement has many benefits and is usually faster than VBA!
What slows down Excel the most? ›Too big spreadsheets in Excel can slow down the Excel speed because big Excel spreadsheets also take up large space on your system. You also know that you need enough free storage space on your system so that you can do your task on the system smoothly and efficiently.
Is VBA faster than formulas? ›It's usually faster to use the Excel formula calculations and worksheet functions than to use VBA user-defined functions. This is because there is a small overhead for each user-defined function call and significant overhead transferring information from Excel to the user-defined function.
How do I make Excel 24 hour time? ›Right click the selected cells and then click Format Cells, or press Ctrl + 1. This will open the Format Cells dialog box. On the Number tab, under Category, select Custom, and type one of the following time formats in the Type box: Over 24 hours: [h]:mm:ss or [h]:mm.
How do I create a unique list in Excel VBA? ›- Add an element that uses the Add Method.
- Remove an element that uses the Remove Method.
- Remove all elements that use the Clear Method.
- Find out how many elements the collection contains with the Count Property.
- Check whether a specific element is present with the Contains Method.
- First, declare an array with its name.
- After that, the elements count left the parentheses empty.
- Now, use the ReDim statement.
- In the end, specify the count of elements you want to add to the array.
- Step 1: Import the necessary data into Excel. No data. ...
- Step 2: Set up your workbook. ...
- Step 3: Add raw data to a table. ...
- Step 4: Data analysis. ...
- Step 5: Determine the visuals. ...
- Step 6: Create your Excel dashboard. ...
- Step 7: Customize your dashboard.
How do I use Excel formulas in VBA code? ›
- Start recording.
- Type the formula (with relative / absolute references as needed) into the cell & press enter.
- Stop recording.
- Open VBA and review the formula, adapting as needed and copying+pasting the code where needed.
To use any Excel function in VBA, type “Application. WorksheetFunction.” and start typing the name of the function. In this case, it's “VLOOKUP”. You'll see it come up in the resulting list (you can also just type the name of the function you're looking for).
What can be automated using VBA? ›- Develop Dynamic Dashboards.
- Simplify Data Entry with Formulas.
- Use Conditional Formatting.
- Link Workbooks and Sheets.
- Create Quotes and Invoices.
- Track Changes in the Audit Log.
- Track the Use of Visuals.
- Clean and Correct Data.
- Step 1 - Open Microsoft Excel. ...
- Step 2 - Go to Options to enable developer menu. ...
- Step 3 - Select Customize Ribbon. ...
- Step 4 - Open Visual Basic application dialog. ...
- Step 5 - Insert a new Module. ...
- Step 6 - Add new references. ...
- Step 7 - Automate Microsoft Edge to open a website.
- Open your worksheets. First, open both spreadsheets that you want to connect. ...
- Select data from your source worksheet. ...
- Copy the formula. ...
- Click the corresponding area of the new sheet. ...
- Enter the link. ...
- Add criteria. ...
- Set update intervals. ...
- Save the workbook.
Insert the same data into multiple cells using Ctrl+Enter
Select the cells that you want to fill with the same data in your Excel worksheet. Please see the tips above for quick data selection. Select all the blank cells in a column. Press Ctrl+Enter instead of Enter.
On the Excel menu, click Preferences. Under Formulas and Lists, click AutoComplete. In the Show the menu only after I've typed box, enter the number of letters that you want to type before the AutoComplete menu appears. Tip: You can also show the AutoComplete menu by pressing CONTROL + OPTION + DOWN ARROW .
How do I get the output of an array in Excel? ›Press the keyboard shortcut CTRL + SHIFT + ENTER to complete the array formula. Once you do this, Microsoft Excel surrounds the formula with {curly braces}, which is a visual indication of an array formula.
How do you use the AutoFill feature to fill the range in Excel? ›Put the mouse pointer over the bottom right-hand corner of the cell until it's a black plus sign. Click and hold the left mouse button, and drag the plus sign over the cells you want to fill. And the series is filled in for you automatically using the AutoFill feature.
Can we initialize array dynamically? ›Dynamic arrays are very useful data structures. They can be initialized with variable size at runtime. This size can be modified later in the program to expand (or) shrink the array. Unlike fixed-size arrays and Variable Length Arrays, Dynamically sized arrays are allocated in a heap.
How do you dynamically allocate an array of objects? ›
- int* scores; // Pointer to a dynamic array of integers. ...
- scores = new int[numElements]; ...
- scores[2] = 27; cout << scores[0] << endl; ...
- delete[] scores; ...
- Student* s; // Pointer to a Student object.
Unlike built-in arrays, ArrayLists are resizable which means they can grow and shrink dynamically as we add and remove elements.
What are the three methods of array? ›There are three different kinds of arrays: indexed arrays, multidimensional arrays, and associative arrays.
How to store data in array in VBA Excel? ›First, use the keyword “Dim”, enter the name of the array, and type parentheses. Next, you need to specify the data type for the array. If you do not have any data type specified VBA will assign appropriate data type. After that, you need to define the number of items that you want to store in the array.
How do you loop through an ArrayList in VBA? ›In VBA, to loop through an array you can use the For Loop (For Next). And to write this loop code you need to know the size of the array (upper and lower bound) so that you can use both as the counter for the loop. Basically, for loop will start from the first element of the array and loop up to the last.
Can you have an array of objects in VBA? ›In VBA, Arrays are variables that store multiple values. You can store VBA Objects in arrays in the same way as you would store any other data.
How do I store data from ArrayList to excel? ›- Create an instance of the Workbook class.
- Get worksheet in an instance of the Worksheet class.
- Create an array list containing string values.
- Call the importArrayList() method with the array list.
- Save the output file by calling the save() method of the Workbook class.
Click the cell where you want to create the list box. Click Properties > Control and set the required properties: In the Input range box, type the range of cells containing the values list. Note: If you want more items displayed in the list box, you can change the font size of text in the list.
How do I add items to a list in VBA? ›VBA does not allow you to append items to an array. The standard method to work around this is to re-dimension to array to the required size and then add the required items. There are a number of problems with this method: Performance – The array is copied into a new array each time it is re-dimensioned.
What is the difference between Listbox and ListView in Excel VBA? ›A ListView is basically like a ListBox (and inherits from it), but it also has a View property. This property allows you to specify a predefined way of displaying the items. The only predefined view in the BCL (Base Class Library) is GridView , but you can easily create your own.
How do I loop through each sheet in Excel VBA? ›
- Type the following macro code into a new module sheet. Sub WorksheetLoop() Dim WS_Count As Integer. Dim I As Integer. ...
- To run the macro, position the insertion point in the line that reads "Sub WorksheetLoop()," and press F5.
To loop through a range in VBA, you need to use the “For Each Loop”. By using this loop, you can write a code where you tell VBA to go through each cell in the range, column, or row and perform a specific activity.
How to iterate data from ArrayList? ›Example 3: Iterate over ArrayList using listIterator()
ArrayList: [1, 3, 2] Iterating over ArrayList: 1, 3, 2, In the above example, we have used the listIterator() method to iterate over the arraylist. Here, hasNext() - returns true if there is next element in the arraylist.
The maximum number is 2,147,483,647, assuming that you have enough memory to store that many elements. > Is it possible to pass over 100,000 records in to one arraylist? Yes, this is well within the capabilities of ArrayList.
How to store multiple values in array in VBA? ›Arrays are a special kind of variable that can store multiple values of the same data type. For example, if you have the names of 100 employees, then instead of creating 100 variables of data type string, you can just create one array variable of type string and assign 100 values to the same array variable.
How do you get the size of an ArrayList in VBA? ›In VBA, to get the length of an array means to count the number of elements you have in that array. For this, you need to know the lowest element and the highest element. So, to get this you can use the UBOUND and LBOUND functions that return the upper bound and lower bound, respectively.
How to check data in ArrayList? ›ArrayList. contains() method can be used to check if an element exists in an ArrayList or not. This method has a single parameter i.e. the element whose presence in the ArrayList is tested. Also it returns true if the element is present in the ArrayList and false if the element is not present.
How to store ArrayList values into array? ›- Create a List object.
- Add elements to it.
- Create an empty array with size of the created ArrayList.
- Convert the list to an array using the toArray() method, bypassing the above-created array as an argument to it.
- Print the contents of the array.
addAll(set); Here, we have used the addAll() method to add all the elements of the hashset to the arraylist. The optional index parameter is not present in the method. Hence, all elements are added at the end of the arraylist.