Visual Basic Arrays
By Floyd Jay Winters 11/09/07, 03/22/10, 10/22/10, 10/01/2012, 03/27/2013, 03/26/2014, 11/04/2016
An
Array can hold a collection of similar objects in one variable. Or you might say an array is a collection of variables with one name. Each value is referred to by its subscript or index or numeric position in the array.
Instead of State1, State2, State3... (three Objects with three names)
An array has State(1), State(2), State(3)... (one Object with one name)
The above is read State "sub 1", State "sub 2", State "sub 3"  
An array is kind of like having one egg carton that holds 12 eggs, instead of having 12 individual mini egg cartons.  In reality, instead of being cubby holes in an egg carton, an Array is simply cubby holes in RAM memory.  Arrays are really handy when you have large files where it would be impossible to have thousands of variables.

A dynamic variable-length array is an array whose length is determined at run time, not at code time.
 

Simple Array | Parallel Arrays | Two Dimensional Array | Sort Array

 

*** SIMPLE ARRAY

' Set up: Create a new VB form with btnLoadArray, btnDisplayAll, ListBoxMonths
Public
Class frmArraySimple
' Display months of the year in a fixed, hard coded, predefined array, as a sample only.

 

Dim numMonths As Integer = 12  ' Define numMonths and initialize to 12 items
Dim i As Integer               ' This may be referred to as the Index

Dim Month(numMonths)As String ' Declare array & reserve 12 cells for 12 months

    ' Cell one will be “Month sub 1” for Jan, and “Month sub 2" for Feb ...

    ' This is a ONE DIMENSIONAL array: basically 12 rows, but only ONE column

Dim Count As Integer

 

Private Sub btnLoadArray_Click(ByVal sender As System.Object, ByVal e As ...
    ' Subscript numbering begins with a 0. But I usually start at 1.

    Month(1) = "Jan" ' Month "sub" 1

    Month(2) = "Feb"

    Month(3) = "Mar" ' Month "sub" 3 ...

End Sub

 

Private Sub btnDisplayAllItems_Click(ByVal sender As System.Object, ByVal ...

    Count = 3 ' Normally there is code for a counter: Count += 1

    For i = 1 To Count ' i, the subscript, becomes 1, then i becomes 2, then 3 ...

        ListBoxMonths.Items.Add(i & vbTab & Month(i))

        ' Month(i) - means load each element of months

    Next i

End Sub
End Class

 

= = = = = = = = =

' The code below allows you to enter Things and Stuff into two separate Textboxes.
' They are saved on lost focus to an ARRAY.

' When you tap the Next button you can reenter new values for Textbox1 and Textbox2 and save the new values to the array as well.

' Then when you are done, you can print them all out at one time in a Listbox. 

' Note: if the original values for Textbox1 and Textbox2 were not saved in an array, they would be overwritten by the next values entered for Textbox1 and Textbox2 and you would therefore lose the previously entered data.

' Create a new VB project: ArrayDemo.
' Create two Textboxes: txtThings and txtStuff.
' Create two Buttons: btnNext and btnDisplayAll.
' Create a ListBox: ListBox1.

 

Public Class frmArrayDemo   ' Very simple Array concept

  Dim count As Integer = 1

  Dim Things(100) As String    ' Define and reserve space in memory for 100 items (actually 101: 0-100)

  Dim Stuff(100) As String

 

  Private Sub txtThings_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles...

      Things(count) = txtThings.Text

  End Sub

 

  Private Sub txtStuff_LostFocus(ByVal sender As Object, ByVal e As System.EventArgs) Handles...

      Stuff(count) = txtStuff.Text

  End Sub

 

  Private Sub btnNext_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles...

      count += 1

      txtThings.Focus()

      txtThings.SelectAll()

  End Sub

 

  Private Sub btnDisplayAll_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles...
      ListBox1.Items.Clear

      For x = 1 To count

          ListBox1.Items.Add(Things(x) & vbTab & Stuff(x))

      Next

  End Sub

End Class

= = = = = = = = =

Top (Simple arrays)

 

' Set up: Create a new form with btnSaveCurrent, btnDisplayAll, txtStudent, txtScore, ListBoxDisplay
*** PARALLEL ARRAYS
' Enter and then display ALL student names and student scores

 

Public Class frmArrayDemo     ' Using two (or more) PARALLEL arrays

      ' Input from TextBoxes: Student Name and Student Score one at a time

      ' Output to a ListBox:  Student Name and Student Score, Class Average 

  Dim Student(32) As String ' Define Array Student: 1 column stores up to 32 items/students

  Dim Score(32) As Integer

  Dim TotalScore As Integer

  Dim Average As Decimal    ' No need for Array: calculate and immediately display in loop

  Dim count As Integer

 

  ' Load Array: Enter Student Names and Scores

  Private Sub btnSaveCurrent_Click(ByVal sender As System.Object, ByVal e As ...

      If txtStudent.Text = Student(count) Then

          MessageBox.Show("Record Already Saved", "Probable Duplicate")

         ' Add above line so if Save is clicked twice record is not Saved twice

          Exit Sub

      End If

      count += 1

      Student(count) = txtStudent.Text ' Variable = textbox to later see if Saved twice

      Score(count) = txtScore.Text

      Debug.WriteLine(count & " " & Student(count) & " " & Score(count))

  End Sub

 

  ' Display results in Array with Loop

  Private Sub btnDisplayAll_Click(ByVal sender As System.Object, ByVal e As ...

      ListBoxDisplay.Items.Clear()

      TotalScore = 0                      ' Reset to 0 if button is clicked twice

      ListBoxDisplay.Items.Add("Student" & vbTab & vbTab & "Score") ' HEADER before Loop

      For x = 1 To count

          ListBoxDisplay.Items.Add(Student(x) & vbTab & vbTab & Score(x))  '  All  DETAIL in Loop

          TotalScore += Score(x)

      Next

      ListBoxDisplay.Items.Add(vbCrLf)

      ListBoxDisplay.Items.Add("Total: " & vbTab & vbTab & TotalScore) ' TOTALS after Loop

      ListBoxDisplay.Items.Add(vbCrLf)

      Average = FormatNumber((TotalScore / count), 2)

      ListBoxDisplay.Items.Add("Average: " & vbTab & vbTab & Average)

  End Sub

 

' Also Note (Put a breakpoint on Array.Sort and click on the [+])

' Dim arrayStudentSort() As String = {"Bob", "Adam", "Doug", "Cindy"}

' Array.Sort(arrayStudentSort)

 

End Class

 

= = =

*** TWO DIMENSIONAL ARRAY

 

Public Class frmArrayDemo2Dim

' A two dimensional array is like a Table or a schedule.

' The 1st part of the subscript represents the Rows of the Table

' The 2nd part of the subscript represents the Columns of the Table.

' Visual Basic can have up to 32 dimensions, each separated by a column.

 

' A ONE dimensional array only has 1 column. Ex: Students(32) for 1 columnm with up to 32 students.
' Below is a TWO dimensional "hard coded" array as a sample only. It has rows and multiple columns.
Dim Student(30, 3) As String ' 30 rows, 3 columns (actually 31 rows and 4 cols, because arrays start at 0)

' Note: Arrays start at zero. However, I start my arrays at 1

Private Sub frmArrayDemo2Dim_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles...

    Student(1, 1) = "Al"      ' Row 1, Column 1 for first name

    Student(1, 2) = "Adams"   ' Row 1, Column 2 for last name

    Student(1, 3) = "A"       ' Row 1, Column 3 for grade

    Student(2, 1) = "Bob"

    Student(2, 2) = "Baker"

    Student(2, 3) = "B"

    Student(3, 1) = "Cindy"   ' Row 3, Column 1
    Student(3, 2) = "Carlson" ' Row 3, Column 2

    Student(3, 2) = "C"       ' Row 3, Column 3

End Sub

 

' A THREE dimensional array might have rows, columns, and multiple sheets, such as

' Rows for each Student, Columns for their grades, Sheets for each class.

 

Private Sub btnDisplayArray_Click(ByVal sender As System.Object, ByVal e As...

    ListBoxDisplayArray.Items.Clear()

    ListBoxDisplayArray.Items.Add("Name" & vbTab & "Grade")

    For Count = 1 To 3

        ListBoxDisplayArray.Items.Add(Student(Count, 1) & vbTab & Student(Count, 2)) ' Col 1, Col 2

    Next Count

End Sub

End Class

 

= = =

*** SORT ARRAY

' Thanks Daniel Dorman 04/06/2012

Private Sub btnSortArray_Click(ByVal sender As System.Object, ByVal e As ...

    Array.Sort(arrSort)

End Sub

 

Private Sub btnPrintArray_Click(ByVal sender As System.Object, ByVal e As ...

    Dim count As Integer = 1

    listSort.Items.Clear()

    While count < arrSort.Length

        listSort.Items.Add(count & vbTab & arrSort(count))

        count += 1

    End While

End Sub