Visual Basic Array Tutorial
Written By Adam Wehmann
In this tutorial you will learn the differences between a fixed-size and dynamic array, how to properly declare each one, how to access them, how to loop through them, how to erase them, and a few other things. This tutorial applies to all versions of Visual Basic, however, versions before Visual Basic 6.0 do not include the split and join function. Below is a list of the major topics that will be discussed.
- Types of Arrays
- Fixed-Size Arrays
- Dynamic Arrays
- Retrieving the Contents of an Array
- Adding New Elements on the Fly
- Erasing an Array
- The Split Function
- The Join Function
- Multidimensional Arrays
Types of Arrays
An array is a lot like a CD rack. You know: one of those rectangular boxes with slots to slide CDs in, each above another. There are two types of Visual Basic arrays: fixed-size and dynamic.
A fixed-size array most closely matches our CD rack anology. There are a limited number of slots you can slide CDs into. Pretend you have three CDs - one by the Deftones, another by Tool, and a third by Disturbed. To fit all of these in your rack, the rack must contain at least three slots. So you declare your CD rack as having three slots:
Dim strCDRack(0 to 2) As String
You've just made a variable 'strCDRack' that contains three slots (#0, #1, and #2) and is of a String data type. Now you can insert your CDs into it:
Dim strCDRack(0 to 2) As String strCDRack(0) = "Deftones" strCDRack(1) = "Tool" strCDRack(2) = "Disturbed"
Notice that each of the three new lines starts off with the variable name and then gives an element number before having a value assigned. This is like numbering the slots on your CD rack starting at 0 up to 2 and then inserting a CD into each slot. The format for declaring an array is:Dim|Public|Private ArrayName(Subscript) As DataType
Privatedeclare the array and its scope. Using
Dimin a procedure will make the array only available from within that procedure. Using it in the General Declarations section will make it available to all procedures in that module.
Privatehas the same effect and should be used only at the modular level. Using
Publicwill make the array available throughout the project.
- ArrayName is the name of the array.
- Subscript is the dimensions of the array.
- DataType is any valid data type.
The new Charlotte Church CD came out but your rack only has three slots. You don't want to throw away any of your CDs to make room for the new one so you decide to use your ultimate building skills to attach another slot. You start building:
Dim strCDRack() As String ReDim strCDRack(0 to 2) As String strCDRack(0) = "Deftones" strCDRack(1) = "Tool" strCDRack(2) = "Disturbed"
What have you done? Nothing wrong, you've just dimensioned your array another way that allows for expansion. Notice that the subscript of the
Dimstatement is missing. This is OK; it tells VB that your array is a dynamic array, meaning that you can change its size with
Now that you've rebuilt the structure of your CD rack, allowing for expansion, it is time to expand:
Dim strCDRack() As String ReDim strCDRack(0 to 2) As String strCDRack(0) = "Deftones" strCDRack(1) = "Tool" strCDRack(2) = "Disturbed" ReDim Preserve strCDRack(0 to 3) As String strCDRack(3) = "Charlotte Church"
This snippet has two more lines, the first redimensioning the array one element larger and the second setting this element's value. Notice the
Preservekeyword: it forces Visual Basic to retain all existing elements' values. Without this keyword all your old CDs would be lost and you'd be stuck with just Charlotte Church.
The ReDim keyword's syntax is:ReDim [Preserve] ArrayName(Subscript) As DataType
ReDimis the keyword that denotes we are redimensioning an array.
Preserveis an optional keyword that forces Visual Basic to retain all existing elements' values. Without it all elements will return to their default values. (Numeric data types to 0, variable-length strings to "" (a zero-length string), fixed-length strings filled with zeros, and variants to empty.)
- ArrayName is the name of the array.
- Subscript is the dimensions of the array.
DataType is any valid data type. The data type cannot be changed from its initial declaration when using the
ReDimkeyword. (Unless it was initially declared as a Variant.)
Retrieving the Contents of an Array
Now that you know how to build an array, you might ask how to retrieve its contents. Say you've built an array of your friends' names:
Dim strFriends(0 to 6) As String strFriends(0) = "Bianca" strFriends(1) = "Jeana" strFriends(2) = "Sam" strFriends(3) = "Jenna" strFriends(4) = "Erin" strFriends(5) = "Carolyn" strFriends(6) = "Kate"
That's all good and dandy but you want to display their names in successive message boxes, so you construct a loop:
Dim strFriends(0 to 6) As String, lngPosition as Long strFriends(0) = "Bianca" strFriends(1) = "Jeana" strFriends(2) = "Sam" strFriends(3) = "Jenna" strFriends(4) = "Erin" strFriends(5) = "Carolyn" strFriends(6) = "Kate" For lngPosition = LBound(strFriends) To UBound(strFriends) MsgBox strFriends(lngPosition) Next lngPositionlngPositionlngPosition
There are two new functions in that snippet of code.
UBoundare used to determine the lower and upper bounds of an array. Because strFriends has a lower bound of 0 and an upper bound of 6. These functions allow you to to iterate through an array with a dynamic size and they keep you from having to keep track of the array's size yourself. With each iteration of that loop, lngPosition will count up from 0 to 6. By accessing the array as
strFriends(lngPosition)you are greatly reducing the amount of code you have to write.
Adding New Elements on the Fly
Sometimes you have an array that needs to keep growing, and you don't know what the upper bound will end up being. Maybe you are making a crappy MP3 player and need to ask the user to input song names. You might do something like this:
Dim strSongNames() As String 'Array of song names Dim blDimensioned As Boolean 'Is the array dimensioned? Dim strText As String 'To temporarily hold names Dim lngPosition as Long 'Counting 'The array has not yet been dimensioned: blDimensioned = False Do 'Ask for a song name strText = InputBox("Enter a song name:") If strText <> "" Then 'Has the array been dimensioned? If blDimensioned = True Then 'Yes, so extend the array one element large than its current upper bound. 'Without the "Preserve" keyword below, the previous elements in our array 'would be erased with the resizing ReDim Preserve strSongNames(0 To UBound(strSongNames) + 1) As String Else 'No, so dimension it and flag it as dimensioned. ReDim strSongNames(0 To 0) As String blDimensioned = True End If 'Add the song name to the last element in the array. strSongNames(UBound(strSongNames)) = strText End If Loop Until strText = "" 'Display entered song names: For lngPosition = LBound(strSongNames) To UBound(strSongNames) MsgBox strSongNames(lngPosition) Next lngPosition 'Erase array Erase strSongName
Look to the comments for an explanation of what is going on.
Erasing an Array
You should always erase your array when you are done using it, especially if you are using dynamic arrays. It's rather easy:
Dim strFriends(0 to 2) As String strFriends(0) = "Bianca" strFriends(1) = "Jeana" strFriends(2) = "Erin" Erase strFriends
The Split Function
Sometimes we run into situations where we want to take the information from within a given string, separate it into multiple strings, and then place those strings in an array. For example, say we had this code:
Dim cdList As String cdList = "Nevermind, OK Computer, I Care Because You Do, Icky Thump"
It'd be nice if we could easily take that list and put it in an array, wouldn't it? This could be done by using Visual Basic's built in string functions, however, writing and updating that code could prove to be time consuming and tedious. Luckily for us, Visual Basic 6.0 provides a built in function called
splitthat allows us to easily parse out information from a string and place it into an array. It has the following syntax:
ArrayName = split(Sting Input[, Delimiter[, Length Limit[, Compare Mode]]])The following is an example showing how to parse the list we showed earlier:
- String Input is the string that you want to parse.
- Delimiter is an optional parameter that indicates what type of string separates the elements in the input string. By default this parameter is set to " ". That would mean an input string of "This is a test" would yield an array of 4 elements ("This", "is", "a", "test").
- Length Limit is the maximum size your output array can be. The text remaining to be parsed will be set as the final element in the array.
Compare Mode. By default, Visual Basic compares strings character by character using their ASCII values. However, you can use different modes that will cause Visual Basic to compare strings differently. For example,
vbTextComparecauses string comparisons to be case insensitive. This parameter effects how the
Dim strCDRack() As String Dim cdList As String Dim i As Integer cdList = "Nevermind, OK Computer, I Care Because You Do, Icky Thump" strCDRack = Split(cdList, ", ") For i = LBound(strCDRack) To UBound(strCDRack) MsgBox strCDRack(i) Next
The Join Function
splitfunction allowed us to break strings down into arrays, is there a function that allows us to take arrays and make them one big long string? Yes, yes there is, and it is called
joinis a very simple function. It has the following syntax:
StringName = join(Array Input[, Delimiter])
- Array Input is the array that you want to place into a string.
- Delimiter is an optional parameter that indicates what you want to place between elements are added to the string. By default this parameter is set to "".
Using one of our previous examples, here is some sample code on how one might use join:
Dim strFriends(0 to 6) As String, lngPosition as Long strFriends(0) = "Bianca" strFriends(1) = "Jeana" strFriends(2) = "Sam" strFriends(3) = "Jenna" strFriends(4) = "Erin" strFriends(5) = "Carolyn" strFriends(6) = "Kate" Dim myFriends As String 'This will produce the following string: "Bianca, Jeana, Sam, Jenna, Erin, Carolyn, Kate" myFriends = Join(strFriends, ", ") MsgBox myFriends
So far all of the examples we've looked at have used one dimensional arrays, but arrays can be multidimensional too. Multidimensional arrays can be thought of as arrays-of-arrays. For example, to visualize a two dimensional array we could picture a row of CD racks. To make things easier, we can imagine that each CD rack could be for a different artist. Like the CDs, the racks would be identifiable by number. Below we'll define a two dimensional array representing a row of CD racks. The strings inside of the array will represent album titles.
' Here we will define an array where the first dimension contains 2 elements and ' the second dimension contains 4 elements ReDim cdRack(0 to 1, 0 to 3) As String ' A CD rack for the Beatles cdRack(0, 0) = "Rubber Soul" cdRack(0, 1) = "Revolver" cdRack(0, 2) = "The White Album" cdRack(0, 3) = "Let It Be" ' A CD rack for the Rolling Stones cdRack(1, 0) = "Sticky Fingers" cdRack(1, 1) = "Beggars Banquet" cdRack(1, 2) = "Let It Bleed" cdRack(1, 3) = "Tattoo You"
The first item of the first dimension is an array for Beatles CDs while the second item of the first dimension is an array for Rolling Stones CDs. You could also add a third dimension if you wanted. Keeping with our CD rack analogy, you could picture this third dimension as a hallway with several rooms. Inside of each room would be a row of CDs racks. If you wanted your hallways to have 10 rooms, each with CD racks like the ones in the above example, you could declare your array as follows:
Dim cdRackHallway(0 to 9, 0 to 1, 0 to 3) As String
In Visual Basic 6.0, you can create arrays with up to 60 dimensions. In Visual Basic .NET, the maximum number of dimensions an array can have is 32. Most arrays you will need to deal with will only be one or two dimensions. Multidimensional arrays can require a decent amount of memory, so use them with care, especially large multidimensional arrays. Lastly, for multidimensional arrays it should be noted that only the last dimension can be resized. That means that given our example above, once we created the array with two CD racks, we would not be able to add more racks, we would only be able to change the number of CDs each rack held. Example:
' Here we will define an array where the first dimension contains 2 elements and ' the second dimension contains 4 elements ReDim cdRack(0 to 1, 0 to 3) As String ' A CD rack for the Beatles cdRack(0, 0) = "Rubber Soul" cdRack(0, 1) = "Revolver" cdRack(0, 2) = "The White Album" cdRack(0, 3) = "Let It Be" ' A CD rack for the Rolling Stones cdRack(1, 0) = "Sticky Fingers" cdRack(1, 1) = "Beggars Banquet" cdRack(1, 2) = "Let It Bleed" cdRack(1, 3) = "Tattoo You" ReDim Preserve cdRack(0 to 1, 0 to 4) As String ' Lets add another Beatles CD cdRack(0, 4) = "Abby Road" ' Lets add another Rolling Stones CD cdRack(1, 4) = "Exile on Main St."
A word from Pat (owner of patorjk.com): I hope you've enjoyed and learned something from this tutorial. This tutorial was originally written for patorjk.com back in 1999 by Adam Wehmann. After patorjk.com was resurrected in 2007, I decided to put the tutorial back up since it had received some positive feed back. When it was put back up, with Adam's concent, I contributed three new sections: "The Split Function", "The Join Function", and "Multidimensional Arrays". Everything else was written by Adam in his original 1999 submission.