340 likes | 491 Views
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..
E N D
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.
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.
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
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)
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 information • Contains 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
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.
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.
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 CurrentDue • Underscore Current_Due *We will use this method
VBA Definitions (AC 462 – 466) Naming Conventions for Items on Forms ItemBegins WithExample Command Button cmd cmdPromo Text Box txt txtPromoAmt Labels lbl lblPromoAmt
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_DueValue 0.95 is assigned to PromoFactor and this value is multiplied by the Current_Due amount. Result is assigned to variable called PromoAmount.
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” Then PromoFactor = 0.95 End If
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” Then PromoFactor = 0.95 Else PromoFactor = 1 End If
VBA Definitions (AC 462 – 466) Statements in VBA ElseIf Statement – performs multiple tests and takes appropriate action • For example: If Client_Type = “EDU” Then PromoFactor = 0.95 ElseIf Client_Type = “SER” Then PromoFactor = 0.97 ElseIf Client_Type = “MAN” Then PromoFactor = 0.98 ElseIf PromoFactor = 1 End If
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
VBA Definitions (AC 462 – 466) Procedures in VBA • Procedure – a group of statements that accomplishes some specific task. • Two types of procedures: • Function – calculates/returns a value and can be used in an expression. • Subroutine – does not return a value and cannot be used in expressions.
VBA Definitions (AC 462 – 466) Procedures in VBA • Function example: Function PromoFactor(Client_Type)‘ Determine PromoFactor based on Client Type If Client_Type = “EDU” Then PromoFactor = 0.95 ‘ Promo factor for Ed clients Else PromoFactor = 1 ‘ Promo factor for others End IfEnd 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
VBA Definitions (AC 462 – 466) • Procedures in VBA • Subroutine example: Public Sub ShowPromotion() txtPromoAmount.Visible = True txtPromoFactor.Visible = True cmdPromoQuery.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.
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.
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.
Using Visual Basic for Applications (VBA) Now, let’s get started. Open Access and your AJC database.
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
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]) or PromoAmount([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
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 IfthecmdPromocontrol=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.
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.
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_AfterUpdate Current_Due_AfterUpdate
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 amount Promotion factor Run Promotion Query button Let’s go back and add the Form Load procedure.
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 • Type DoCmd DoCmd is an object • Type a period (.) • Type the action Action is a method
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:
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.
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.
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.
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 form • To 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.
Using Visual Basic for Applications (VBA) – Project 8 Any Questions?