Visual Basic (2008 Express)
Variables and Constants
Variables are declared using the Dim statement. The name and the data type must be given.

Eg. If we want to use a data element called ExamMark which is always going to be an integer...

 

Dim ExamMark As Integer For Global variables, replace the word Dim by the word Public
To declare a Constant use a Const statement. It must be given a value. 

For example, if we need a constant called VATRate with a value of 17.5...

 

Const VATRate  = 17.5 For Global Constants, put the word Public before the declaration.
The position of the declaration is important. If the declaration is inside a subroutine, then it is local to that subroutine.

If it is at the top, outside the subroutines, but inside the Class, it is global to the Class and can be used anywhere in that Class(Form).

If it is in a Module, then it is global to the whole project.

 
Below is the full listing of a VB program that allows the user to enter two integers, and display the addition of these two numbers in a ListBox. 

The output of the program when the inputs are 1579, 6372 and 10.
 

The program also uses a subroutine that draws a line of dashes - the number of dashes in each line is also entered by the user.

Public Class Form1

  'Global constant declared
  Dim
NumDashes As Integer

--------------------------------------------------------------------
  Private Sub DrawLine()

    'Declare local variables    
    Dim
Line As String
    Dim
i As Integer

    Line = ""
    For i = 1 To NumDashes
        Line = Line + "-"
   
Next
    ListBox1.Items.Add(Line)

  End Sub

--------------------------------------------------------------------

  Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    'Declare Local variables
    Dim
Num1, Num2 As Integer
    Dim
Result As Integer

    Num1 = InputBox("Please enter the first number")
    Num2 = InputBox("Please enter second number")
    NumDashes = InputBox("How may dashes in each line?")

    Result = Num1 + Num2

    'Add the two numbers to the ListBox    
    ListBox1.Items.Add(Num1)
    ListBox1.Items.Add(Num2)

    'Call the subroutine to draw a line
    DrawLine()

    'Add the result to the ListBox
    ListBox1.Items.Add(Result)

    DrawLine()

    Label1.Text = "Sum completed using " & NumDashes & " dashes"

  End Sub

--------------------------------------------------------------------

End Class

 

The variable NumDashes is global and can be used anywhere in the code for this Form (Class).

 

The variables Line and i are local to the subroutine DrawLine and can only be used inside that subroutine.

 

 

 

The variables Num1, Num2 and Result are local to the subroutine Form1_Load and can only be used in that subroutine.

Remember that Global public variables declared in a Module can be used on every Form in a project.

 

 

   Back