Skip to Content
Course content

8.2 Collections and Dictionaries.

In VBA, Collections and Dictionaries are powerful data structures that allow you to store and manage groups of related data. While both can store collections of objects, they differ in terms of functionality and use cases. This section explores how to work with both collections and dictionaries in VBA.

1. Collections

A Collection is a special type of object in VBA that can store multiple items. Unlike arrays, collections are more flexible and allow you to add, remove, and manipulate items without worrying about the size of the collection.

Key Characteristics of Collections:

  • No Fixed Size: Collections grow and shrink dynamically.
  • Indexed Access: Items can be accessed by their index or key.
  • Variant Type: All items in a collection are stored as Variant data types, so you can store any type of object.
  • Automatically Handles Indexing: Unlike arrays, you do not need to define an index when adding elements, making it more flexible.

Creating and Using a Collection:

Sub CollectionExample()
    Dim myCollection As Collection
    Set myCollection = New Collection ' Create a new collection

    ' Adding items to the collection
    myCollection.Add "Apple"
    myCollection.Add "Banana"
    myCollection.Add "Cherry"
    
    ' Accessing items by index (index starts from 1)
    Debug.Print myCollection(1) ' Prints "Apple"
    Debug.Print myCollection(2) ' Prints "Banana"

    ' Looping through the collection
    Dim i As Integer
    For i = 1 To myCollection.Count
        Debug.Print myCollection(i) ' Prints all items
    Next i
End Sub

Removing Items from a Collection:

You can remove items from a collection using the Remove method. Items can be removed by their index or key (if you used keys when adding items).

myCollection.Remove 2 ' Removes the second item (Banana)

2. Dictionaries

A Dictionary is a more advanced data structure compared to a collection. It stores items in key-value pairs, which makes it very efficient for looking up values based on a unique key.

Key Characteristics of Dictionaries:

  • Key-Value Pairs: Each item is stored with a unique key, which allows for fast lookups.
  • No Fixed Size: Like collections, dictionaries grow and shrink dynamically.
  • More Flexible: You can use any data type for both the key and the value.
  • Efficient Searching: You can quickly find values based on their keys.

Creating and Using a Dictionary:

In order to use a dictionary, you need to reference the Microsoft Scripting Runtime library.

  • Go to the VBA editor.
  • Click Tools > References.
  • Check Microsoft Scripting Runtime.

Now you can create and use dictionaries in VBA.

Sub DictionaryExample()
    Dim dict As Object
    Set dict = CreateObject("Scripting.Dictionary") ' Create a new dictionary

    ' Adding items to the dictionary with a key-value pair
    dict.Add "A", "Apple"
    dict.Add "B", "Banana"
    dict.Add "C", "Cherry"

    ' Accessing items by key
    Debug.Print dict("A") ' Prints "Apple"
    Debug.Print dict("B") ' Prints "Banana"

    ' Checking if a key exists
    If dict.Exists("C") Then
        Debug.Print "Key 'C' exists!" ' Prints this line
    End If

    ' Looping through the dictionary
    Dim key As Variant
    For Each key In dict.Keys
        Debug.Print key & ": " & dict(key) ' Prints each key-value pair
    Next key
End Sub

Removing Items from a Dictionary:

You can remove items from a dictionary using the Remove method, either by key or by index.

dict.Remove "B" ' Removes the item with the key "B"

You can also check if a key exists before attempting to remove it:

If dict.Exists("A") Then
    dict.Remove "A"
End If

3. Key Differences Between Collections and Dictionaries

Feature Collection Dictionary
Storage Type Stores items sequentially without keys (unless explicitly specified) Stores items as key-value pairs.
Key Optional (can add items by index or key) Requires a unique key for each item.
Accessing Items Accessed by index (starting from 1) Accessed by key (unique identifier for each item).
Efficiency Slower for searching by item value Faster for searching, adding, and removing by key.
Data Types Can store any data type, but only one type per item Can store any data type for both keys and values.
Removal Items are removed by index or key Items are removed by key.

4. When to Use Collections vs. Dictionaries

  • Use Collections when:
    • You want to store a list of items and don’t need to use keys.
    • The order of items matters.
    • You need a simple, flexible way to store multiple values.
  • Use Dictionaries when:
    • You need to store data as key-value pairs (e.g., mapping a name to an ID).
    • You need to quickly find values by their key.
    • You need more advanced functionality, such as checking if a key exists, or removing items based on keys.

5. Summary

Feature Collection Dictionary
Storage Type Indexed items (optional keys) Key-Value pairs
Lookup Efficiency Slower Faster, especially with large datasets
Data Types Any data type but usually one per item Can store different data types for keys and values
Best Use Simple list of values, order matters Complex data relationships and fast lookups

Collections and dictionaries are essential tools in VBA, providing flexibility and efficiency in managing data. By selecting the appropriate structure for your needs, you can streamline your code and enhance performance.

Commenting is not enabled on this course.