Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamically Dimensioning A VBA Array?

Tags:

arrays

vba

Why am I unable to set the size of an array based on a variable? What's the best way around this?

Dim NumberOfZombies as integer NumberOfZombies = 20000 Dim Zombies(NumberOfZombies) as New Zombie 
like image 439
sooprise Avatar asked Dec 01 '10 16:12

sooprise


People also ask

Can an array be sized dynamically?

A dynamic array is an array with a big improvement: automatic resizing. One limitation of arrays is that they're fixed size, meaning you need to specify the number of elements your array will hold ahead of time. A dynamic array expands as you add more elements. So you don't need to determine the size ahead of time.

How do you dynamically allocate an array in VBA?

Create a Dynamic Array in VBAFirst, declare an array with its name. After that, the elements count left the parentheses empty. Now, use the ReDim statement. In the end, specify the count of elements you want to add to the array.

How do I change the size of an array in VBA?

The ReDim statement is used to size or resize a dynamic array that has already been formally declared by using a Private, Public, or Dim statement with empty parentheses (without dimension subscripts). Use the ReDim statement repeatedly to change the number of elements and dimensions in an array.


2 Answers

You can use a dynamic array when you don't know the number of values it will contain until run-time:

Dim Zombies() As Integer ReDim Zombies(NumberOfZombies) 

Or you could do everything with one statement if you're creating an array that's local to a procedure:

ReDim Zombies(NumberOfZombies) As Integer 

Fixed-size arrays require the number of elements contained to be known at compile-time. This is why you can't use a variable to set the size of the array—by definition, the values of a variable are variable and only known at run-time.

You could use a constant if you knew the value of the variable was not going to change:

Const NumberOfZombies = 2000 

but there's no way to cast between constants and variables. They have distinctly different meanings.

like image 78
Cody Gray Avatar answered Oct 04 '22 16:10

Cody Gray


You have to use the ReDim statement to dynamically size arrays.

Public Sub Test()     Dim NumberOfZombies As Integer     NumberOfZombies = 20000     Dim Zombies() As New Zombie     ReDim Zombies(NumberOfZombies)  End Sub 

This can seem strange when you already know the size of your array, but there you go!

like image 32
Chris Spicer Avatar answered Oct 04 '22 16:10

Chris Spicer