LIS 558 - Programming and Visual Basic

Visual Basic is object oriented and event driven. Objects, such as buttons and forms, have properties. Some of these properties are simple values, such as Width. Others specify methods.

A method is a procedure that is executed in response to an event. An event is an action that may affect an object, such as pressing a key, clicking the mouse, opening a form, report or table, changing a value in a field, adding a record to a table, clicking on a button, or choosing an item on a menu.

The wizards can help you by creating simple methods to deal with common types of events. For example, if you use the wizard when adding a command button to a form and select closing the form as the action, a procedure like the following is automatically created and made the method of the the button's OnClick property:

Private Sub ExitButton_Click()
On Error GoTo Err_ExitButton_Click


    DoCmd.Close

Exit_ExitButton_Click:
    Exit Sub

Err_ExitButton_Click:
    MsgBox Err.Description
    Resume Exit_ExitButton_Click
    
End Sub
You can then modify or add to the procedure to get it to accomplish more complicated tasks.

Statements

The body of a procedure contains a series of statements. Each statement is an instruction to Visual Basic to do something, such as close a form or display a message. Normally, each statement occupies one line, but a long statement can be spread over more than one line by ending each of the lines except the last with a space plus underscore ( _); for example,
    MsgBox _
        Err.Description
is the same as
    MsgBox Err.Description
There are some restrictions on where a line can be broken.

One type of statement is a reference to a procedure. The procedure referred to might be the method of an object. For example

    DoCmd.Close
tells Visual Basic to perform the procedure that is the Close method of the object DoCmd; the effect of this procedure is to close the active window.

The procedure may also be referred to directly, without referring to a particular object. For example,

    Beep
tells Visual Basic to sound a tone through the computer's speaker.

A similar type of statement is a reference to an action. For example,

    MsgBox Err.Description
tells Visual Basic to perform the action MsgBox with the Message argument Err.Description; that is, to display a message box with the text equal to the Description property of the object Err.

Arguments are used to specify the effect of a procedure or action. Arguments of actions are simply listed, separated by commas, after the action name. The list of arguments of a procedure is enclosed in parentheses. Arguments of an action or procedure in Visual Basic are often optional; so, the argument list may be empty or of various lengths, depending on what is desired.

Other kinds of statements control where Visual Basic should proceed next in other ways. For example,

    Exit Sub
tells Visual Basic to leave off performing the current procedure and go on to the next step following the point at which the procedure was called.

You can add a comment, which will be ignored by the Visual Basic compiler, at the end of line by means of the apostrophe (') or on a separate line starting with the keyword REM; for example,

    DoCmd.Close 'close the form
or
    DoCmd.Close
    REM close the form

Variables, literals, and constants

A variable is the name of a storage location for simple data such as numbers and character strings as well as for references to more complex objects. To define a new variable in a procedure, you must declare it in a Dim statement; for example,
    Dim i As Integer
It can be any of the basic data types in Visual Basic: Boolean, Byte, Integer, Long, Currency, Single, Double, Date, String, Object, or Variant. Variables are used internally to manipulate and temporarily store data in a procedure. A variable must use a letter as the first character, should not include a space or any of the characters ., !, @, &, $, #, should be no more than 255 characters long, and should generally not be the same as the name of something else.

A literal is the actual data value used directly in your procedure. For example, a string literal such as "Can not open table, check your disk files", or a numeric literal such as 324.

The = is used in procedures to change the value of a variable. The new value can be specified by a literal; for example,

    i = 57
It may also be specified by a formula; for example,
    cost = PriceEdit.Value * (1 + gst)
If the variable is a reference to an object, Set must be used before the variable name in addition to the = after it; for example,
    Dim tbx As TextBox
    Set tbx = PriceEdit
Failure to include Set will result in an "Error 91" error message when the procedure is executed.

A constant is a name for an item whose value does not change during execution. You can use the name throughout your procedure and, if you decide that you need a different value, you only have to change one line of code. Example:

    Const gst As Single = 0.07

Constants are usually declared in the Declarations section at the beginning of the code for the form or report, before the code for the specific procedures. Variables to be used by more than one procedure can also be declared in the Declarations section.

Expressions

You can use mathematical expressions using +, -, *, / for add, subtract, multiply and divide on any type of numerical variables, constants, and literals. Example:
    Dim cost As Currency
    cost = PriceEdit.Value * (1 + gst)

Strings can be concatenated by using +. Example:

    MsgBox ("Hi, " + UserNameEdit.Value + "!")

Date and time can use the + and - operators.

Functions

A function is a procedure that returns a value, such as a number. The MsgBox procedure is actually a function, which can return different values depending on how the user responds to the message. For example, the following procedure allows the user to see what numbers are returned by clicking the "Yes", "No", and "Cancel" buttons in a message box:
Private Sub FunctionButton_Click()
    Dim response As Integer
    response = MsgBox("Select your response", vbYesNoCancel)
    MsgBox ("Your reply is coded " + Str(response))
End Sub
Str is another example of a function, one that takes an integer as an argument and returns a character string.

There are no date or time literals in Visual Basic; so you must convert them with built-in functions, such as DateValue; for example,

Private Sub DaysLeftButton_Click()
    MsgBox (Str(DateValue("Jan 1, 2001") - Date))
End Sub

Structured programming

Only three basic structures are required to control the order of execution in a procedure.
  1. Sequence: this is the natural order of one statement following another.

    Example:

    Private Sub MsgsButton_Click()
        MsgBox ("This is your first message")
        MsgBox ("This is your second message")
    End Sub
    
  2. Choice: provides a choice between two actions based on a logical condition (TRUE-FALSE); sometimes called "IF-THEN-ELSE".

    Example:

    Private Sub LoginButton_Click()
        If UserNameEdit.Value <> "" Then
            MsgBox ("Hi, " + UserNameEdit.Value + "!")
        Else
            MsgBox ("You need to enter your name first.")
        End If
    End Sub
    

    NOTE: a variant of the choice structure provides a choice among more than two actions based on a switch value. Look for the Select Case statement in Visual Basic.

  3. Iteration (or loop): repeats a set of instructions while some condition remains true.

    Example 1 (While):

    Private Sub WhileButton_Click()
        While MsgBox("Do you want to keep looping?", vbYesNo) = 
    vbYes
            MsgBox ("OK, we'll loop again")
        Wend
        MsgBox ("OK, we've stopped looping")
    End Sub
    

    Example 2 (use a "for loop" if you know exactly how many times you want the code repeated):

    Private Sub ForButton_Click()
        Dim i As Integer
        For i = 1 To TimesListBox.ListIndex
            MsgBox ("Iteration #" + Str(i))
        Next
    End Sub
    

Visual Basic does not support structured programming for certain special cases, such as error handling, where control has to jump around in a somewhat unstructured manner. For example, the statements

    On Error GoTo Err_ExitButton_Click
and
    Resume Exit_ExitButton_Click
tell Visual Basic to jump out of the current structure to other, named, locations in the procedure. The locations are named with line labels. A line label can be any combination of characters that starts with a letter and ends with a colon (:) and must begin in the first column.

Generally, you should avoid unstructured programming wherever possible.

Top-down, modular design

When designing applications, it is a good idea to do some systems analysis and design before actually programming. Part of this is E-R diagramming to design the tables. Another part is to decide which functions the program must perform. One method used is to use a hierarchy diagram to divide the application into logically related parts (modules) which can be separately implemented and brought together under a main menu or command line.
Home

Last updated July 5, 2001.
This page maintained by Prof. Tim Craven
E-mail (text/plain only): craven@uwo.ca
Faculty of Information and Media Studies
University of Western Ontario,
London, Ontario
Canada, N6A 5B7