Collezione VBA - Come creare un oggetto di raccolta in VBA?

Oggetto Collection VBA di Excel

Nella codifica VBA, oltre alla raccolta esistente di elementi in un gruppo, possiamo creare i nostri gruppi di raccolta. Nei nostri numerosi articoli, abbiamo parlato di variabili oggetto e in questo tutorial esamineremo in dettaglio l'oggetto della raccolta VBA.

Se hai letto il nostro precedente articolo "Array VBA", questo sarà molto più facile da capire. Gli array vengono utilizzati per raggruppare le variabili sotto lo stesso tetto; allo stesso modo, Collection viene utilizzato anche per memorizzare un gruppo di variabili.

Le raccolte vengono utilizzate per archiviare oggetti. Sono molto più flessibili degli array VBA, mentre gli array hanno limiti di dimensione fissi, ma i lettori non hanno limiti di dimensione fissi in un dato momento e non richiedono nemmeno il ridimensionamento manuale.

La raccolta VBA è molto simile al "Dizionario VBA", ma il dizionario richiede che il riferimento a un oggetto esterno sia impostato nella finestra di riferimento dell'oggetto. Con il dizionario VBA, dobbiamo impostare il tipo di riferimento come "Microsoft Scripting Runtime", ma Collection non richiede alcun adattamento aggiuntivo.

Come creare un oggetto di raccolta in VBA?

Per iniziare prima con la raccolta, dobbiamo dichiarare la variabile come "Collezione".

Codice:

Sub Collection_Example () Dim Col As Collection End Sub

Poiché la raccolta è una variabile oggetto, è necessario impostare il riferimento all'oggetto creando una nuova istanza.

Codice:

Sub Collection_Example () Dim Col As Collection Set Col = New Collection End Sub

Ora con la variabile, possiamo accedere a tutti i metodi di raccolta della variabile "Col".

Codice:

Sub Collection_Example () Dim Col As Collection Set Col = New Collection Col. End Sub

Prima di utilizzare questi metodi, dobbiamo dichiarare una variabile come stringa.

Codice:

Sub Collection_Example () Dim Col As Collection Set Col = New Collection Dim ColResult As String End Sub

Ora usa la variabile "Col" per scegliere il metodo "Aggiungi".

Codice:

Sub Collection_Example () Dim Col As Collection Set Col = New Collection Col.Add End Sub

Sotto il metodo Add, abbiamo parametri specifici. Supponiamo di memorizzare i nomi dei marchi di dispositivi mobili con il loro prezzo di vendita medio sul mercato.

In Item, l'argomento inserisce il prezzo del cellulare.

Codice:

Sub Collection_Example () Dim Col As Collection Set Col = New Collection Col.Add Item: = 15000, End Sub

Successivamente, in Argomento chiave , inserisci il nome del marchio del cellulare.

Codice:

Sub Collection_Example () Dim Col As Collection Set Col = New Collection Col.Add Item: = 15000, Key: = "Redmi" End Sub

Per la variabile "ColResult", memorizzeremo il risultato della variabile oggetto "Col".

Codice:

Sub Collection_Example () Dim Col As Collection Set Col = New Collection Col.Add Item: = 15000, Key: = "Redmi" ColResult = Col (End Sub

Quando apri la parentesi della variabile "Col", possiamo vedere l'argomento come Indice. Per questo argomento, dobbiamo fornire il valore dell'argomento critico dal metodo Collection add, ovvero il nome del marchio del cellulare.

Codice:

Sub Collection_Example() Dim Col As Collection Set Col = New Collection Col.Add Item:=15000, Key:="Redmi" ColResult = Col("Redmi") End Sub

Now let show the result in the message box in VBA.

Code:

Sub Collection_Example() Dim Col As Collection Set Col = New Collection Col.Add Item:=15000, Key:="Redmi" ColResult = Col("Redmi") MsgBox ColResult End Sub

Ok, we are done when we run the code. We should see the price of the mobile brand, “Redmi.”

Better Understanding of Key & Item Parameters

I am sure it is not easy to understand the parameters of the Collection object. Let me explain to you a simple example.

Imagine you have a menu of fruits with their name and price of the fruits. Assume you are searching the “Apple” fruit price by the name of the fruit.

To search the price of the fruit, we need to mention the name of the fruit, i.e., in collection VBA language Name of the Fruit is Key, and the price of the fruit is “Item.”

It is like applying the VLOOKUP or HLOOKUP function, based on the lookup value, and we will fetch the required data from the database. Here lookup value is Key, and the result is Item.

Advanced Example

Imagine you are a store manager in one of the retail stores, and you are responsible for managing the customer queries. One such customer query is an inquiry about the product price.

It would help if you allowed the customer to search the price of the product with complete information. Similarly, you need to show the message in case of no data found. Below is the example code which will present the input box in front of the user. They require to enter the name of the product they are looking for. If the product is there in the collection, it will show the price of the mentioned product, or else it will show the message as “The Product you are searching for doesn’t exist.”

Code:

Sub Collection_Example2 () Dim ItemsCol As Collection Dim ColResult As String Set ItemsCol = New Collection ItemsCol.Add Key: = "Apple", Item: = 150 ItemsCol.Add Key: = "Orange", Item: = 75 ItemsCol.Add Key: = "Water Melon", Item: = 45 ItemsCol.Add Key: = "Mush Millan", Item: = 85 ItemsCol.Add Key: = "Mango", Item: = 65 ColResult = Application.InputBox (Prompt: = "Please Inserisci il nome del frutto ") Se ItemsCol (ColResult)" "Allora MsgBox" Il prezzo del frutto "e ColResult &" è: "& ItemsCol (ColResult) Else MsgBox" Il prezzo del frutto che stai cercando non esiste in la raccolta "End If End Sub

Articoli interessanti...