article

Array Basics (FIXED 18-Apr-08)

Email
Submitted on: 2/18/2015 8:59:00 PM
By: Rde (from psc cd)  
Level: Beginner
User Rating: By 6 Users
Compatibility: VB 4.0 (32-bit), VB 5.0, VB 6.0
Views: 3504
 
     Array basics for beginners


 
				

' There are two areas where arrays can be declared.

' Firstly in the General Declarations section. Arrays declared
' here are seen by all procedures in this form or module:

Private arrayName([intLow To] intHigh) As dataType

' For example:

Private lngArray(2 To 4) As Long

' You can also declare the array as Public, making it visible to
' all forms and modules in the application:

Public arrayName([intLow To] intHigh) As dataType

' For example:

Public strArray(0 To 200) As String

' Secondly, within procedures:

Dim arrayName([intLow To] intHigh) As dataType

' For example:

Dim intArray(0 To 9) As Integer

' You can also specify element size like a string variable:

Dim arrayName([intLow To] intHigh) As dataType * intByteSize

' For example:

Dim strArray(3 To 14) As String * 256

' Also, you can just specify the array length by omitting the
' [intLow To] code shown above. This specifies the upper
' element's index, not neccessarily the arrays length:

Dim ArrayName(intHigh) As dataType

' For example:

Dim intArray(9) As Integer

' This array will be indexed from 0 by default (so the array's
' size will be one greater than intHigh) unless the following
' line is added to the General Declarations section:

Option Base 1


' You can also do this (for single dimensional arrays only):

Dim scores As Variant
scores = Array(81, 49, 80, 71, 92, 66)

' The above scores array will be indexed from 0 unless Option Base 1
' is added to the General Declarations section.


' VB supports static and dynamic arrays. Static arrays are fixed in
' size and can't be changed at runtime, dynamic array sizes can.

' Static arrays are more memory efficient:

Dim array2(10 To 20) As Integer

' Dynamic arrays do not have a size defined when initialized:

Dim array3() As Integer

' You must ReDim a dynamic array to change its size at runtime:

ReDim array3(1 To 4) As Integer

' You can preserve the contents of the array elements when you
' ReDim the array by using the Preserve keyword with ReDim:

ReDim Preserve array3(1 To 9) As Integer

' You can also assign to a dynamic array directly from another
' array without specifying size:

Dim array4() As Integer

array4 = array3

' array4 will now be initialize with the size
' (and element values if any) of array3.


' Visual Basic allows you to use For Each ... Next to enumerate
' the items in an array:

Dim element As Variant
For Each
element In array4()
 
'code to process array elements sequentially
Next

' Because arrays do not have a Count property you can use the
' UBound and LBound methods to establish its length.

' You could use a loop like the following:

For x = LBound(ArrayName()) To UBound(ArrayName())
 
'code to process array items sequentially
Next

' The arrays empty parentheses are not required, so the first
' line of code above could be like this:

For x = LBound(ArrayName) To UBound(ArrayName)

' To establish the length you could also use the following code
' that subtracts the LowerBound value from the UpperBound value,
' then adds one to the result because the array elements include
' both upper and lower, then returns the result As Integer:

Function GetCount(AnyArray As Variant) As Integer
  On
Error Resume Next
  Dim
length As Integer
 
length = UBound(AnyArray) - LBound(AnyArray) + 1
 
GetCount = length ' + 1 = inclusive
End Function

' If you know the data type of the array you could declare
' the AnyArray argument as that type instead of As Variant
' to improve performance:

Function GetCount(sngArray() As Single) As Integer
  On
Error Resume Next
  Dim
length As Integer
 
length = UBound(sngArray) - LBound(sngArray) + 1
 
GetCount = length ' + 1 = inclusive
End Function

' Calling the function is as easy as:

intCount = GetCount(myArray())


' Multi-dimensional arrays

' Each dimension of the array must contain the same data type.

' The second-last and last dimensions of a multi-dimensional array
' are normally considered to be a Row and a Column respectively.

Private multiArray(1 To 5, 1 To 3) As Integer

' So for a two dimensional array in VB the dimension (row) is
' defined first, and the number of elements (cols) for each
' dimension defined second:

Public 2DArray(1 To 2, 1 To 8) As Long

' This array is a two dimensional array containing 8 elements
' in each dimension:

Dim i1 As Integer, i2 As Integer
For
i1 = 1 To 2
 
For i2 = 1 To 8
   
2DArray(i1, i2) = "Cell " & CStr(i1) & "," & CStr(i2)
 
Next
Next

' You can also assign arrays to the elements of other arrays to
' create multi-dimensional arrays:

Public Sub CreateMultiArray()
 
Dim intX As Integer ' Declare counter variable

  ' Declare and populate an integer array
 
Dim countersA(1 To 4) As Integer

  For intX = 1 To 4
   
countersA(intX) = intX
 
Next intX

  ' Declare and populate a string array
  Dim countersB(1 To 4) As String

  For intX = 1 To 4
   
countersB(intX) = "hello"
 
Next intX

  ' Declare a new two-member array
  Dim arrX(1 To 2) As Variant

  ' Populate the array with other arrays
  arrX(1) = countersA()
  arrX(2) = countersB()

  ' Display a member of each array
  MsgBox arrX(1)(2)
  MsgBox arrX(2)(3)

End Sub

' To increase the size of an array without losing its current
' values use the Preserve keyword:

ReDim Preserve DynArray(UBound(DynArray) + 1)

' Only the upper bound of the last dimension in a multi-dimensional
' array can be changed when you use the Preserve keyword; if you
' change any of the other dimensions, or the lower bound of the
' last dimension, a run-time error occurs.

' Thus, you can use code like this:

ReDim Preserve Matrix(10, UBound(Matrix, 2) + 1)

' But you cannot use this code:

ReDim Preserve Matrix(UBound(Matrix, 1) + 1, 10)


' Multi-dimensional array demonstration

' The following code can be copied and pasted into the form of
' a new project and after creating three command buttons named
' cmdFill, cmdShow and cmdMulti you can run the program:

Option Explicit

Option Base 1

Private multiArray(1 To 5, 1 To 3) As String
Private
counter As Integer

Private Sub cmdFill_Click()

  Dim idx1 As Integer, idx2 As Integer

  For idx1 = 1 To 5
   
For idx2 = 1 To 3
     
counter = counter + 1
     
multiArray(idx1, idx2) = "Cell " & CStr(counter)
   
Next
  Next

End Sub

Private Sub cmdShow_Click()

  Me.Refresh
  CurrentY
= 100
  Print " Dim multiarray(1 To 5, 1 To 3) As String"
  CurrentY = 400

  Dim idx1 As Integer, idx2 As Integer

  For idx1 = 1 To 5
    For idx2 = 1 To 3
      Print "multiarray(" & _
        CStr(idx1) & "," & CStr(idx2) & ") = " & _
        Chr
(34) & multiArray(idx1, idx2) & Chr(34)
    Next
  Next

End Sub

Private Sub cmdMulti_Click()
  Dim intX As Integer ' Declare counter variable

  ' Declare and populate an integer array
  Dim countersA(4) As Integer

  For intX = 1 To 4
    countersA(intX) = intX
  Next intX

  ' Declare and populate a string array
  Dim countersB(4) As String

  For intX = 1 To 4
    countersB(intX) = "hello"
  Next intX

  ' Declare a new two-member array
  Dim arrX(1 To 2) As Variant

  ' Populate the array with other arrays
  arrX(1) = countersA()
  arrX(2) = countersB()

  ' Display a member of each array
  MsgBox arrX(1)(2)
  MsgBox arrX(2)(3)
End Sub



Other 30 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Beginner category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.