This is a short VBA code to:
- Create a dynamic array.
- Redimension a dynamic array to 3 elements.
Fill the newly added element with a value.
Sub ChangingArrayLengthShort()
' First create array:
Dim arr() As Variant
Dim u As Integer
u = 3
ReDim arr(1 To u + 1) ' Redimension:
arr(UBound(arr)) = "SomeValue" ' Fill last element
End Sub
This is that code explained:
Sub ChangingArrayLength()
Dim arr() As Variant ' One can only redimension a dynamic array, so:
'Dim arr(43 to 65) As Variant ' Will yield an error since it is not a dynamic- but a static array.
Dim NrOfElements As Integer
NrOfElements = 3
ReDim arr(1 To NrOfElements) ' Re-dimension array length
MsgBox (UBound(arr)) ' Show what the last element index is in array arr.
NrOfElements = NrOfElements + 1 ' Increase the variable that is used to increase the nr of elements in array arr.
ReDim arr(1 To NrOfElements) ' Re-dimension array length
MsgBox (UBound(arr)) ' Show what the last element index is in array arr. (And that it increased by 1)
' Add value at element to the end of an array:
arr(UBound(arr)) = "This string is added as last element of array named arr"
End Sub