Chapter 7
Part A

Procedures

A block of code with a specific task

Sub <Procedure Name>( )
   Command
   Command
   Command
   etc.
End Sub

Using Procedures

  • Defined in text editor (outside of existing procedures)
  • Called by name
  • Execute when they are called
  • Return to where they were called from

Procedure Example

Let's define the following:
   
subroutine in Form_Load

Private Sub Form_Load()
    SubRoutine1
    SubRoutine2
   
SubRoutine3
End Sub

Adding Procedures

Type the word Sub plus procedure name

Sub Subroutine1

When you hit Enter, VB adds the parentheses and the End Sub

Sub Subroutine1( )
|
End Sub


Calling Procedures

Define the following subroutine in Form_Load

Private Sub Form_Load()
    SubRoutine1
    SubRoutine2
    SubRoutine3
End Sub

Defining Procedures

Returns error message

  • Subroutines need to be defined

    Sub Subroutine1( )
           MsgBox "This is subroutine 1"
    End Sub

  • Repeat for Subroutine2 and Subroutine3
  • Run program

 

Value Parameters

  • Values subroutines need to do their task
  • Value Parameters

    Example:

  • Private Sub Form_Load()
    Dim intNum As Integer
        intNum = 1
        MsgBox "The value before call” & intNum
        AddOne intNum ‘this is the “call”
        MsgBox "The value after call " & intNum
    End Sub

    Now lets write the subroutine:

Sub AddOne(ByVal intN As Integer)
    intN = intN + 1
End Sub

Results:

 

    The procedure leaves intNum unaffected

  • Reference Parameters

    Example:

    Now a simple change

    Sub AddOne(ByRef intN As Integer)
         intN = intN + 1
    End Sub

Results:

 

    Note the different results!

Scope of Variables

Global

  • Defined in General Declarations
  • Known throughout form

Local

  • Defined in subroutine
  • Only known in that subroutine

“Lifespan” of variables

Global

  • Born when program compiled
  • Die when program ends

Local

  • Born when subroutine called
  • Die when subroutine concludes

Static Variable

  • Only known locally like local value
  • “Lifespan” like global
  • Declared in subroutine with Static rather then Dim

Homework

Chapter 7 excercises 1, 2, 3, 4.