|
Let's create and initialize a Dynamic Array
For instance, you might use a Dynamic Array to store the values found in a disk file that is opened and read at run time, in which the number of records varies from one running of the program to the next. For instance, let's create a disk file called 'LETTERS'.TXT' once again containing the first seven letters of the alphabet…

Now let's modify the small program we've written to read the letters of the alphabet from this disk file. Knowing that we have seven 'records' in the file, we could write this code…
Dim strLetters(6) As String
Dim x As Integer
Open "C:\LETTERS.TXT" For Input As #1
For x = 0 To 6
Input #1, strLetters(x)
Next
Close #1
For x = 0 To 6
Form1.Print strLetters(x)
Next x
with the result that each one of the letters from the file would be loaded into an Array element, and then displayed on the form. The problem arises when the number of records in the file doesn't match what the program is expecting. If we add another letter to the file…

and run the program, this code doesn't load the letter 'H' to the Array, and therefore fails to display it on our form…

And if the file contains one less record than we are expecting…

…then when we run the program, it bombs with this error…

For more on why this happens, you should check out Chapter 13 of my best selling book, "Learn to Program with Visual Basic."
This is where a Dynamic Array comes in handy---it can handle the variable number of records in a disk file in a snap. Here's the code to load the letters in our file to a Dynamic Array.
Dim strLetters() As String
Dim x As Integer
Open "C:\LETTERS.TXT" For Input As #1
Do While Not EOF(1)
ReDim Preserve strLetters(x)
Input #1, strLetters(x)
x = x + 1
Loop
Close #1
Notice the differences between a Static Array Declaration and a Dynamic Array Declaration. The Dynamic Array, instead of being declared with a number within its parentheses, is declared with an empty set of parentheses…
Dim strLetters() As String
The empty set of parentheses tells Visual Basic that the number of elements in the Array will be determined later---using a ReDim statement. In fact, we execute multiple ReDim statements within the body of the loop that we use to read the records in our file---each time we read another record, we increment the value of the Upper Bound of our Array with this statement…
ReDim Preserve strLetters(x)
"Preserve" tells Visual Basic to retain the current values in the Array---otherwise, the values would be wiped out.
<<Previous | Next >> |