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

Slides:



Advertisements
Similar presentations
Objectives Understand the software development lifecycle Perform calculations Use decision structures Perform data validation Use logical operators Use.
Advertisements

Tutorial 12: Enhancing Excel with Visual Basic for Applications
The Web Warrior Guide to Web Design Technologies
1 Chapter 12 Working With Access 2000 on the Internet.
Exploring Microsoft Access Chapter 8 Creating More Powerful Applications: Introduction to VBA By Robert T. Grauer Maryann Barber.
VBA Modules, Functions, Variables, and Constants
Automating Tasks With Macros
Creating Custom Forms. 2 Design and create a custom form You can create a custom form by modifying an existing form or creating a new form. Either way,
Using Visual Basic 6.0 to Create Web-Based Database Applications
String Variables Visual Basic for Applications 4.
Exploring Office Grauer and Barber 1 Creating More Powerful Applications: Introduction to VBA(Wk9)
Using Objects and Properties
Automating Tasks With Macros. 2 Design a switchboard and dialog box for a graphical user interface Database developers interact directly with Access.
1 Chapter 4 The Fundamentals of VBA, Macros, and Command Bars.
Event-Driven Programming and Access Events
SUNY Morrisville-Norwich Campus-Week 12 CITA 130 Advanced Computer Applications II Spring 2005 Prof. Tom Smith.
Using the Visual Basic Editor Visual Basic for Applications 1.
Macros Tutorial Week 20. Objectives By the end of this tutorial you should understand how to: Create macros Assign macros to events Associate macros with.
1 Chapter 1 Tour of Access. 1 Chapter Objectives Start and exit Microsoft Access Open and run an Access application Identify the major elements of the.
Exploring Microsoft Excel 2002 Chapter 8 Chapter 8 Automating Repetitive Tasks: Macros and Visual Basic for Applications By Robert T. Grauer Maryann Barber.
Access Tutorial 10 Automating Tasks with Macros
WORKING WITH MACROS CHAPTER 10 WORKING WITH MACROS.
A First Program Using C#
Visual Basic Chapter 1 Mr. Wangler.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
XP New Perspectives on Microsoft Access 2002 Tutorial 51 Microsoft Access 2002 Tutorial 5 – Enhancing a Table’s Design, and Creating Advanced Queries and.
Advanced Report and Form Techniques – Project 7. 2 Project 7 Overview This project shows how to create queries for reports, add command buttons to forms,
XP New Perspectives on Microsoft Office Access 2003 Tutorial 11 1 Microsoft Office Access 2003 Tutorial 11 – Using and Writing Visual Basic for Applications.
XP Chapter 7 Succeeding in Business with Microsoft Office Access 2003: A Problem-Solving Approach 1 Enhancing User Interaction Through Programming Chapter.
Automating Tasks with Visual Basic. Introduction  When can’t find a readymade macro action that does the job you want, you can use Visual Basic code.
Tutorial 11 Using and Writing Visual Basic for Applications Code
Enhancing User Interaction Through Programming
Using Visual Basic 6.0 to Create Web-Based Database Applications
® Microsoft Access 2010 Tutorial 11 Using and Writing Visual Basic for Applications Code.
Copyright © 2008 Pearson Prentice Hall. All rights reserved. 1 Microsoft Office Excel Copyright © 2008 Pearson Prentice Hall. All rights reserved
Creating your own form from scratch.. To create a custom form, you can modify an existing form or design and create a form from scratch. In either case,
Office 2003 Advanced Concepts and Techniques M i c r o s o f t Access Web Feature Data Access Pages.
Automating Database Processing Chapter 6. Chapter Introduction Design and implement user-friendly menu – Called navigation form Macros – Automate repetitive.
Working with Numeric Variables (Unit 6) Visual Basic for Applications.
Introduction to Visual Basic.NET Chapter 2 Introduction to Controls, Events.
 Application – another name for a program.  Interface – is what appears on the screen when the application is running.  Program Code – is instructions.
Microsoft Office 2007 Access Chapter 6 Using Macros, Switchboards, PivotTables, and PivotCharts.
Program Design and Coding
Microsoft Visual Basic 2012 CHAPTER THREE Program Design and Coding.
Microsoft Visual Basic 2010 CHAPTER THREE Program Design and Coding.
 Agenda 2/20/13 o Review quiz, answer questions o Review database design exercises from 2/13 o Create relationships through “Lookup tables” o Discuss.
Visual Basic.NET BASICS Lesson 5 Exponentiation, Order of Operations, and Error Handling.
Introduction to Programming with RAPTOR
Chapter Two Creating a First Project in Visual Basic.
Exploring Microsoft Access Chapter 8 Creating More Powerful Applications: Introduction to VBA.
Microsoft Access 2010 Chapter 8 Advanced Form Techniques.
® Microsoft Access 2010 Tutorial 10 Automating Tasks with Macros.
1 MIS309 Database Systems Introduction to Microsoft Access.
Introduction to a Database Defining a database Database window in Access The six items in window: Tables, Queries Forms, Reports, Macros, Modules.
XP New Perspectives on Microsoft Office Access 2003 Tutorial 10 1 Microsoft Office Access 2003 Tutorial 10 – Automating Tasks With Macros.
Visual Basic for Application - Microsoft Access 2003 Programming applications using Objects.
INSERT BOOK COVER 1Copyright © 2012 Pearson Education, Inc. Publishing as Prentice Hall. Exploring Getting Started with VBA for Microsoft Office 2010 by.
8 Chapter Eight Server-side Scripts. 8 Chapter Objectives Create dynamic Web pages that retrieve and display database data using Active Server Pages Process.
Copyright (c) 2003 by Prentice Hall Provided By: Qasim Al-ajmi Chapter 2 Introduction to Visual Basic Programming Visual Basic.NET.
COMPREHENSIVE Access Tutorial 11 Using and Writing Visual Basic for Applications Code.
XP New Perspectives on Microsoft Office Access 2003, Second Edition- Tutorial 6 1 Microsoft Office Access 2003 Tutorial 6 – Creating Custom Forms.
Visual Basic.NET Windows Programming
Access Project 8 Using Visual Basic for Applications (VBA) and Creating Multi-Page Forms.
Microsoft Access Illustrated
Objectives Learn about Function procedures (functions), Sub procedures (subroutines), and modules Review and modify an existing subroutine in an event.
Chapter 7 Advanced Form Techniques
Exploring Microsoft Excel
Microsoft Visual Basic 2005 BASICS
Tutorial 11 Using and Writing Visual Basic for Applications Code
Presentation transcript:

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.

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.

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

5 Introduction (AC ) 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)

6 Introduction (AC ) 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

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.

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.

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  CurrentDue  Underscore  Current_Due *We will use this method

10 VBA Definitions (AC 462 – 466) Naming Conventions for Items on Forms ItemBegins WithExample Command Button cmdcmdPromo Text Box txttxtPromoAmt Labels lbllblPromoAmt

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.95 PromoAmount = 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.

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” Then PromoFactor = 0.95 End If

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” Then PromoFactor = 0.95 Else PromoFactor = 1 End If

14 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

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 Type If Client_Type = “EDU” Then PromoFactor = 0.95 ‘ Promo factor for Educational clients End If

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.

17 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 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

18 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.

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.

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.

21 Using Visual Basic for Applications (VBA) Now, let’s get started. Open Access and your AJC database.

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

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]) 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

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.

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.

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_AfterUpdate Current_Due_AfterUpdate

27 Creating a Form 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.

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 ApplyFilterSets a filter CloseCloses object FindRecordLocates a record GoToRecordMoves to record MaximizeMaximizes window OpenFormOpens a form OpenQueryOpens a query OpenReportOpens a report PrintoutPrints object RunCommandRuns a command ShowAllRecordsRemoves filter

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, acReadOnly RunPromoAmountQuery_Exit: Exit Function RunPromoAmountQuery_Err: MsgBox Error$ Resume RunPromoAmountQuery_Exit End Function  The key statement is the DoCmd statement which uses the OpenQuery method to run a query.  The remaining statements are for error handling:

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, acReadOnly DoCmd  Use the OpenQuery  method Arguments 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.

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.

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.

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 form  To indicate the Web page, include a statement similar to: Form_Load procedure: me!WebBrowser1.navigate followed 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.

Any Questions? Using Visual Basic for Applications (VBA) – Project 8