65
Visual Basic for Application - Microsoft Access 2003 Introduction

Visual Basic for Application - Microsoft Access 2003 Introduction

Embed Size (px)

Citation preview

Page 1: Visual Basic for Application - Microsoft Access 2003 Introduction

Visual Basic for Application - Microsoft Access 2003

Introduction

Page 2: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST2

Course objectives

• You will learn how to:

– Create code modules

– Create and call procedures

– Use variables and constants to store values

– Use arrays

– Use naming conventions

– Control the flow of programs

– Document code

– Debug and handle errors

Page 3: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST3

VBA Model

• Before you can start to program, you must understand the VBA model. In order to do that, you need to learn the hierarchy of structures:

– Modules: The module is the place where VBA code is written and stored. You can keep related sections of code in separate modules, which facilitates the ability to organize your code efficiently. Modules are divided into several types:

The form and report modules hold code associated with a particular report or form. As a matter of fact, if that form or report is moved to another database, the module holding the code usually moves with it.

The standard module holds code that has no association with a particular database object. Most of your coding will be in a standard module.

– Procedures: The code within the module is divided into blocks called procedures. Most procedures should only perform one specialized job. Procedures fall into two categories:

sub procedures functions

Page 4: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST4

VBA Editor

• In order to create VBA code, you need to use the VBA Editor.• Open the VBA editor: go to Tools | Macro | Visual Basic Editor• If you had no object selected, the editor would appear empty. If you

had an open database when you accessed the editor, it would appear with non-empty windows that would display contents related to the db.

• The VBA editor is divided into distinct windows to help you handle various aspects of your project:

1

32

4

Page 5: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST5

VBA Editor

1. Project window – This window helps you maneuver to the various code modules associated with your project. One of the main uses of this window is to find and open the various modules that hold your code.

2. Properties window – This window shows the various properties that can be set for the selected form.

3. Immediate window – This window allows you to test your code.

4. Code Window – you will type your procedures and functions in this window.

Page 6: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST6

Creating Modules

• Definition: Modules are best described as containers for holding VBA code. Modules can contain declarations and procedures. VBA code that is placed in one or more modules can be called from an Access application to perform a specified task.

1. Object navigation box – Use to select the object to work with

2. Declarations/Procedure navigation box – Use to navigate to the general declarations section or to a particular procedure

3. Declarations – Contains the declarations for the module

4. Procedures – Contains the sub procedures and functions for the module

1

4

3

2

Page 7: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST7

Creating Modules

• In the VBA editor go to: Insert | Module• VBA assigned your new module a temporary name of Module1.

You will probably want to give it a more descriptive name. This can be done from the Properties window of the VBA Editor or directly in the Database window.

• In addition, you should click on the Save icon in the toolbar. You will be prompted to confirm the name.

• Now you can confirm that the name has been changed in the Project window and the Database window:

Page 8: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST8

Creating Modules – Exercise 1

1. Create a new database and save it as “Exercise1.db”

2. Add a new form to your database. And switch to Design View.

3. Use the controls shown in the toolbar to select and draw two text boxes and one command button (select Cancel to exit the Button Wizard that appears after you draw the button on the form) onto the form, as shown here:

4. Change the Name properties of the first text box, second text box, and command button to txtValue1, txtValue2, and cmdRun, respectively.

Page 9: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST9

Creating Modules – Exercise 1

5. Change the Name property of the first text box label to lblValue1 and its Caption property to Value 1. Change the Name property of second text box label to lblValue2 and the Caption property to Value 2. Change the cmdRun Caption property to Run. After these changes, the finished form should look like that:

6. Save the form and specify the name for the form as frmTest.

7. Create a new module.

8. The Visual Basic Editor window appears. Use the Properties window of the Visual Basic Editor to rename the module to modBusinessLogic.

Page 10: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST10

Creating & Calling Procedures

• Definition: Procedures are the building blocks of modules. Each module contains one or more sub procedures or functions, and each sub procedure or function contains one or more VBA code statements.

• Difference between Sub & Function Procedure:

Procedures can either be sub procedures or function procedures. – A sub procedure performs an action but does not return a

particular result.

Declaration: Sub Name_of_Sub_Procedure(Arguments) – A function performs an action and returns a particular result.

Declaration: Function Name_of_Function(Arguments) As Type

Sub procedures and functions can be called both from within other procedures and functions and when an event associated with an object is triggered.

Page 11: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST11

Creating & Calling Procedures

• Example of a Sub Procedure named “Concat”:Sub Concat()

   Dim strFirstname As String    Dim strLastName As String   Dim strFullName As String

    strFirstname = "John"    strLastName = "Smith"

    strFullName = strFirstname & " " & strLastName    Debug.Print strFullName

End Sub

Don’t worry about all the particulars of this sub procedure right now.– The procedure opens with the line: Sub + name of the procedure

+ () (example: Concat() ) – The sub procedure ends with the line: End Sub

Code inside the procedure

End of the procedure

Start of the procedure

Page 12: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST12

Creating & Calling Procedures

• Example of a Function named “Concat” returning a String:Function concat() As String

Dim strFirstname As String    

Dim strLastName As String    

Dim strFullName As String    

strFirstname = "John"    

strLastName = "Smith"    

strFullName = strFirstname & " " & strLastName

concat = strFullName

End Function

– The function opens with the line: Function + name of the function + () + As + Type of the data returned

– The funtion returns the String variable whose has the same name (concat). You must not declare it in the code.

– The function ends with the line: End Function

Code inside the function

End of the function

Start of the function

Variable returned

Page 13: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST13

Creating & Calling Procedures

• VBA gives a handy tool to assist in building procedures and functions. It is called the “Add Procedure” dialog box and can be found in the Insert menu:

Page 14: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST14

Creating & Calling Procedures

• The previous procedures have been self-contained. Usually, the variables within your procedures will need to get their values from an outside source.

• To do this, you need to set up parameters in the parentheses after the procedure’s name. In programming terminology, the process of sending information to those variables is called passing parameters.

Function fullName(strFname As String, strLname As String) As String    

Dim strFirstName As String    Dim strLastName As String    Dim strFullName As String    strFirstName = strFname    strLastName = strLname    strFullName = strFirstName & " " & strLastName    fullName = strFullName

End Function

Page 15: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST15

Creating & Calling Procedures

• Let’s go to the Immediate window and type the following:? fullName ("Jane", "Doe")

• The call sends two arguments: The first one goes to strFName, and the second goes to strLName.

• Let’s set up our module with a second procedure now:Sub getName()    

Dim strFirstName As String    Dim strLastName As String    Dim strFullName As String    strFirstName = InputBox("Enter the First Name", "First

Name")    strLastName = InputBox("Enter the Last Name", "Last

Name")    strFullName = fullName(strFirstName, strLastName)    MsgBox strFullName, , "Full Name"

End Sub

Page 16: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST16

Creating & Calling Procedures

• Advice: You should try to group procedures in the modules with their dependence in mind.

For instance, you may want all the procedures for formatting names in one module, while the procedures to do date calculations are in another module.

• In practice, you preface procedures with the keywords Public or Private: – Public means that the procedure can be accessed by another

procedure in another module. – Private means that it can be accessed only by procedures in the

same module.

• Many times you will make only one or two procedures public. In programming terms, these procedures serve as the module’s interface. In other words, this is the controlled access point to the module from other modules.

Page 17: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST17

Creating & Calling Procedures – Exercise 2

• Let’s now create a new procedure for frmTest using the VBA editor.1. Return to the database window and open frmTest in design view.2. Select the cmdRun button on the form and open the Properties

window.3. Select the Event tab from the cmdRun Properties window. Click the On

Click event from the list and select “[Event ¨procedure]”.4. Click right on the command button and select « Build Event ».5. The Visual Basic Editor will now be displayed with the cursor flashing

in a newly created empty procedure called cmdRun_Click

Page 18: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST18

Creating & Calling Procedures – Exercise 2

6. Add the following code to the newly created procedure:Private Sub cmdRun_Click()

'declare variables to store price and avail credit

Dim curPrice As Currency

Dim curCreditAvail As Currency

'assign variables from current values in text boxes on Form

curPrice = txtValue1

curCreditAvail = txtValue2

'call VerifyCreditAvail procedure

VerifyCreditAvail curPrice, curCreditAvail

End Sub

7. Add the following procedure which verifies if there is enough creditSub VerifyCreditAvail(curTotalPrice As Currency, curAvailCredit As Currency)

'inform user if not enough credit for purchase

If curTotalPrice > curAvailCredit Then

MsgBox "You do not have enough credit available for this purchase.”

End If

End Sub

Page 19: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST19

Creating & Calling Procedures – Exercise 2

8. click the Save button in the Visual Basic Editor to make sure all code so far has been saved.

9. Return to the frmTest form and open it in View mode to run it. Input a value of 2000 for Value 1 and 1500 for Value 2.

10. You should see the same message box indicating that not enough credit is available.

Page 20: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST20

Using Variables to Store Values

• Definition: A variable is a piece of information stored somewhere in the computer’s memory. It could be a number, a letter, or an entire sentence. The location where it is stored in memory is known by the variable name.

• Various types of variables can be declared and used in your procedures. The most common variables are String, Integer, Long, Currency, and Date.

• Variables can be declared using the Dim statement.Examples: Dim strMessage As String

Dim rsSales As Adodb.Recordset Dim intCounter As Integer

Dim blnResponse As Boolean

Page 21: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST21

Using Variables to Store Values

• After it is declared, a variable obtains its value (is assigned) by setting the variable equal to a value or to an expression that evaluates to a value. Example:

Sub TestObjectVariable()

'declare an String variable

Dim strMessage As String

'set the value of the String variable

Set strMessage = “Hello World"

'set the value of the String variable to the txtValue1 text box

Set strMessage = Me.txtValue1

End Sub

Page 22: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST22

Using Variables to Store Values

Data type What it stores Corresponding Access Data type

Attachment File attachment Attachment

Boolean True or False Yes/No

Byte Positive integers from 0 to 255 Number (Byte)

Currency Positive and negative currency values with four decimal places

Currency

Date Date and time from 1/1/0100 to 12/31/9999

Date/Time

Double 8-byte decimal values Number (Double)

Integer 2-byte integers from –32,768 to +32,768 Number (Integer)

Long 4-byte integers from –2 billion to +2 billion

Number (Long Integer) or AutoNumber (Long Integer)

Object Access object reference

Single 4-byte decimal values Number (Single)

String (Fixed length) From 1 to 65,000 characters Text or Memo

Page 23: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST23

Using Variables to Store Values

• A variable is only visible within the procedure and will only exist until the procedure completes its job but there are two exceptions — global variables and static variables:– Global variables: The variable will be available to all the procedures in the

module. In order to set one, you have to declare it at the top of the module in the general declaration area, after the 2 lines:

Option Compare Database Option Explicit Private strFullName As String

Private means it can only be seen by procedures in the module. Public means it can be accessed by other modules but that is not a very secure way of doing things.

– Static variables: A static variable is one that will stay in memory after the procedure has completed its job. However, it can only be accessed by that procedure.

Sub staticTestProcedure()    Static intCounter As Integer    intCounter = intCounter + 1    Debug.Print intCounter

End Sub

Run several times this procedure and check the variable intCounter:

Page 24: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST24

Using Constants to Store Values

• Definition: A constant is a type of variable that maintains a constant value that does not change. Unlike traditional variables, constants are assigned values when you create them.

• Constants are declared with the Const statement instead of the Dim statement.

Examples: Const conRate as Double = 12.5 Const conWelcomeMessage as String = "Welcome to

my first VBA application."

• Why to use Constants?– help improve the readability of your code. – make your code easier to maintain

Page 25: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST25

Naming Conventions

Data type Prefix Example

Boolean Bln blnResult

Byte Byt bytResponse

Currency Cur curTotalSales

Date Dt dtBirth

Double Dbl dblGPA

Integer Int intCount

Long Lng lngTrackingNum

Object Obj objControl

Single Sng sngResult

String Str strMessage

Data type Prefix Example

Class module Cls clsProject

Form Frm frmMain

SubForm Fsub fsubMainDetail

Macro Mcr mcrAutoExec

Module Mod modBusinessLogic

Query Qry qryCalculateSales

Report Rpt rptAnnualSales

SubReport Rsub rsubAccountExecutives

Table Tbl tblSales

Variables Objects

• Definition: provides a standardized way of naming objects and variables in order to always know through the code which data type the variable/object is.

Page 26: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST26

Using Constants – Exercise 3

1. In the modBusinessLogic standard module, go to the General Declarations section.

2. Add a public constant called strTest to the General Declarations section.

Page 27: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST27

Using Arrays

• Definition: An array is a variable that contains multiple values. The number of values that the variable will hold must be decided and declared in advance.

• Components of an array:– Each value in the array is called an element. – Since an array variable has multiple elements in it, you can reference

them them individually by using a number called an index. – The first element of an array is index number 0.

For example: strName (0) “John Smith”                

(1) “Jane Doe”                

(2) “Rosemary Brown”                

(3) “Anita LaScala”                

(4) “Bob Gray”

If you wanted to select Anita LaScala’s name out of the array for printing, you would use: Print strName(3)

Page 28: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST28

Using Arrays

• VBA proposes two types of arrays:– Static array  The number of elements in the array, called the length

of the array, is decided in advance and remains fixed.– Dynamic array  The length of the array is variable and not decided

in advance.

• Static arrays: – Declaring a static array is similar to declaring a variable, with one

small exception:Dim intMyScores(10) As Integer

Be careful! How many elements have you declared in this array? Answer: 11Because the lower bound, or lowest index number, of this array is 0.

– By default, the first index value is 0, strings are initialized as empty, and integers are initialized at 0.

Page 29: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST29

Using Arrays

• Example:Sub arrayTest()

Dim i As Integer

Dim intMyScores(10) As Integer

For i = 0 To 10    

intMyScores(i) = InputBox("Enter number " & i, "Static Array Test")

Next

For i = 0 To 10    

Debug.Print "For array element " & i & " the number is " & intMyScores(i)

Next

End Sub

• You could change the syntax of the For loop in the previous code as follows:

For i = LBound(intMyScores) To UBound(intMyScores)  

intMScores(i) = InputBox("Enter number " & i, "Static Array Test")

Next

Page 30: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST30

Using Arrays

• Dynamic Arrays: It is still a static array, but you do not declare the size until the program is running. So the only issue is when the size is being declared.– You start off by declaring an empty array: Dim intMyScores() As Integer

– Then you use a keyword, ReDim, to redeclare the size of the array while the program is running and it is known what the size will be.

Sub arrayTest()

Dim i As Integer

Dim intMyScores() As Integer

Dim intArraySize As Integer

intArraySize = InputBox("How many scores are you entering?", "Array Size")

ReDim intMyScores(intArraySize)

For i = 0 To intArraySize    

intMyScores(i) = InputBox("Enter number " & i-1, "Static Array Test")

Next

For i = 0 To intArraySize    

Debug.Print "For array element " & i-1 & " the number is " & intMyScores(i)

Next

End Sub

Page 31: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST31

Using Arrays

• Make an array smaller: The Preserve keyword reallocates the memory and retains the elements intact.

ReDim Preserve intMyScores(4)

• Erase an array: clear the contents but keeps the declaration:Erase intMyScores

• IsArray: How do you know if a variable is an array?Sub arrayTest()   

Dim intScores1 As Integer   

Dim intScores2(4) As Integer    Debug.Print "Is intScores1 an array: " & IsArray(intScores1)   

Debug.Print "Is intScores2 an array: " & IsArray(intScores2)

End Sub

IsArray is a Boolean function. It returns a value of either True or False.

Page 32: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST32

Control Structures

• Decision Making Structures

Various statements you can use to make decisions in your code and then take an appropriate action depending on the result. – If … Then can be used to make decisions and perform

certain actions depending on whether the conditions are met. – Conditional If enables to selectively compile and execute

certain blocks of code. – Select … Case can be used to easily evaluate the same

variable multiple times and then take a particular action depending on the evaluation.

– Iif can be used to return one of two possible values depending on whether the condition being tested is true or false.

Page 33: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST33

Control Structures

• Example of a If… Then structure in a subroutine:Sub ifTest()    

Dim intNum As Integer    

Dim strMessage As String    

intNum = 12    

If intNum > 10 Then        

strMessage = "The number is " & intNum    

End If    

Debug.Print strMessage

End Sub

• The line that contains the conditional expression begins with If and ends with Then.

• Also, like other structures in VBA, the conditional If structure must end with an End statement, in this case End If.

Page 34: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST34

Control Structures

• But what happens if the number is not greater than 10?Sub ifTest()    

Dim intNum As Integer    

Dim strMessage As String    

intNum = 9    

If intNum > 10 Then        

strMessage = "The number is greater than 10"    

Else        

strMessage = "The number is less than 10"    

End If    

Debug.Print strMessage

End Sub

• Notice that an Else statement has been added. since the Else statement is part of the If statement, it does not need a separate End.

Page 35: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST35

Control Structures

• Example of a ElseIf Structure structure in a subroutine:Sub ifTest()      

Dim intNum as Integer      

intNum = InputBox("Enter a number between 1 and 15", "Testing the If structure")     

If intNum = 1 Then            

Debug.Print “This is the lowest number”      

ElseIf intNum = 15 Then            

Debug.Print “This is the highest number”      

Else            

Debug.Print “The number is between 1 and 15”      

End If

End Sub • You can combine several If structures using ElseIf as many as

necessary to perform as many conditional tests as necessary.

Page 36: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST36

Control Structures – Exercise 4

1. Now, it’s your turn to create a new procedure and makes uses of If…Then statements. In the modBusinessLogic standard module, add the following TestIfStatement procedure:

Sub TestIfStatement()

'declare variable to store sales tax value

Dim curSalesTax As Currency

'call function to calculate sales tax

curSalesTax = CalculateSalesTax(500, 0.05)

'evaluate sales tax and write proper message 'to debug window

If curSalesTax <= 10 Then

Debug.Print "You are lucky - the amount of tax is nominal."

ElseIf curSalesTax > 10 And curSalesTax <= 50 Then

Debug.Print "The amount of sales tax could have bought you a nice meal."

Else

Debug.Print "You bought a really nice item for that tax amount."

End If

End Sub

2. From the Immediate Window, run the new TestIfStatement procedure. The result is displayed in the Immediate Window.

Page 37: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST37

Control Structures

• If you find yourself using a lot of ElseIf structures, you may want to consider the Select Case structure.

• Example of a Select Case Structure structure in a subroutine:Sub ifTest()      

Dim intNum as Integer      intNum = 2      Select Case intNum      Case 1            

Debug.Print "This is the lowest number"      Case 15            

Debug.Print "This is the highest number"      Case Else            

Debug.Print "The number is between 1 and 15" 

End Select End Sub

• The Case Else statement is optional, but it is strongly recommend that you always use it to have all your bases covered.

Page 38: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST38

Control Structures – Exercise 5

• Let’s create a new procedure that makes use of a Select...Case statement to illustrate this:

1. Add the following TestCaseStatement procedure to the modBusinessLogic standard module.

Sub TestCaseStatement(strCountry As String) 'evaluate the value of strCountry and display applicable result in debug

window Select Case strCountry Case "Italy"

Debug.Print "The buildings dating back to 400 BC are incredible." Case "China"

Debug.Print "Great bargains for shoppers." Case "Russia"

Debug.Print "A beautiful country with a growing democracy." Case "Germany" Debug.Print "Fantastic food - you will not starve there."

Case Else Debug.Print “Every country has its own speciality.“

End Select End Sub

2. Run the TestCaseStatement procedure from the Immediate Window and specify "Italy" as the parameter. Click Enter to run the procedure. The resulting value is then displayed in the Immediate Window.

Page 39: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST39

Control Structures

• There is one other structure, IIF, referring to as the Immediate If.

• The syntax is: IIF(conditional test, value for True, value for False)

Example:strMessage = IIF(intNum > 10, “Number is greater than

10”, “Number is less than 10”)

• The performance of the IIF structure is somewhat slow and rarely used by programmers in a larger programming project.

Page 40: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST40

Control Structures

• Loops StructuresVarious types of loops can be used to have a block of code repeated a certain number of times or until an event of some sort happens. The number of times the code repeats can be controlled by a counter.– For … Next and For Each … Next (counter-controlled loop)

can be used to run the same code a particular number of times.

– Do … Loop (sentinel-controlled loop) can be used to run the same code a particular number of times

– While … Wend executes repeatedly while a certain condition is met. When the condition is no longer met, the loop terminates.

Page 41: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST41

Control Structures

• Example of a counter-controlled repetition:– Counter: This is the heart of the loop. It tracks the number of times

the loop has repeated.– Start: This is the starting number for the counter. It is rare, if ever,

to set this to anything else but 1. (Occasionally you may use a different start number for mathematical calculations.)

– End: This number marks the end of the loop, where you want the counter to stop.

– Step: You can specify a number for the counter to increment with each loop. This part is optional.

Sub forTest() Dim intCounter As Integer For intCounter = 1 To 10    

If (intCounter Mod 2) = 0 Then        Debug.Print intCounter & " is an even

number"    Else        

Debug.Print intCounter & " is an odd number"    

End If Next

End Sub

Page 42: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST42

Control Structures – Exercise 6

1. Place this code for the TestLoop procedure in the modBusinessLogic standard module.

Sub TestLoop()

'declare variable to store Counter

Dim intCounter As Integer

'increment intCounter from 1 to 5 and

'display output in debug window

For intCounter = 1 To 5

Debug.Print intCounter

Next intCounter

End Sub

• Run the TestLoop procedure from the Immediate Window.

Page 43: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST43

Control Structures

• Example of sentinel-controlled repetitions:– Do While: The Do While loop tests to see if a condition is true. If it

is true, the statements in the loop execute.

Sub doTest()    

Dim intCounter As Integer    

Dim intTest As Integer    

intTest = 1    

intCounter = 1    

Do While intTest = 1        

Debug.Print "This is loop number " & intCounter        

If intCounter >= 5 Then           

intTest = 0        

End If        

intCounter = intCounter + 1    

Loop

End Sub

Page 44: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST44

Control Structures

– Do Until: This is a subtle variation of Do… What loop. In a Do While loop, you run the loop while a condition is true. However, in a Do Until loop, you run the loop until a condition becomes true.

Sub doTest()    Dim intCounter As Integer    Dim intTest As Integer    intTest = 1    intCounter = 1    Do Until intTest <> 1        

Debug.Print "This is loop number " & intCounter        If intCounter >= 5 Then            

intTest = 0        End If        intCounter = intCounter + 1   

Loop End Sub

Page 45: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST45

Documenting the code

• Definition: It allows someone to be able to understand the purpose of each procedure and why it was written in a certain way if he has to maintain the code alone.

• How to document the code?– use a general comment section at the beginning of each

procedure

– use in-line comments to describe each segment of codeExample: 'display a message to the user

Msgbox "Demonstration of In-Line commenting"

Page 46: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST46

Debugging Code

• Types of Errors:– Syntax errors occur because the code you wrote does not

comply with the required syntax. Example: Dim intCounter Integer => The As word is missing!

– Compile errors are discovered on compilation that may have a correct code syntax.

Example: A function cannot be located => not defined in the code.

– Runtime errors occur at runtime when the code executes because of something that it not allowed or supposed to happen.

Example: A line of code that tries to assign a variable of one data type to an incompatible value.

– Logic errors are flaws in the logic of your code. Logic errors can be the hardest to find because they are syntactically correct but can only be discovered by testing your code and ensuring it produces the desired and appropriate result.

Page 47: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST47

Tools for Debugging Code

• Using Breakpoints to Step through Code:– The breakpoint enables you to closely monitor and determine

the values of variables and take other actions that will allow you to test and review your code most effectively.

– Breakpoints can be set on one or more lines of code. – When a line of code that has an associated breakpoint is

reached, code execution stops and you can then choose to Step Into, Step Over, or Step Out of the code.

Selecting the Step Into option from the Debug menu will run the current line of code at the breakpoint.

The Step Over option will skip the current line of code at the breakpoint and move on to the next line of code.

Example: use of debug.print (in a loop)

Page 48: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST48

Tools for Debugging Code

• The Immediate window (go to View | Immediate Window) offers a variety of tracing and debugging tools that are quite easy to use:

Sub addNumbers()   Dim intNumber1 As Integer   Dim intNumber2 As Integer   Dim intSum As Integer   intNumber1 = 5   intNumber2 = 3   intSum = intNumber1 + intNumber2      Debug.Print "The sum of the two numbers is: " & intSum

End Sub

• You can run procedures by clicking on the Run button or by simply typing its name into the Immediate window,

• You can also set a breakpoint in the code. This tool allows you to set a point for the code to halt and wait for you to tell it to resume operation. You can set a breakpoint by clicking in the margin to the left of the line where you want to stop the code.

Page 49: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST49

Tools for Debugging Code

• Let’s stop the code where the two variables are added and assigned to the sum. You should see the code highlighted at the breakpoint:

• There are several ways to check the assignments to the variables. As an example, you can put the mouse pointer right over the variable name and a tool tip will show you the assigned value.

• You could also test the value in the Immediate window by typing a question mark followed by the name of the variable you are testing.

Page 50: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST50

Tools for Debugging Code – Exercise 7

1. Navigate to the TestLoop procedure you created previously in the modBusinessLogic standard module.

2. Set a breakpoint on the Debug.Print and the Next intCounter lines of code. You can set a breakpoint by pointing and clicking the cursor just to the left of the line of code where you want to add a breakpoint.

3. Next, open the Immediate Window and run the TestLoop procedure. The code will stop execution at the first breakpoint.

4. While at the breakpoint, use the Immediate Window to inquire about the current value of the intCounter variable. To do so, type ? intCounter and press Enter.

Page 51: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST51

Tools for Debugging Code – Exercise 7

5. The current value of intCounter is displayed in the Immediate Window. You should press F5 or select Run Continue to keep executing the lines of code. Execution will stop on each breakpoint.

Page 52: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST52

Tools for Debugging Code

• Using Locals Window: (go to View | Locals Window)– With a breakpoint set, the Locals window will show any objects and

variables assigned in the procedure, as well as the current values assigned to them.

– As an example, if you set a breakpoint at the addition point and run the procedure, the code will halt there. You then select View | Locals Window to open the Locals window.

– Here you find the assigned values, at that point, for the two variables. Since the code was halted before the addition took place, intSum is showing a value of 0. You can also click on one of the values, change it, and press ENTER. This will assign a new value to the variable in much the same way that you did in the Immediate window earlier.

– The Locals window also allows you a rather unique way to trace your code with the Debug toolbar. Select View | Toolbars | Debug. One of the buttons, Step Into, allows you to walk through the code one line at a time.

Page 53: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST53

Tools for Debugging Code – Exercise 8

• Display the Locals Window by selecting View Locals Window.

• Run the TestLoop procedure again from the Immediate Window.

• The code execution will again stop when the first breakpoint is reached. Notice that the values in the Locals Window are updated with the current value of intCounter.

• Press F5 or select Run Continue to keep executing the lines of code. You should see that the values of intCounter in the Locals window change as you walk through the code.

Page 54: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST54

Tools for Debugging Code

• Using Watch Window: (go to View | Watch Window)It allows you to set a condition to test for and stop the code if the condition is not met. – Let’s assume you want to test to see if intNumber2 was assigned a

value of 3. – Start off by highlighting the statement. Then select Debug | Add

Watch.– You can then tell it to just watch the expression, break if the

expression is true, or break if the value changes.

– Once it runs, the value will show and the appropriate action will be taken depending on your choices

Page 55: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST55

Tools for Debugging Code – Exercise 9

1. From the Debug menu in the Visual Basic Editor, choose Add Watch.

2. On the Add Watch dialog box, specify intCounter as the Expression, TestLoop as the procedure, and modBusinessLogic as the Module.

3. Click the OK button on the Add Watch dialog box, and a Watch Window will appear.

4. Run the TestLoop procedure again from the Immediate Window. You should see the values in the Watch Window change when the first breakpoint is encountered.

Page 56: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST56

Handling Errors

• Handling Errors with an On Error Statement:– On Error statement: The On Error statement can be placed

on your procedure to specify a section in the procedure to which the execution should jump when an error occurs.

Example: Sub Test() On Error GoTo HandleError 'normal code for the procedure goes hereExit Sub HandleError: 'code for handling the error goes here Exit Sub End Sub

– On Resume statement: The Resume statement will cause code execution to resume at the line that caused the error, and the Resume Next statement will cause code execution to resume at the line following the one that caused the error. Resume statements are commonly added within the error-handler routines.

Page 57: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST57

Handling Errors

• Let’s begin with a simple coding example where you will intentionally cause a runtime error to happen: Sub errorTest()    

Dim intNumerator As Integer    Dim intDenominator As Integer    Dim intResult As Integer

intNumerator = InputBox("Please enter a numerator", "Numerator")    intDenominator = InputBox("Please enter a denominator", "Denominator")    intResult = intNumerator / intDenominator    MsgBox "The result is " & intResult

End Sub

Notice that if 0 is entered as the denominator, you will get an error message 11 “Division by zero”.

Page 58: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST58

Handling Errors

• We have error handling and an error handler, but when we dismiss the error message, the program ends. Wouldn’t it be far better to have a way to return the user to the input box to reenter the denominator? Let’s make some others modifications:Sub errorTest()    

Dim intNumerator As Integer    Dim intDenominator As Integer    Dim intResult As Integer    On Error GoTo mytrap

intNumerator = InputBox("Please enter a numerator", "Numerator")    

intDenominator = InputBox("Please enter a denominator", "Denominator")    

intResult = intNumerator / intDenominator    MsgBox "The result is " & intResult

Exit Sub

mytrap:    MsgBox "You cannot divide by zero"

End Sub

Page 59: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST59

Handling Errors

• Do you really want your end user to see this error box? Wouldn’t you like a more graceful way of helping your user to get out of this? Let’s make some modifications:Sub errorTest()    

Dim intNumerator As Integer    Dim intDenominator As Integer    Dim intResult As Integer    On Error GoTo mytrap

intNumerator = InputBox("Please enter a numerator", "Numerator")    enterDenominator:

intDenominator = InputBox("Please enter a denominator", "Denominator")    

intResult = intNumerator / intDenominator    MsgBox "The result is " & intResult

Exit Sub

mytrap:    MsgBox "You cannot divide by zero" Resume enterDenominator

End Sub

Page 60: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST60

Handling Errors

• Using the Err object:– The Err object contains information about runtime errors that occur

when the code executes. It provides useful information to users or to the system to help determine what action should be taken.

– The Err object has a global scope. You need not declare it. Some examples of the properties available for the Err object include Number, Description, HelpContext, HelpFile, and Source. Number and Description are the most commonly used properties of the Err object.

Example: Err.Raise number, source, description, helpfile, helpcontext

Page 61: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST61

Handling Errors

• Example:Sub errorTest()    

Dim intNumerator As Integer    

Dim intDenominator As Integer    

Dim intResult As Double    

On Error GoTo mytrap        

intNumerator = InputBox("Please enter a numerator", "Numerator")

enterDenominator:       

intDenominator = InputBox("Please enter a denominator", "Denominator") intResult = intNumerator / intDenominator        

MsgBox "The result is " & intResult    

Exit Sub

mytrap:    

MsgBox "The number of this error is " & Err.Number    

MsgBox "The description of the error is " & Err.Description    

Resume enterDenominator

End Sub

Page 62: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST62

Handling Errors

• When the error is raised, the code then jumps to the error handler just as if the error had occurred in the traditional fashion.

• But there was the possibility of multiple things going wrong. Let’s make some new modifications:

mytrap:        

If Err.Number = 11 Then

MsgBox ("The description of the error is " & Err.Description)

Else       

MsgBox ("Something else is going wrong")    

End If    

Resume enterDenominator

Page 63: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST63

Various useful functions

• Rajouter une partie avec les fonctions classiques des string, date, math + msgbox + inputbox + …

Page 64: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST64

Any Question?

Page 65: Visual Basic for Application - Microsoft Access 2003 Introduction

Copyright © 2007 - CIST65

The End