ARRAY

Introduction to Arrays

By definition, an array is a list of variables with the same data type and name. When we work with a single item, we only need to use one variable. However, if we have a list of items which are of similar type to deal with, we need to declare an array of variables instead of using a variable for each item

Dimension of an Array

Table 16.1. One dimensional Array

Student NameName(1)Name(2)Name(3)Name(4)

Table 16.2 Two Dimensional Array

Name(1,1)Name(1,2)Name(1,3)Name(1,4)
Name(2,1)Name(2,2)Name(2,3)Name(2,4)
Name(3,1)Name(3,2)Name(3,3)Name(3,4)

Declaring Arrays

We can use Public or Dim statement to declare an array just as the way we declare a single variable. The Public statement declares an array that can be used throughout an application while the Dim statement declare an array that could be used only in a local procedure.

The general format to declare a one dimensional array is as follow:
Dim arrayName(subs) as dataType
where subs indicates the last subscript in the array.

Example 

Dim CusName(10) as String

will declare an array that consists of 10 elements if the statement Option Base 1 appear in the declaration area, starting from CusName(1) to CusName(10). Otherwise, there will be 11 elements in the array starting from CusName(0) through to CusName(10)

CusName(1)CusName(2)CusName(3)CusName(4)CusName(5)
CusName(6)CusName(7)CusName(8)CusName(9)CusName(10)

Example

Dim Count(100 to 500) as Integer
declares an array that consists of the first element starting from Count(100) and ends at Count(500)
 
The general format to declare a two dimensional array is as follow:
Dim ArrayName(Sub1,Sub2) as dataType

Sample Programs

(i) The program accepts data entry through an input box and displays the entries in the form itself. As you can see, this program will only allows a user to enter 10 names each time he click on the start button.
Dim studentName(10) As String
Dim num As Integer

Private Sub addName()
For num = 1 To 10
studentName(num) = InputBox("Enter the student name", "Enter Name", "", 1500, 4500)
If studentName(num) <> "" Then
Form1.Print studentName(num)
Else
End
End If
Next
End Sub

ii) The program accepts data entries through an InputBox and displays the items in a list box.

Dim studentName(10) As String
Dim num As Integer

Private Sub addName( )
For num = 1 To 10
studentName(num) = InputBox("Enter the student name")
List1.AddItem studentName(num)
Next
End Sub 

Private Sub Start_Click()
addName
End Sub