tags:

views:

89

answers:

1

Hello all I am getting an error

Run-time error '9':
Subscript out of range

with the following code

Public newarray() As String

Sub test1() 
    Dim int1 As Integer 
    int1 = 0
    Do 
        int1 = int1 + 1 
        newarray(int1) = int1 * 5     
    Loop Until int1 > 3
End Sub

when i decare the array

Public newarray(4) As string

it works, however I wish to declare a dynamic array. Please help. Thank you.

+7  A: 

You can allocate the array size by using ReDim:

Public newarray() As String

Sub test1() 

    Dim int1 As Integer 
    ReDim newarray(4)

    int1 = 0

    Do 

     int1 = int1 + 1 

     newarray(int1) = int1 * 5 

    Loop Until int1 > 3

End Sub

This will redefine your entire array. If you need to preserve the contents of the array, and just change the size, you can use ReDim Preserve newarray(4).

Your code assumes that arrays are 1 based. This can be 0 based (set by option in VB). To be sure your code works regardless of this option, you should use LBound/UBound for the limits of your counter:

    int1 = LBound(newarray)

    Do 

     newarray(int1) = int1 * 5 

     int1 = int1 + 1 


    Loop Until int1 > UBound(newarray)
awe
You can specify the indices in the ReDim statement like `ReDim newarray(1 To 5)`
Ryan Shannon
Thank you! It helps.
Yoga