| Hashtable: CopyTo |
Copies the Hashtable elements to a one-dimensional Array instance at the specified index.
Public Sub CopyTo( ByRef Arr As Variant, ByVal ArrayIndex As Long )
The elements are copied to the array in the same order in which the enumerator iterates through the Hashtable.
To copy only the keys in the Hashtable, use Hashtable.Keys.CopyTo.
To copy only the values in the Hashtable, use Hashtable.Values.CopyTo.
This method is an O(n) operation, where n is Count.
| Exception | Condition |
|---|---|
| ArgumentNullException | Arr is uninitialized. |
| ArgumentOutOfRangeException | ArrayIndex is less than lowerbound. |
| ArgumentException | Arr is multidimensional. -or- The number of elements in the source Hashtable is greater than the available space from ArrayIndex to the end of the destination Arr. |
| InvalidCastException | The type of the source Hashtable cannot be cast automatically to the type of the destination Arr. |
The following example shows how to copy the list of keys or the list of values in a Hashtable into a one-dimensional Array.
Public Sub Main() ' Creates and initializes the source Hashtable. Dim MySourceHT As New Hashtable MySourceHT.Add "A", "valueA" MySourceHT.Add "B", "valueB" ' Creates and initializes the one-dimensional target Array. Dim MyTargetArray(14) As String MyTargetArray(0) = "The" MyTargetArray(1) = "quick" MyTargetArray(2) = "brown" MyTargetArray(3) = "fox" MyTargetArray(4) = "jumped" MyTargetArray(5) = "over" MyTargetArray(6) = "the" MyTargetArray(7) = "lazy" MyTargetArray(8) = "dog" ' Displays the values of the target Array. Debug.Print "The target Array contains the following before:" PrintValues MyTargetArray ' Copies the keys in the source Hashtable to the target Hashtable, starting at index 6. Debug.Print "After copying the keys, starting at index 6:" MySourceHT.Keys.CopyTo MyTargetArray, 6 ' Displays the values of the target Array. PrintValues MyTargetArray ' Copies the values in the source Hashtable to the target Hashtable, starting at index 6. Debug.Print "After copying the values, starting at index 6:" MySourceHT.Values.CopyTo MyTargetArray, 6 ' Displays the values of the target Array. PrintValues MyTargetArray End Sub Public Sub PrintValues(ByRef MyArr() As String) Dim i As Long For i = LBound(MyArr) To UBound(MyArr) Debug.Print " " & MyArr(i); Next Debug.Print End Sub 'PrintValues ' This example code produces the following output. ' ' The target Array contains the following before: ' The quick brown fox jumped over the lazy dog ' After copying the keys, starting at index 6: ' The quick brown fox jumped over A B dog ' After copying the values, starting at index 6: ' The quick brown fox jumped over valueA valueB dog