February 28, 2021
Hot Topics:

Discovering Arrays

  • By Karl Moore
  • Send Email »
  • More Articles »

Now, there are two very important functions that go hand in hand with arrays.

They're called LBound and UBound.

Remember that our array holds five bits of information? Well, the LBound (lower boundary) function returns the lowest numbered item in the array. In our case, this is zero though it can change, and we'll see that later.

And unsurprisingly, the UBound (upper boundary) function returns exactly the opposite the highest numbered item in the array. For us, that's four.

Those figures 0 and 4 are known as the dimensions of our array. Try mentioning that word as often as possible. It sounds awfully impressive and might win you a date with a geekess sometime.

Now those dimensions (See? You're impressed, right?) are pretty useful for finding out how many pieces of data you have in the array, then cycling through them all to do a little processing of some sort.

Let's add a little code now to see these functions in action.

  • Add yet another Command Button to your Form
  • Change it's Caption property to: Cycle Through Array
  • Insert the following code behind the button:
Private Sub Command3_Click()    For i = LBound(MyArray) To UBound(MyArray)            MsgBox MyArray(i)        Next iEnd Sub

This code simply cycles through a loop from zero to four and displays a message box for the individual array items.

Top Tip: If you're unsure about loops, get the lowdown here (link to Beg VB Tut, loop section).

The good thing about this is that it's flexible. After all, we could change our array to hold six pieces of info, and this same piece of code would continue to work and display the correct number of message boxes.

But who wants to display message boxes all day? Certainly not you. Instead, you'll probably replace the message box bit with a little code to add the individual array items (elements) to a combo box. Or maybe a database. Or whatever.

Whew! Excellent, I'm glad you're keeping abreast with everything so far. Next up, I'm diving straight for third base, with a talk about these thingies called dynamic arrays, which are certainly a lot more exciting. But first, let's summarise the last couple of pages. We've learnt:

  • Arrays are created like this: codeDim MyArrayName(number) as DataType
  • By default, arrays are zero-based
  • If you try to access a non-existent array element, error nine steps in
  • You can use LBound and UBound to retrieve the dimensions of an array

You can download a sample of the small project we've just built here.

Page 4 of 11

This article was originally published on November 20, 2002

Enterprise Development Update

Don't miss an article. Subscribe to our newsletter below.

Thanks for your registration, follow us on our social networks to keep up-to-date