How to Use Arrays in Visual Basic

Arrays provide programmers with a method of assigning several values within one variable name. The technique is used when you have a list of values such as states, colors or other objects with predefined amounts. Arrays hold these lists as one variable so programmers are not forced to define several dozen variables for individual values. Like other programming languages, the Visual Basic compiler has a specific syntax used to define and fill arrays.

Instructions

    • 1

      Define your array variables. For this example, a predetermined size array is created. The next array is a dynamic array, which means the variable is resized later in the code. The following is how to create both array types:
      Dim arrStatic(0 to 2) As String
      Dim arrDynamic() As Integer
      The "arrStatic" array is set to hold three values (zero through two). The "arrDynamic" variable is set to an array, but it is set as an unknown size.

    • 2

      Assign values to your "arrStatic" array. In this example, three colors are assigned to the array variable as follows:
      arrStatic(0) = "blue"
      arrStatic(1) = "green"
      arrStatic(2) = "red"
      Notice each array element is defined by a numerical value. The number sets the point in the array dimension. These values can be retrieved or replaced using the array's dimension numbers.

    • 3

      Re-dimension the dynamic array. The "ReDim" statement is used to redefine the size of an array. "arrDynamic" is an unknown size, so before you can use it in your code, you need to define its dimensions. The following code resizes the "arrDynamic" variable:
      ReDim arrDynamic(0 to 3) As Integer

    • 4

      Assign values to the "arrDynamic" array. Since the "arrDynamic" variable is defined as an Integer, it needs to hold integer values. The code below assigns values to the dynamic array:
      arrDynamic(0) = 1
      arrDynamic(1) = 2
      arrDynamic(2) = 3
      arrDynamic(3) = 4

    • 5

      Print a value to the desktop to test the code. To test your arrays, you can print one of the values to a message box. The message box displays the value for the specific dimension. The code below illustrates how to display an array value:
      MsgBox (arrDynamic(1))
      The message box displays the number "2."

Related Searches

References

  • Photo Credit computers image by Orlando Florin Rosu from Fotolia.com

You May Also Like

Related Ads

Check It Out

Geek Vs Geek: The Best Tech of 2014