UBound() and LBound()

When you use a For...Next loop to iterate through an array, you may
be inclined to hard code the starting and ending counter values.  For
instance, suppose you created the following array

MusicGenres = Array("Blues", "Classic Rock", "Country",
"Dance", "Disco", "Funk", "Grunge", "Hip -Hop",
"Jazz", "Metal", "New Age", "Oldies", "Other")

you might think to loop through the array like so

For x = 0 To 12
    Debug.Print MusicGenres(x)
Next x

However, because you may want to add more items to the array at a later
time, it's best to use the LBound() and UBound() functions to delimit
the counter's boundaries, as in

For x = LBound(MusicGenres) To UBound(MusicGenres)
Debug.Print MusicGenres(x)
Next x

This way, no matter how many times you add items to the array, you
won't need to modify the For...Next loop at all. Also, keep in mind
that you don't need to subtract 1 from the UBound() value because the
function returns the array's largest available subscript NOT the number
of items in the array.

You might also like...


ElementK Journals


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Brevity is the soul of wit” - Shakespeare