Wednesday, December 12, 2012

Multi dimensional Array in visual basic


Multidimensional Arrays: Sometimes data cannot be accurately depicted and stored in a single dimension array. Suppose you want to store the x and y coordinates of a map or grid or the rows and columns of a record from a file. You can implement these and many other examples through the use of a two-dimensional array. Also known as multi subscripted arrays, multidimensional arrays are not limited to just two dimensions.
Like 1D array, multidimensional arrays share similar scope to variables, and share a common name. They have like data types, and they are referenced through element numbers.
The following statement creates a two-dimensional array with four rows and four columns:
Dim myArray(3, 3) As String
This gives the array a total of 16 elements. As shown in the next segment, you can also explicitly declare upper and lower bounds with two-dimensional arrays:
Dim myArray(1 To 4, 1 To 4) As String
Ex.
Option Explicit
Dim myArray(3, 3) As String ‘16 elements
Private Sub Form_Load()
Dim liOuterLoop As Integer
Dim liInnerLoop As Integer
‘Populate the array
For liOuterLoop = 0 To 3
For liInnerLoop = 0 To 3
myArray(liOuterLoop, liInnerLoop) = “Row “ & liOuterLoop & “, _
Column “ & liInnerLoop
Next liInnerLoop
Next liOuterLoop
End Sub

Private Sub cmdPrint_Click()
Dim liOuterLoop As Integer
Dim liInnerLoop As Integer
‘Print array elements
For liOuterLoop = 0 To 3
For liInnerLoop = 0 To 3
Picture1.Print myArray(liOuterLoop, liInnerLoop)
Next liInnerLoop
Next liOuterLoop
End Sub