Variable Array Sizes

pnh73
pnh73 used Ask the Experts™
on
How do I create an array with a variable size that is set by the user but can be accessed globally by all procedures. I have an input box where the user types the number and then the program needs to create an array this size. Any ideas?

Paul
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®

Commented:
Add a module to your form and put the module code in it that is listed below.

Next put the form code that is listed below in your form.  You may need to change the names "Command1" and "Text1" to the names of your controls.

Or you can create a new project, then add a module, command button, and text box and paste the code accordingly in it to see how it works.

Module code
-----------

Public Arr() As String



Form code
---------

Private Sub Command1_Click()
Dim i As Integer
ReDim Arr(1 To Text1.Text) As String
For i = 1 To UBound(Arr)
    Arr(i) = i
    MsgBox Arr(i)
Next i
End Sub

Commented:
After I re-read your question, I'm thinking you may have wanted to know how the user can set the array with an inputbox.  Here's the code:

By the way, you don't need any controls on a form to test this out.  You only need a project with a form and a module.


Module code
-----------

Public Arr() As String



Form code
---------

Private Sub Form_Load()
Dim i As Integer
ReDim Arr(1 To InputBox("Enter array top value")) As String
MsgBox "Your Arr() array variable goes from " & _
       LBound(Arr) & " to " & UBound(Arr)
End Sub
Commented:
The key to dynamically created arrays, as described above, is to create a variable with no dimensions:

dim strSomethingArray() as String

Once this is done, you have an array shell that's undefined, so you soon thereafter want to define it.  This requires a ReDim:

ReDim strSomethingArray(0)

(Note that the type was omitted because it was already defined.)

In the future, you can ReDim again based on whatever criteria, as long as the number of dimensions does not change.

--
One thing missed in the above comments is that if you need to retain the current data in the array, you must "Preserve" it or the data will be erased when the array is recreated:

ReDim Preserve strSomethingArray(intMyNewSize)

Author

Commented:
Thanks for that tip. It works a treat.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial