ArrayList: AddRange

AddRange

Adds the items from a collection to the list.

 Public Sub AddRange(
	  ByRef c As Variant )

Parameters

c
[ByRef] Variant. The collection of items to add. The collection can be a VBA.Collection, ICollection object, or an Array.

Remarks

The elements in the collection added by using For..Each to iterate each element. The elements are added to the end of the list in the same order as the For..Each loop produces them.

If the number of elements to be added is more than the available capacity in the ArrayList, then the capacity is increased to accommodate the collection of elements.

Exceptions

Exception TypeCondition
ArgumentNullException c is an uninitialized array.
- or -
c is Nothing.
NotSupportedException The ArrayList is Read-Only
- or -
The ArrayList is Fixed-Size.
InvalidCastExceptionc is not a VBA.Collection, ICollection object, or an Array.

Example

The following example shows how to add the elements from an existing collection to the ArrayList using the AddRange method.

An ArrayList is created and filled with an initial set of elements, then a Queue is filled with additional elements that will be added to the ArrayList using AddRange.

Private Sub Main()
    Dim list As New ArrayList
    
    ' add several elements to the ArrayList
    list.Add "Humpty"
    list.Add "Dumpty"
    list.Add "sat"
    list.Add "on"
    list.Add "a"
    list.Add "wall."
    
    ' Display the contents of the ArrayList
    Console.WriteLine "The ArrayList initially contains:"
    PrintValues list
    
    Dim que As New Queue
    que.Enqueue "Humpty"
    que.Enqueue "Dumpty"
    que.Enqueue "had"
    que.Enqueue "a"
    que.Enqueue "great"
    que.Enqueue "fall."
    
    ' Display the contents of the Queue
    Console.WriteLine "The Queue initially contains:"
    PrintValues que
    
    ' Add the elements in the Queue to the ArrayList
    list.AddRange que
    
    ' Display the new contents of the ArrayList
    Console.WriteLine "The ArrayList with the elements from the Queue:"
    PrintValues list
    
    ' Wait for user to press return key
    Console.ReadLine
    
End Sub

Private Sub PrintValues(ByVal en As IEnumerable)
    Const Space As String = " "
    
    Dim value As Variant
    
    Console.WriteValue vbTab
    
    ' Iterate over the list
    For Each value In en
        ' Write each value onto the same line
        Console.WriteValue value
        Console.WriteValue Space
    Next value
    Console.WriteLine
End Sub

' This code produces the following output.
'
' The ArrayList initially contains:
'     Humpty Dumpty sat on a wall.
' The Queue initially contains:
'     Humpty Dumpty had a great fall.
' The ArrayList with the elements from the Queue:
'     Humpty Dumpty sat on a wall. Humpty Dumpty had a great fall.

See Also

Project VBCorLib Overview | Class ArrayList Overview | ICollection