ArrayList: CopyTo |
Copies all of the items to an array.
Public Sub CopyTo( ByRef Arr As Variant, Optional ByRef ArrayIndex As Variant )
The destination array must be large enough to hold all of the items. If an ArrayIndex is specified, then the destination array must be large enough to hold all of the items from that index on.
Exception | Condition |
---|---|
ArgumentNullException | The Arr is uninitialized. |
ArgumentException |
Arr is multidimension. -or- The number of elements in the ArrayList is greater than the destination Arr can contain. |
InvalidCastException | Elements in the ArrayList cannot be converted to a compatible type of the destination Arr. |
This example shows how to copy elements from an ArrayList into an existing array, replacing any elements in the destination array.
Private Sub Main() Dim Words As New ArrayList Dim Story() As String ' Create our initial story in a regular String array. Story = NewStrings("Humpty", "Dumpty", "sat", "on", "a", "wall.") ' Display the current story. Debug.Print "The initial story is:" PrintValues Story ' Create a new story in an ArrayList. Words.Add "Peter" Words.Add "Rabbit" Words.Add "slept" Words.Add "under" Words.Add "a" Words.Add "tree." ' Copies the third word to same word location in the array. Words.CopyToEx 2, Story, 2, 1 ' Display the new story. Debug.Print "The story with 'sat' substituted by 'slept' is:" PrintValues Story ' Copies the first two elements to the first ' two elements in the array. Words.CopyToEx 0, Story, 0, 2 ' Display the story with the new name. Debug.Print "The story with the name changed is:" PrintValues Story ' Increase the size of the story array. ReDim Preserve Story(0 To 11) ' Append the words to the end of the current story. Words.CopyTo Story, 6 ' Display the final story. Debug.Print "The final story is:" PrintValues Story End Sub Private Sub PrintValues(ByRef s() As String) Dim i As Long Debug.Print vbTab; For i = LBound(s) To UBound(s) Debug.Print CorString.Format("{0} ", s(i)); Next i Debug.Print End Sub ' This code produces the following output. ' ' The initial story is: ' Humpty Dumpty sat on a wall. ' The story with 'sat' substituted by 'slept' is: ' Humpty Dumpty slept on a wall. ' The story with the name changed is: ' Peter Rabbit slept on a wall. ' The final story is: ' Peter Rabbit slept on a wall. Peter Rabbit slept under a tree.