Types of Procedures

We are going to do something unconventional.  Typically a programming language is started at the basics, like definition of variables and data types.  Other elements like functions/procedures come much later.  Here we are going to begin with procedures.  VB is developing into an important tool for designing the Graphical User Interface(GUI) in a window's application.  Event driven procedures  are necessary to achieve this.  Moreover we would also like to start fooling with VB.

Procedures are units/blocks of code that typically calculate values, manipulate text or control, or interact with database operations.  They are very useful for breaking down a large programs into smaller units.  Most often you will use a procedure to execute repeated or shared tasks to avoid code duplication - (Code duplication is not wrong merely inefficient).  You can also use them as building blocks that let you easily develop other related applications fast.

(from books on line)
There are two major benefits of programming with procedures:

  Procedures allow you to break your programs into discrete logical units, each of which you can debug more easily than an entire program without procedures.
  Procedures used in one program can act as building blocks for other programs, usually with little or no modification.
There are several types of procedures used in Visual Basic:
Sub procedures do not return a value.
Function procedures return a value.
Property procedures can return and assign values, and set references to objects.
 

Sub Procedure

A Sub procedure is a block of code that is executed in response to an event. By breaking the code in a module into Sub procedures, it becomes much easier to find or modify the code in your application.

The syntax for a Sub procedure is: ( we will postpone the discussion on Private/Public/Static to later)

     [Private|Public][Static]Sub procedurename (arguments)

        statements

     End Sub 

Each time the Sub procedure is called, the statements between Sub and End Sub are executed. Sub procedures can be placed in standard modules, class modules, and form modules. Sub procedures are by default Public in all modules, which means they can be called from anywhere in the application.

The arguments for a procedure are like a variable declaration, declaring values that are passed in from the calling procedure.  We will explore this after we have defined variables

In VB, it's useful to distinguish between two types of Sub procedures, event procedures and general procedures.
 

Event Procedures When an object in VB recognizes that an event has occurred, it automatically invokes the event procedure using the name corresponding to the event. Because the name establishes an association between the object and the code, event procedures are said to be attached to forms and controls.

Syntax for a control event

    Private Sub controlname_eventname (arguments )
        statements
    End 

Syntax for a form event

    Sub Private Sub Form_eventname (arguments)
            statements
    End Sub 

  An event procedure for a control combines the control's actual name (specified in the Name property), an underscore (_), and the event name. For instance, if you want a command button named cmdPlay to invoke an event procedure when it is clicked, use the procedure cmdPlay_Click.

  An event procedure for a form combines the word "Form" an underscore, and the event name. If you want a form to invoke an event procedure when it is clicked, use the procedure Form_Click. (Like controls, forms do have unique names, but they are not used in the names of event procedures.) If you are using the MDI form, the event procedure combines the word "MDIForm," an underscore, and the event name, as in MDIForm_Load.

All event procedures use the same general syntax.
 
Although you can write event procedures from scratch, it's easier to use the code procedures provided by VB, which automatically include the correct procedure names. You can select a template in the Code Editor window by selecting an object from the Object box and then selecting a procedure from the Procedure box.
 

We will now examine event procedures and how to program them
Run the program we have created so far by clicking  the blue forward filled triangle on the toolbar
    The program compiles and executes.  You should see the image of the form with the controls we created.

  Click on any of the command button. Note that nothing happens !

While the command button by default can recognize the mouse click we have not instructed the program to respond to this event.

  Exit/terminate the program by clicking the " X " sign in the title bar of the application window
This should put us back in VB.

For the following I have retained default names for the various objects on the form.  You should work with the changes you had made earlier because this increases the effectiveness of what you learn today.

   Select Object View
   Select the second Command Button you created in the Properties Window
   Change the caption to read "Exit"
   Double click on the  second Command Button you created

This should place the code view screen in the center area and provide a template for the click event procedure.  This is the mouse click event.  We are now ready to write our first event procedure

Private Sub Command2_Click()
    End  ' exits application - this is a comment - anything right of the single quote is ignored by compiler
End Sub

   Run the application
   Click the command button
        The application should terminate and put us back into VB design environment

We have successfully executed an event procedure.
 

Event Driven Programming (EDP) :

The impetus for event driven programming comes from the popularity of the user interface(UI) that is now expected in all software.  Given the ease of navigation and the enhanced productivity that accompanies a software with the user interface, imagine the difficulty involved in getting the people to use UNIX.  Here you execute the programs on the command line.  Actually this is an exaggeration.  X-Windows and Motif have removed some of the pain, but they still lag significantly behind the PC windows or the Mac interface.
 We will examine some more aspects of event driven programing.  This time we will set up the first command button to accomplish something for us. We will select the button in a different way

   Select Code View
   Using the left drop down button at the top select the first Command Button you created
   Click on the right drop down button.  Examine the name of all the events that the object selected on the left supports.
   Lets place the following pieces of code by selecting the object and the event through the drop down list
 

 Private Sub Command1_Click()
    Text1.Text = "command button 1 is clicked"     ' the Text property of Text1 is changes
    Label1.Caption = "Why me ?"                ' the caption property of Label1 is changed
End Sub
 

Private Sub Command2_Click()
    End
End Sub

Private Sub Label1_Click()
    Label1.BackColor = vbGreen   ' the background color property of Label1 1 changes
 
End Sub

Private Sub Text1_LostFocus()
    Label2.BorderStyle = 1       ' the border style property of Label2 is changed
End Sub
 

   Run the application
 

    When the application starts notice that the cursor is in the Textbox.  This is the same as saying that the Textbox has got the focus.

   Click the command button 1
 

When you click on command1 - two events have simultaneously take place. (1) the Command Button 1 click event was launched and (2) the Textbox lost focus.  The click event of the command button changed the text in the Textbox and the caption of Label1.  The loss of focus of the Textbox caused a change in the appearance of Label2.  Clicking Label1  ( generally not done - since label basically is a container for descriptive text) causes Label1 to change color - here a VB constant "vbGreen" is used .
 
   Click the command button 2
 
The application should terminate and put us back into VB design environment

General Procedures :

We saw the event procedure respond to an event triggered by the mouse or the cursor.  A general procedure is used to   accomplish a specific task.  It must be deliberately invoked by the program.   By contrast, an event procedure remains idle until called upon to respond to events caused by the user or triggered by the system.

One reason to write a general procedure is that is that several different event procedures might need the same actions performed. A good programming strategy is to put common statements in a separate procedure (a general procedure) and have your event procedures call it.

Avoid writing event procedures until you have frozen the Name of the Object.  This allows you to use event procedure templates provided by VB.  If the name is changed after writing the procedures then you will have to change the name of the procedure too for VB to recognize it as an event procedure.  If VB does not recognize it as an event procedure it is considered a general procedure

It is a good idea to have event procedures call general procedures

For the code below:

Screen Shot of the Form at design Time


 

Screen shot of the form at Run Time


 

Examples of General Procedures

Private Sub Command1_Click()
         Text1.Text = "command button 1 is clicked"     ' the Text property of Text1 is changes
         Label1.Caption = "Why me ?"  ' the caption property of Label1 is changed
 
         ' Example of a general procedure
         Label_ColorChange    ' a general procedure without arguments
         Call Locate_Text       ' a similar one but notice another way to call it
End Sub
 
Private Sub Command2_Click()
   MsgBox "Do You want to quit", vbOKOnly, "Quit" ' Using built in MsgBox Function
   End
End Sub
Private Sub Label1_Click()
    Label1.BackColor = vbGreen       ' the background color property of Label1 1 changes
End Sub

Private Sub Text1_LostFocus()
     Label2.BorderStyle = 1           ' the border style property of Label2 is changed
End Sub
Private Sub Label_ColorChange() ' a general procedure
    Label1.BackColor = RGB(75, 175, 203)    'Using RGB function
    Label2.BackColor = RGB(25, 100, 100)
    Label2.ForeColor = RGB(255, 255, 255)
    Text2.Text = "Did you see the changes in color"
End Sub
Private Sub Locate_Text()    'another general procedure
    Label1.Left = 50            ' location the objects in code
    Label1.Top = 50
    Label1.Height = 500
    Label1.Width = 1000
 
    With Label2     ' the built in with keyword simplifies coding
        .Left = 50
        .Top = Label1.Top + Label1.Height + 50
        .Height = Label1.Height
        .Width = Label1.Width
    End With
 
    Text1.Left = Label1.Left + Label1.Width + 50
    Text1.Top = Label1.Top
 
    With Command1
        .Left = 50
        .Top = Label2.Top + Label2.Height + 50
    End With
 
    Command2.Top = Command1.Top
    Command2.Left = Command1.Left + Command1.Width + 50
    Command2.Height = Command1.Height
 
    Text2.Left = 50
    Text2.Top = Command1.Top + Command1.Height + 50
 
End Sub

 
                We are now familiar with both kinds of Sub procedures
 

Function Procedures

 A Function procedure is another kind of  procedure, similar to a Sub procedure  for it  can take arguments, perform a series of statements, and change the value of its arguments. However, unlike a Sub procedure, a Function procedure can return a value to the calling procedure.

There are three differences between Sub and Function procedures: (books on line)
 

  Generally, you call a function by including the function procedure name and arguments on the right side of a larger statement or expression
        returnvalue = function()

  Function procedures have data types, just as variables do. This determines the type of the return value. (In the absence of an As clause, the type is the default Variant type.)

  You return a value by assigning it to the procedurename itself. When the Function procedure returns a value, this value can then become part of a larger expression.
 

Visual Basic includes built-in, or intrinsic functions, like Sqr, Cos or Chr. In addition, you can use the Function statement to write your own Function procedures.

The syntax for a Function procedure is:
 

[Private|Public][Static]Function procedurename (arguments) [As type]

    statements

End Function

Property Procedures

Property procedures are typically use to set an object's property or to get the value of an object's property.  This will be useful when we define our own classes and objects.

Here we  just accept the following information
 

Visual Basic provides three kinds of property procedures depending on the purpose
 

Property Get Returns the value of a property.

Property Let Sets the value of a property.

Property Set Sets the value of an object property (that is, a property that contains a reference to an object).

Each of these property procedures has a particular role to play in defining a property. The typical property will be made up of a pair of property procedures: A Property Get to retrieve the property value, and a Property Let or Property Set to assign a new value.