Visual Basic Concepts

Using Collections as an Alternative to Arrays

Although collections are most often used for working with objects, you can use a collection to work with any data type. In some circumstances, it may be more efficient to store items in a collection rather than an array.

You may want to use a collection if you're working with a small, dynamic set of items. The following code fragment shows how you might use a collection to save and display a list of URL addresses.

' Module-level collection.
Public colURLHistory As New Collection

' Code for adding a specified URL address
' to the collection.
Private Sub SaveURLHistory(URLAddress As String)
   colURLHistory.Add URLAddress
End Sub

' Code for displaying the list of URL addresses
' in the Immediate window.
Private Sub PrintURLHistory()
   Dim URLAddress As Variant
   For Each URLAddress in colURLHistory
      Debug.Print URLAddress
   Next URLAddress
End Sub

For More Information   For more information on using collections, see "Programming With Your Own Objects" in "Programming with Objects." To learn more about using arrays, see "Arrays" in "Programming Fundamentals."