using visual basic for applications (vba) – project 8

34
Using Visual Basic for Applications (VBA) – Project 8

Upload: toyah

Post on 20-Jan-2016

62 views

Category:

Documents


2 download

DESCRIPTION

Using Visual Basic for Applications (VBA) – Project 8. Project 8 Overview. This project shows us how to add command buttons and controls to a form without using Control Wizards and how to create Visual Basic for Applications (VBA) code to add functionality to the buttons and controls.. - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: Using Visual Basic for Applications (VBA) – Project 8

Using Visual Basic for Applications (VBA) – Project 8

Page 2: Using Visual Basic for Applications (VBA) – Project 8

2

Project 8 Overview

This project shows us how to add command buttons and controls to a form without using Control Wizards and how to create Visual Basic for Applications (VBA) code to add functionality to the buttons and controls..

We will learn … To create both functions and Sub procedures. We will

use the functions in the form and in a query. How to group procedures in a module and use these to

accomplish a variety of tasks. How to create forms from scratch using Design view. How to create a multi-page form by adding a tab control.

On the three pages of the tab control, we will add a subform, charts, and a Web Browser control.

Page 3: Using Visual Basic for Applications (VBA) – Project 8

3

Project 8 Perspective (AC 457)

AJC is considering running a promotion and would like changes made accordingly.

Users receive a discount on the amount currently due to AJC for training they have received.

The discount is determined by a promotional factor that is dependent on client type.

EDU = 0.95, SER = 0.97, MAN = 0.98 The Client Update Form should be modified to

include promotional amount and promotion factor. Users must be able to hide this information.

Page 4: Using Visual Basic for Applications (VBA) – Project 8

4

Project 8 Perspective (AC 457)

Administration would also like a button on the form that, when clicked, runs a query that calculates promotional amounts.

In addition, they would like a form that lists the number and name of trainers. It should contain a subform listing client course offerings It should contain 2 charts with hours spent It should contain a Web browser with AJC’s home page

Page 5: Using Visual Basic for Applications (VBA) – Project 8

5

Introduction (AC 459 - 461) Using VBA and Creating Multi-Page Forms

Figure 8-1 (a,b)

Notice the Client Update Form has 2 new buttons

Hide Promotion (8-1a) Hides promotion amount, promotion factor, and Run Promotion

Query button Caption changes to Show Promotion when clicked

Run Promotion Query (8-1a) Displays the promotion query Figure 8-1 (b)

Page 6: Using Visual Basic for Applications (VBA) – Project 8

6

Introduction (AC 459 - 461) Using VBA and Creating Multi-Page Forms

Figure 8-2 (a,b,c)

The Trainer Course Offerings form lists the Trainer Number, First Name, and Last Name fields from Trainer table.

A multi-page form – more than one page of informationContains a tab control that allows access to three different pages.

Datasheet tab (8-2a)– contains a subform with course offerings Charts tab (8-2b)– contains 2 bar charts representing various courses Web tab (8-2c) – contains a Web browser with home page for AJC

Page 7: Using Visual Basic for Applications (VBA) – Project 8

7

VBA Definitions (AC 462 – 466)

Visual Basic for Applications (VBA) is a programming language that can be used with MS Access. is a collection of statements or commands that will cause

actions to take place when the program executes.

An Access database is composed of objects that have properties and are in turn composed of other objects.For example, Tables have properties, and contain fields, that have

properties. Forms have properties, and contain controls, that have

properties.

Page 8: Using Visual Basic for Applications (VBA) – Project 8

8

VBA Definitions (AC 462 – 466)

Event-driven Programming

VBA deals with event properties – actions recognized by objects.

For example, an event, for a command button, could be a “click”.

The corresponding event property is On Click.

You can associate VBA code with the On Click event property, which executes anytime the button is clicked.

Page 9: Using Visual Basic for Applications (VBA) – Project 8

9

VBA Definitions (AC 462 – 466)

Names in VBA …

can be up to 255 characters long must begin with a letter can include letters, numbers, and underscores (_) cannot contain spaces … for example, Current Due

Capitalize CurrentDueUnderscore Current_Due *We will use this method

Page 10: Using Visual Basic for Applications (VBA) – Project 8

10

VBA Definitions (AC 462 – 466)

Naming Conventions for Items on Forms

Item Begins With Example

Command Button cmd cmdPromo

Text Box txt txtPromoAmt

Labels lbl lblPromoAmt

Page 11: Using Visual Basic for Applications (VBA) – Project 8

11

VBA Definitions (AC 462 – 466)

Statements in VBA use variables …

Variables – named locations in computer memory Assignment Statement – used to assign a value to

a variable and to change the value in a variable.For example:

PromoFactor = 0.95PromoAmount = PromoFactor * Current_Due

Value 0.95 is assigned to PromoFactor and this value is multiplied by the Current_Due amount. Result is assigned to variable called PromoAmount.

Page 12: Using Visual Basic for Applications (VBA) – Project 8

12

VBA Definitions (AC 462 – 466)

Statements in VBA

IF Statement – performs a test and then takes action Action depends on results of the test

For example:

If Client_Type = “EDU” ThenPromoFactor = 0.95

End If

Page 13: Using Visual Basic for Applications (VBA) – Project 8

13

VBA Definitions (AC 462 – 466)

Statements in VBA

If Then Else Statement – takes action if true or does something else if false

For example:

If Client_Type = “EDU” ThenPromoFactor = 0.95

ElsePromoFactor = 1

End If

Page 14: Using Visual Basic for Applications (VBA) – Project 8

14

VBA Definitions (AC 462 – 466)

Statements in VBA

ElseIf Statement – performs multiple tests and takes appropriate action

For example:

If Client_Type = “EDU” ThenPromoFactor = 0.95

ElseIf Client_Type = “SER” ThenPromoFactor = 0.97

ElseIf Client_Type = “MAN” ThenPromoFactor = 0.98

ElseIfPromoFactor = 1

End If

Page 15: Using Visual Basic for Applications (VBA) – Project 8

15

VBA Definitions (AC 462 – 466)

Comments in VBA

Comments can (and should) be included in VBA code to describe the purpose of the code.

Place an apostrophe (‘) before the comment to indicate the text is a comment and not a VBA statement.

Comments can appear on the same line with code.For example:

‘ Determine PromoFactor based on Client TypeIf Client_Type = “EDU” Then

PromoFactor = 0.95 ‘ Promo factor for Educational clientsEnd If

Page 16: Using Visual Basic for Applications (VBA) – Project 8

16

VBA Definitions (AC 462 – 466)

Procedures in VBA

Procedure – a group of statements that accomplishes some specific task.

Two types of procedures:

1. Function – calculates/returns a value and can be used in an expression.

2. Subroutine – does not return a value and cannot be used in expressions.

Page 17: Using Visual Basic for Applications (VBA) – Project 8

17

VBA Definitions (AC 462 – 466)

Procedures in VBA Function example:

Function PromoFactor(Client_Type)‘ Determine PromoFactor based on Client TypeIf Client_Type = “EDU” Then

PromoFactor = 0.95 ‘ Promo factor for Ed clientsElse

PromoFactor = 1 ‘ Promo factor for othersEnd If

End Function

Name of function is PromoFactor Purpose of function is to calculate a value for PromoFactor Variable in parentheses (Client_Type) is called a parameter –

passes data to the function for calculating the function value. Item that furnishes parameter is called an argument.

In PromoFactor(“EDU”) “EDU” is the argument

Page 18: Using Visual Basic for Applications (VBA) – Project 8

18

VBA Definitions (AC 462 – 466)

Procedures in VBA

Subroutine example:

Public Sub ShowPromotion()txtPromoAmount.Visible = TruetxtPromoFactor.Visible = TruecmdPromoQuery.Visible = True

End Sub

Name of subroutine is ShowPromotion Purpose of subroutine is to make visible the controls containing

the promotional amount and promotional factor, as well as the button to run the promotion query.

By placing these statements in a procedure, they can be used from a variety of places within the VBA code.

To call the subroutine, include the name of the procedure at the point you want the commands executed.

Page 19: Using Visual Basic for Applications (VBA) – Project 8

19

VBA Definitions (AC 462 – 466)

Modules in VBA Procedures are grouped together in VBA in a module

There are 2 types of modules:Standard Module – procedures available from anywhere in a database.Class Module – procedures for a particular form or report.

When creating a procedure for an object on a form/report, Access automatically places procedure in class module for that form/report.

When creating additional procedures, you can place them in either a standard module or a class module.If the only way the procedure will be used is in connection with a form or

report, place on form’s or report’s class module.If used widely, place in standard module. For example, if a function is

used by a control on a report and in a query, place in standard module.

Page 20: Using Visual Basic for Applications (VBA) – Project 8

20

VBA Definitions (AC 462 – 466)

Compilation The process of translating programs from one language into a

language the computer can understand and run.

Compiling Translating the program

Compiler The software that performs the translation

When a procedure is run, compiler will first compile the procedure. If successful, the compiled version will run. If failure, errors will be reported, programmer fixes errors and resubmits.

In Access, after creating a procedure, select Debug on menu bar in VB and then select Compile. If failure, fix errors and resubmit. If successful, procedure can be run without a compilation step.

Page 21: Using Visual Basic for Applications (VBA) – Project 8

21

Using Visual Basic for Applications (VBA)

Now, let’s get started.

Open Access and your AJC database.

Page 22: Using Visual Basic for Applications (VBA) – Project 8

22

Testing the Functions (AC 471)

Visual Basic provides an easy way to test functions and procedures.

Use the Immediate Window.Type a question mark, followed by the procedure name

along with values for any arguments.

For example:

?PromoFactor(“EDU”) Tests the function PromoFactor with the “EDU” client

Page 23: Using Visual Basic for Applications (VBA) – Project 8

23

Using the Functions in a Query (AC 473)

Functions stored in a standard module can be used anywhere in the database. To use … type the name of the function place the appropriate argument(s) in parentheses.

If arguments are field names, enclose field names in brackets. For example:

PromoFactor([Client Type])orPromoAmount([Client Type],[Current Due])

To format the expression as currency, you must return a numeric value that can be reformatted. For example:

PromoAmount([Client Type],[Current Due]) * 1.00

Now, let’s get back to Access … We will add the functions to a query We will then add controls to our forms

Page 24: Using Visual Basic for Applications (VBA) – Project 8

24

Associating Code with an Event (AC 482)

Now that we have created the controls on our Client Update form, we need to associate code with an event trigger.

cmdPromo_Click Event

If the cmdPromo control = Show Promotion The caption for cmdPromo changes to “Hide Promotion” The ShowPromotion procedure will run.

displays the promotion amount, promotion factor, and the button to run the Promotion Amount query

Else The caption for cmdPromo changes to “Show Promotion” The HidePromotion procedure will run.

hides the promotion amount, promotion factor, and the button to run the Promotion Amount query

Let’s go back to Access and build the cmdPromo_Click code.

Page 25: Using Visual Basic for Applications (VBA) – Project 8

25

Creating Code to Update the Controls (AC 488)

Now that the event-drive code has been created, we need to update our controls.

UpdatePromoData()

txtPromoAmount.Value = PromoAmount([Client Type], [Current Due])

Uses PromoAmount function to calculate the appropriate amount for the given client type and current due amount.

txtPromoFactor.Value =

PromoFactor([Client Type])

Uses the PromoFactor function to calculate the appropriate factor for the given client type.

Page 26: Using Visual Basic for Applications (VBA) – Project 8

26

Creating Code to Update the Controls (AC 488)

Once created, the procedure can be called from others. Form_Current

Guarantees promotional data will be updated whenever you move from one client to another

Current_Due_AfterUpdate Guarantees that the values would be updated imediately after a user

changed the current due amount.

AfterUpdate (for Client Type combo box) Guarantees that the values would be updated immediately after a user

changes the Client Type.

Let’s go back to Access, create UpdatePromoData, and include it in: Form_Current

Combo32_AfterUpdateCurrent_Due_AfterUpdate

Page 27: Using Visual Basic for Applications (VBA) – Project 8

27

Creating aForm Load Event Procedure (AC 491)

There may be times when you want a special action to be taken when a form first loads into memory.

This action should be included in a Form Load event procedure a procedure executed upon Form Load

For the Client Update Form: Hide the following upon load:

Promotion amountPromotion factorRun Promotion Query button

Let’s go back and add the Form Load procedure.

Page 28: Using Visual Basic for Applications (VBA) – Project 8

28

Creating a Function to Run a Query (AC 492)

We learned how to carry out actions with macros.

We can now carry out actions within VBA code

1. Type DoCmd DoCmd is an object

2. Type a period (.)

3. Type the action Action is a method

ApplyFilter Sets a filter

Close Closes object

FindRecord Locates a record

GoToRecord Moves to record

Maximize Maximizes window

OpenForm Opens a form

OpenQuery Opens a query

OpenReport Opens a report

Printout Prints object

RunCommand Runs a command

ShowAllRecords Removes filter

Page 29: Using Visual Basic for Applications (VBA) – Project 8

29

Creating a Function to Run a Query (AC 492)

We will create the following function:

Function RunPromoAmountQuery()On Error GoTo RunPromoAmountQuery_Err DoCmd.OpenQuery "Promo Amount Query", acNormal, acReadOnlyRunPromoAmountQuery_Exit: Exit FunctionRunPromoAmountQuery_Err: MsgBox Error$ Resume RunPromoAmountQuery_ExitEnd Function

The key statement is the DoCmd statement which uses the OpenQuery method to run a query.

The remaining statements are for error handling:

Page 30: Using Visual Basic for Applications (VBA) – Project 8

30

Creating a Function to Run a Query (AC 492)

On Error GoTo RunPromoAmountQuery_Err

On Error - If an error occurs while function is running

GoTo - Access should proceed to the indicated line of code

DoCmd.OpenQuery "Promo Amount Query", acNormal, acReadOnlyDoCmd Use the OpenQuery methodArguments are: Name of the query “Promo Amount Query” View in which results are to appear (acNormal Datasheet view) ReadOnly indicates users cannot change data when running this query

RunPromoAmountQuery_Exit:This is a label that is used by the Resume statement below

Exit Function

Terminates the function. Function is complete.

Page 31: Using Visual Basic for Applications (VBA) – Project 8

31

Creating a Function to Run a Query (AC 492)

RunPromoAmountQuery_Err:

If an error occurs while procedure is running, Access moves to this line

MsgBox Error$

MsgBox – displays a message

Error$ - a variable that contains description of error that occurred

MsgBox displays the contents of Error$ and forces user to click OK.

Resume RunPromoAmountQuery_Exit

Resume - run the procedure at the line with the specified label.In our case, code returns to RunPromoAmountQuery_Exit:which contains Exit Function. This way the function ends and the user is returned to the form.

Let’s go back and create a function to run a query.

Page 32: Using Visual Basic for Applications (VBA) – Project 8

32

Creating a Form Using Design View (AC 505)

Up to now, we have used the Form Wizard to create forms.

We will now create a form from a blank form upon which we will place controls.

For this project, we need to place a subform, two charts, and a Web browser on the form.

Let’s go back to Access and build our form.

Page 33: Using Visual Basic for Applications (VBA) – Project 8

33

Adding an ActiveX Control (AC 515)

When we created forms, we worked with several of the special built-in Access controls text box, label, command button, etc.

Many additional controls, ActiveX controls, are also available. (Both from Microsoft and elsewhere.)

We will add the Web Browser ActiveXcontrol:Add to the form by selecting from a list of Active X controls Indicate Web page should be displayed during load of formTo indicate the Web page, include a statement similar to:

Form_Load procedure: me!WebBrowser1.navigatefollowed by the URL for the Web page to be displayed.(me! means that what follows is part of the current object)

Let’s go back to Access and add the ActiveX.

Page 34: Using Visual Basic for Applications (VBA) – Project 8

Any Questions?

Using Visual Basic for Applications (VBA) – Project 8