Visual Basic Explorer
Visual Basic Explorer
 Navigation
 Home


 Coding
 Source Code

 FAQ Center

 VB Tips

 Downloads

 ToolBox

 Tutorials

 VB Games

 VB News

 VB Award

 VB Forums



 Affiliates
 Planet Source Code

 Rent a Coder

 DirectX4VB


 Misc
 Search

 Feedback

 Advertise

 About


Need to hire
a VB coder?

Please support our sponsor:

 Home 
 Site Map 
 Forums 
 News 
 Feedback 

 

Array Tutorial-Part 1 

What are variable arrays? 

Variable arrays are a collection of variables with the same name that are referenced by an index. 

What are control arrays? 

Control arrays are a collection of controls with the same name that are referenced by an index. 

What are User Defined arrays? 

User Defined Arrays are a collection of variables with the same name that are referenced by an index, and that have multiple pieces of data for each element of the array. 

When should I use arrays? 

This is a question that only you can answer. By the time you finish reading this tutorial, you should be able to answer the question yourself. 

How do I declare a variable array? 

There are many ways to declare a variable array. I will show you several of the methods.

	Dim sArray() as String
	Dim sArray(10) as String
	Dim sArray(1 to 10) as String
	Dim sArray(kMaxSize) as String
The four declarations above are all valid declarations for an array. Below are the differences. For simplicity sake, I declared all the arrays as strings, but you can declare the arrays as any type that you want, including User Defined, which I will address later. 

Dim sArray() as String 

This method simply declares sArray to be an array of any size. You will need to ReDim the array later in code before you can use it. If you are unsure of how much data you are going to be storing, this is the best method to use. This allows you to dynamically resize the array, larger or smaller, as you need it. More on ReDim later on. 

Dim sArray(10) as String 

So, how big is this array? 10 elements, right? Wrong. By default, all arrays are 0 based, unless specified otherwise. This means that the first element in the array is 0. This gives us 0 to 10 elements. 0 to 10 equals 11 elements total. 

Dim sArray(1 to 10) as String 

This array is 10 elements long. We specified a starting point when we declared this array. You can use any starting and ending values you want, however, the beginning element must be less than the ending element. 

Dim sArray(kMaxSize) as String 

This array will be however large the constant kMaxSize is. This array will be 0 based, since we did not specify the starting element. We could have used: Dim sArray(5 to kMaxSize) as String if we had wanted to start with the 5th element. 

First, I will cover a few of the functions that are used with Arrays. 

iUpper = UBound(sR) 'UBound retrieves the upper end of the array 

iLower = LBound(sR) 'LBound retrieves the lower end of the array 

ReDim sR(10) 'ReDim adjusts the array size, destroying existing data 

ReDim Preserve sR(10) 'Adjusts the array size, keeping existing data 

How do I declare a User Defined array? 

OK, first you need to define the Type.

  Public Type MY_ARRAY_TYPE 
	 lValue as Long
	 sTemp as String 
	 iCount as Integer 
  End Type	
The first line declares the type. It is Public so it can be accessed anywhere in the project. Then next three lines simply declare the values that are to be used in the type. You can have any almost variable type within a Type, including other Types. The last line closes the Type. If you are not familiar with Types then you should read up on them. They can be very useful in VB, especially when dealing with API calls, or arrays. 

Now you declare the array like this: 

	Dim uArray() as MY_ARRAY_TYPE 
You can use any of the methods listed for variable arrays for declaring a User Defined array. You can specify upper and lower bounds, use a constant for the upper and or lower bounds or even make the array variable length. 

How do I declare a Control array? 

Well, you do not actually declare a control array. You normally put the control array on the form at design time. 

1. Add a Text box to the form. 

2. Name the Text box txtArray 

3. Change the Index of the text box to 0. This changes the value from nothing (non-arrayed control) to 0 (arrayed control) 

4. Copy the txtArray control and paste it back to the form. 

If you look at the new txtArray control's properties, you will notice that it now has an Index of 1. This is because there are two elements of the txtArray control array. 0 and 1. You can also load control arrays at run time, via code. This can be a little complex, but nothing the average programmer cannot master with a little time and practice. I will cover this topic later during this tutorial. 

How do I access my array? 

Remember the index we mentioned in the very beginning? Well, here is where you use it. If you want to access the 1st element in an array, you would use:

  Debug.Print sArray(0) 'Prints 'Element 0' in the Immediate window.
  Debug.Print uArray(0) 'Prints 'Element 0' in the Immediate window.
  Debug.Print txtArray(0) 'Prints 'Element 0' in the Immediate window.

Remember that unless we specified otherwise, the arrays first element is always 0. If you try to access an index value that does not exist, you get the following error. 

Run-time Error '9': Subscript out of range

If you want to assign a value to the array, you would use: 

sArray(0) = "My String"
txtArray(0).Text = "My Text"
And for the User Defined, you would use: 
  uArray(0).lValue = 300
  uArray(0).sTemp = "Temp String"
  uArray(0).iCount = uArray(0).iCount + 1

How do I change the size of my array after I have declared it? 

You use the ReDim statement. 

  ReDim sArray(5) 'Six elements, erases data that was already in array.
  ReDim Preserve sArray(5) 'Six elements, keeps data that was already in the array.

Since we previously declared the array as a String, we do not declare the array as anything this time. Here is a code example you can paste into the Click event of a form. 

Dim sArray(1 To 5) As String
Dim iCount As Integer

For iCount = 1 To 5
  sArray(iCount) = "Element " & iCount
Next iCount

Debug.Print sArray(3) 'Prints 'Element 3' in the Immediate window.

ReDim Preserve sArray(1 To 10)
  Debug.Print sArray(3) 'Prints 'Element 3' in the Immediate window.
ReDim sArray(1 To 20)
  Debug.Print sArray(3) 'Prints an empty line in the Immediate window.

Ok, so now you know how to declare an array, and how to access and assign data to arrays. 

When do you use them? 

I will show you several methods where you might want to use an array. 

1. You want to store a list of all files within a directory. (Variable Array) 

2. You want to store a list of all files within a directory. (User Defined Array) 

3. You want to create a bunch of command buttons. (Control Array) 

Storing a list of all files within a directory using a Variable Array 

OK, enter the following code into the Click event of a form. 

Dim sFile As String
Dim sArray() As String
Dim i As Integer
 
sFile = Dir$("C:\") 'Get first entry
 
Do Until Len(sFile) = 0 'Loop until we run out (sFile will be empty)
  If Not sFile = "." And Not sFile = ".." Then
    ReDim Preserve sArray(i)
    sArray(i) = sFile 	'Display what we found
    i = i + 1
  End If

  sFile = Dir$ 'Get next entry.
 
Loop
 
For i = 0 To UBound(sArray) 'Now we have all the files in an array, so..
  Debug.Print sArray(i) 'We show them. 
Next i

Storing a list of all files within a directory using a User Defined Array

Type MY_ARRAY_TYPE
  sFile as String
  sExtension as String
End Type

Remember, the Type declaration has to be in the General Declarations section (right after the Option Explicit). This can not be put into the Form Load event, or anything like that.

Dim sFile As String
Dim sArray() As MY_ARRAY_TYPE
Dim i As Integer

  sFile = Dir$("C:\") 'Get first entry

  Do Until Len(sFile) = 0 'Loop until we run out (sFile will be empty)
    If Not sFile = "." And Not sFile = ".." Then 
      ReDim Preserve sArray(i)
      sArray(i).sFile = sFile 'Display what we found
      sArray(i).sExtension = Right$(sFile, 3)
      i = i + 1
    End If

  sFile = Dir$ 'Get next entry.

  Loop

For i = 0 To UBound(sArray)	'Now we have all the files in an array, so..
  Debug.Print sArray(i).sFile, sArray(i).sExtension 'We show them
Next I
Creating command buttons using a Control Array

1. Start a new VB project. 

2. Place a command button on the form. 

3. Name the command button cmdArray 

4. Set the Index property to 0 

5. Paste the following code into the Form, and run the program. 

Private Sub Form_Load()
Dim i As Integer
  cmdArray(0).Caption = "Command 0"
  
  For i = 1 To 9
    Load cmdArray(i)
    With cmdArray(i)
      .Caption = "Command " & i
      .Visible = True
      .Top = cmdArray(i - 1).Top + 550
    End With
  Next i
End Sub

To access the control array, simply reference the index value for the control you want. Paste the code below into the form. 

Private Sub cmdArray_Click(Index As Integer)
  Select Case Index
    Case 0, 1, 2
      MsgBox "You pressed button " & Index, vbOKOnly, "Group 1"
    Case 3, 4, 5
      MsgBox "You pressed button " & Index, vbOKOnly, "Group 2"
    Case 6, 7, 8
      MsgBox "You pressed button " & Index, vbOKOnly, "Group 3"
    Case 9
      MsgBox "You pressed button " & Index, vbOKOnly, "This button is all alone."
  End Select
End Sub
If you want to change the property of a command button, then just reference it like you would any other array element.
cmdArray(3).Caption = "This is command button 3"


Tutorial submitted by:
  Eric D. Burdo,
  Red-Leif International
  VB Programmer and Consultant
  http://www.redleif.com




Home | About | What's New | Source Code | FAQ | Tips & Tricks | Downloads | ToolBox | Tutorials | Game Programming | VB Award | Search | VB Forums | Feedback | VBNews | Copyright & Disclaimer | Advertise | Privacy Policy |

Quick searches: Site Search | Advanced Site Search 

Copyright 2002 by Exhedra Solutions, Inc.
By using this site you agree to its terms and conditions
VB Explorer and VBExplorer.com are trademarks of Exhedra Solutions, Inc.