You've successfully subscribed to Nicholas Workshop
Great! Next, complete checkout for full access to Nicholas Workshop
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Dynamic Array in VBA

Nicholas Wong
Nicholas Wong

We can easy resize the array declared in VBA. The trick is actually relocate the array to a bigger space. Suppose we need an array, we have to declare (dim) it with unknown size. It can be any variant (string, integer, etc…):

Dim MyArray() As String

We we need to add something new to this array, we re-declare (re-dim) it to a bigger size. The preserve is optional but needed to preserve data for the re-dimmed array.

ReDim Preserve MyArray(0 to 1) As String  
MyArray(0) = "First One"  
MyArray(1) = "Second One"  

To make it general, we can build a function or class. To conclude, the ReDim syntax is:

ReDim [Preserve] ArrayName(Subscript) As DataType  
Unsorted

Nicholas Wong

Fullstack software engineer with strong background in computer science and extensive experience in software engineering and architecture. Studied in NYU, worked in Yahoo, Rakuten and Manulife.