Using the For…Each Statement to 'loop' through the elements of an Array



Accessing all of the items within a Dynamic Array

Since we don't know, at the time we write the program how many elements a Dynamic Array will contain, we can't use the 'Brute Force' method we used earlier. One way to deal with the variable nature of a Dynamic Array is to use the LBound and Ubound Visual Basic functions. LBound returns the Lower Bound of an Array, and Ubound returns the Upper Bound of an Array. Therefore, to display all of the values in an array on our form, we can execute this code…

For x = LBound(strLetters) To UBound(strLetters)

Form1.Print strLetters(x)

Next x

The beauty of this code is that no matter how many letters are in our file (or our Array), this code is 'smart enough' to handle it.

img

We can take this code on step further by using the Visual Basic For…Each statement to 'loop' through the elements of the Array. For those of you not familiar with it, the For…Each statement, in conjunction with an Object variable, can be used to 'loop' through the elements of a Visual Basic Collection---but it can also be used to loop through the elements of an Array, like this…

Dim y As Variant

For Each y In strLetters

Form1.Print y

Next

In this code, the variable y is an Object Variable (and it MUST be declared as a Variant). Y is used, by the For…Each statement as a placeholder to the value of the element in the Array.

Here's a final look at the code …

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

Dim y As Variant

For Each y In strLetters

Form1.Print y

Next

and for good measure, let's modify the contents of our file

img

and run the program one more time to be sure that it works…

img

Summary

I hope you've enjoyed this refresher on Arrays, and that you will find the use of the For…Each statement a valuable technique.

<<Previous

Contents

- Create A Static Array
- Access A Static Array
- Create A Dynamic Array
- Access A Dynamic Array

 

Main VB Page
Back to Tutorials

Search For More Tutorials

Google