Search Tools Links Login

VB6 Tutorial 52: Dynamic Array


In case of a fixed size array, we have seen that the size of the array is fixed or unchanged, but there may be some situations where you may want to change the array size. A dynamic array can be resized at run time whenever you want.

Declaring dynamic arrays

  • Declare the array with empty dimension list. For example:

    Dim arr() As Integer

  • Resize the array with the ReDim keyword. For Example:

    ReDim arr(5) As Integer

    or

    ReDim arr(2 To 5) As Integer

  • Example

    Dim ar() As Integer
    ReDim ar(2) As Integer

    QuickHint:

    Unlike the Dim and Static statements, the ReDim statements are executable. So a ReDim statement can only be in a procedure and when you execute the ReDim statement, all the values stored in the array are lost. You can use the ReDim statement repeatedly to change the array size.

    Preserving the values of Dynamic arrays

    The ReDim statement deletes all the values stored in the array. You can preserve the element values using the Preserve keyword. So using Preserve keyword with ReDim statements enables you to change the array size without losing the data in the array.

    Example

    Dim arr() As Integer
    ReDim arr(2) As Integer
    For i = 0 To 2
        arr(i) = InputBox("Enter the value")
    Next i
    ReDim Preserve arr(3) As Integer
    arr(3) = 9
    Print arr(0), arr(1), arr(2), arr(3)

    Output

    If the input values through InputBox are 5,6,7 then the following will be printed on the form.

    5     6     7     9

    About this post

    Posted: 2018-05-25
    By: vb6boy
    Viewed: 2,357 times

    Categories

    Visual Basic 6

    VB6 Tutorial

    Attachments

    No attachments for this post


    Loading Comments ...

    Comments

    No comments have been added for this post.

    You must be logged in to make a comment.