Array in excel vba Array in excel vba arrays arrays

Array in excel vba


Students must be declared as a dynamic array. That is, an array whose bounds can be changed. Dim Students(10) gives an array whose bounds cannot be changed and cannot be loaded from an array.

Dim Students() As Variant

To load Students:

Students = Array(2,7,14,54,33,45,55,59,62,66,69)

To access the elements:

Dim Inx As LongFor Inx = LBound(Students) to UBound(Students)  Debug.Print Students(Inx)Next

LBound (Lower bound) and UBound mean that the for loop adjusts to the actual number of elements in Students.


This is too complex for you right now, and you'll probably never run into a situation where you'll need this, but:

I use the following method for forming more memory-efficient arrays (because Variant uses the most memory of any variable type) while still having the convenience of declaring the array contents in one line. To follow your example:

Dim Students() As LongDim Array2() As StringArray2() = Split("2,7,14,54,33,45,55,59,62,66,69", ",")ReDim Array1(0) As LongFor Loop1 = LBound(Array2()) To UBound(Array2())    ReDim Preserve Array1(0 To (UBound(Array1) + 1)) As String    Array1(Loop1) = Array2(Loop1)Next Loop1ReDim Preserve Array1(0 To (UBound(Array1) - 1)) As LongErase Array2

An example of accessing it would be something like:

For Loop1 = LBound(Students) to UBound(Students)    Msgbox Students(Loop1)Next Loop1

I learned this from here: http://www.vbforums.com/showthread.php?669265-RESOLVED-VBA-Excel-Assigning-values-to-array-in-a-single-line&p=4116778&viewfull=1#post4116778


You can add values to an Array like this...

For i = 1 to 10    Students(i) = iNext i

Or like this

Students = Array(2,7,14,54,33,45,55,59,62,66,69)

Then you can access the values in the same manor. Note if you use the second option you'll need to declare it as follows:

Dim Students() As Variant