Show Buttons
Share On Facebook
Share On Twitter
Share On Google Plus
Share On Linkdin
Share On Reddit
Contact us
Hide Buttons

VBA-Excel: Arrays – One Dimension, Dynamic Array

Dynamic array means when size of the array is not fixed at the start of the program,  the size changes dynamically.

Use ReDim, For Resizing the size of the array.

If you just you ReDim to changing the size of an array, the already stored values in array will be deleted, if you want to keep the old values of an array while resizing the array, use Presereve keyword along with ReDim

ReDim Preserve arrArrayName(newSize)

Example: Store all the available values in column A, into an Array.

For creating one dimensional static array, follow the below steps

  • Declare an Array
  • Resize the array
  • Store values in array
  • Retrieve values from array.


Declare an Array

Dim arrDynArray()

Resize the array

intCounter = 2

ReDim Preserve arrDynArray(intCounter)

Store values in array

arrDynArray(intCounter) = 4

Retrieve values from array.

MsgBox arrDynArray (1)

Example: Store all the available values in column A, into an Array.

One Dimension, Dynamic Array -1

One Dimension, Dynamic Array -1

Complete Code:

Function FnSingleDynamicArray()

   Dim arrDynArray()

   Dim mainWorkBook As Workbook

   Dim intRows

   Dim intCounter

   intCounter = -1

   Set mainWorkBook = ActiveWorkbook

   intRows = mainWorkBook.Sheets("Sheet1").UsedRange.Rows.Count

   For i = 1 To intRows

      intCounter = intCounter + 1

       ReDim Preserve arrDynArray(intCounter)

      arrDynArray(intCounter) = mainWorkBook.Sheets("Sheet1").Range("A" & i).Value

    Next
    MsgBox  “ The Third value in A Column is “ & arrDynArray(3)

End Function
One Dimension, Dynamic Array -2

One Dimension, Dynamic Array -2

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

%d bloggers like this: