You are on page 1of 48

Information Resources

Access 97
Macros & Switchboards

Topics:
Creating Forms Calculations in Forms Command Button Wizard Switchboards Macros Start Up Parameters Charts

Marshall School of Business University of Southern California

Table of Contents
DEFINITIONS.................................................................................................................................... 4 Switchboard..................................................................................................................................... 4 MACRO .......................................................................................................................................... 4 Module ............................................................................................................................................ 4 Where Macros/Modules Are Stored................................................................................................. 4 ABOUT THE DATABASE................................................................................................................. 5 DATA ENTRY FORM........................................................................................................................ 6 EXAMINING Mainform - Complete............................................................................................ 6 SWITCHBOARDS.............................................................................................................................. 7 Examining A Completed Switchboard ............................................................................................. 7 CREATING A SWITCHBOARD........................................................................................................ 8 The Toolbox Toolbar.................................................................................................................... 8 Create the Button: Dollars to Goal............................................................................................... 9 Create the Button: Total Donations.............................................................................................. 9 Create the Button: Non Donating Patrons .................................................................................. 10 MACROS.......................................................................................................................................... 11 Macro Basics ................................................................................................................................. 11 Exploring an Existing Macro ......................................................................................................... 11 MACRO 1: OPEN THE MAINFORM ............................................................................................. 13 Assign the Macro to the Switchboard Button ................................................................................. 13 Test the Macro............................................................................................................................... 13 Macro 2: Add New Records Macro ................................................................................................... 14 Set the Arguments for GoToRecord............................................................................................... 14 Set the Arguments for GoToControl .............................................................................................. 14 Assign the Macro to the MainForm without the Wizards Help...................................................... 15 UNDERSTANDING EVENTS ......................................................................................................... 15 MACRO 3: ATTENDANCE HISTORY ........................................................................................... 16 Setting Arguments for the Actions ................................................................................................. 16 Create the Combo Box................................................................................................................... 17 Assign the Macro to the Drop Down List....................................................................................... 17 MACRO 4: DONATION HISTORY................................................................................................. 18 Setting Arguments for the Actions ................................................................................................. 18 Create the Combo Box................................................................................................................... 19 Assign the Macro to the Drop Down List....................................................................................... 19 MACRO 5: CONDITION COLUMN................................................................................................ 20 Condition Example 1 ..................................................................................................................... 20 Setting Action Arguments.............................................................................................................. 21 Assign the Macro to the Form........................................................................................................ 21 Condition Example 2 ..................................................................................................................... 22 Setting the Arguments ................................................................................................................... 23 Assign the Macro to the Form........................................................................................................ 23 MACRO 6: USING MESSAGE BOXES........................................................................................... 24 Assign the Macro to the Form........................................................................................................ 25 MACRO 7: OPTION BOXES ........................................................................................................... 26 Examining the Query: Donation Status ......................................................................................... 26 Creating the Option Group............................................................................................................. 26

How Option Groups Work............................................................................................................. 27 Naming the Option Group ............................................................................................................. 27 Creating the Macro ........................................................................................................................ 27 Assigning the Macro to the Labels Form........................................................................................ 28 KEYSTROKE MACROS.................................................................................................................. 29 Naming the Keystroke Macros....................................................................................................... 29 Keystroke Macro Example............................................................................................................. 29 Save the Macro.............................................................................................................................. 30 Testing the Macro Freeze & Unfreeze Columns Macro.................................................................. 30 Testing the Run Query Macro........................................................................................................ 30 MACRO 7: SELF EXECUTING MACROS...................................................................................... 31 Run the Autoexec Macro ............................................................................................................... 31 Bypass the Autoexec Macro........................................................................................................... 31 HIDING FORM CONTROLS ........................................................................................................... 32 SETTING STARTUP PARAMETERS ............................................................................................. 33 Temporarily Bypassing the Startup Limitations ............................................................................. 33 Removing Startup Limitations ....................................................................................................... 33 HIDING DATABASE OBJECTS...................................................................................................... 34 Unhiding Database Objects............................................................................................................ 34 ADVANCED FORM CALCULATIONS .......................................................................................... 35 The DSUM Function ..................................................................................................................... 36 The DLOOKUP Function .............................................................................................................. 37 Dlookup for Number of Visits........................................................................................................ 37 Removing Tab Stops ..................................................................................................................... 38 MODULES: CREATING CUSTOM FUNCTIONS .......................................................................... 39 Function Basics ............................................................................................................................. 39 Function Example 1....................................................................................................................... 39 Testing Functions .......................................................................................................................... 40 Function Example 2: Fahrenheit to Celsius ................................................................................... 40 Function Example 3: IF Statements & Multiple Variables............................................................. 41 Discounts Based Upon Quantity Purchased.................................................................................... 41 Example 4: Nested If Statements................................................................................................... 42 Function Example 5: Select Case ................................................................................................. 43 Determining Letter Grades Based on a Test Score ......................................................................... 43 Function Example 6: Working With Dates.................................................................................... 45 Functions Employed: ..................................................................................................................... 45 Finding the Number of Years......................................................................................................... 46 Getting Months.............................................................................................................................. 47 Combine the Two Tunctions into a Single Function....................................................................... 47

Marshall School of Business

University of Southern California

DEFINITIONS
Switchboard
A Switchboard is a screen with buttons on it that automate database functions. Its purpose is to make Access easier to use for novice users while keeping sensitive areas of the database protected from misuse. The switchboard screen itself is created from an unbound form (a form which is not based on a table) and the buttons on the switchboard activate either macro or Visual Basic code sequences. Calculations and functions can also be placed on a switchboard

MACRO
A macro is a way to automate a task or a series of tasks in your database. A macro is an object just as tables, queries, forms, and reports are objects. Action: every task you want an access macro to perform is called an Action. There are 42 actions that you can select and perform in your macros. Events: Most macros are triggered by events such as opening a form, clicking in a field, pressing enter in a certain place, etc. You can make macros do such things as: automatically opening a form, updating a field, or placing the hourglass on the screen.

Module
A module is a unit of Visual Basic programming code that you can use to add additional functionality to Access. By using Visual Basic, Access can be used to perform operations its designers did not build into it. When you use the command button wizard, it creates visual basic code, not macro code. Custom functions can also be created using modules. Visual Basic is a fairly easy programming language but is also extensive and therefore beyond the scope of a simple two hour workshop.

Where Macros/Modules Are Stored


Stand Alone Macros - These are macros you created manually within the Macros tab. They are called stand alone because they can be made to work alone or assigned to an Access object such as a form, query, etc. Form Created Macros/Modules - When you create a Command Button in a form to automate operations, the macro is stored within the button as visual basic code and will not appear within the Macros or modules tab.

Access_Macros.Doc

February 26, 1999

Page 4 of 48

Marshall School of Business

University of Southern California

ABOUT THE DATABASE


This handout utilizes a database called 24th Street Theatre.mdb. The database can be found in two locations: From HOH300, HOH401, & Bri202, it can be copied from: M:\Prof\Training to your A drive or to C:\temp It can also be downloaded from the web at the following address: http://www.marshall.usc.edu/computing/training/Handouts.htm

The purpose of this database is to track which shows customers have seen, how many tickets were purchased, and how much money they have donated to the theatre. It is made up of 3 tables which are related by their common field of Client_ID.

Customer Info - This table tracks general patron information. Every patron, whether they are a donor, attendee or both, is listed in this database only once. Donor Info - If a patron has made a donation then the donation amount, date, etc. is tracked in this database. If they have made more than one donation, their Client_ID will appear more than once. (Their name, address, etc, is listed in the Customer Info database.) Tickets Purchased - If a patron has purchased a ticket then the name of the show, date, number of tickets, and ticket price will appear in this database. If they have seen more than one show, then their Client_ID will appear more than once. (Their name, address, etc, is listed in the Customer Info database.)

For more information on relating tables, see the handout: Forms - Beginning which can be found at the following web address: http://www.marshall.usc.edu/computing/training/Handouts.htm

Access_Macros.Doc

February 26, 1999

Page 5 of 48

Marshall School of Business

University of Southern California

DATA ENTRY FORM


If you click on the Forms tab, you will notice that there are three forms:

MainForm - Complete - This form is based off the table Customer info and contains the two subforms Donor Info Subform and Tickets Purchased Subform. It also contains three calculated fields and two command controls. It is there as an example of what we will create using the MainForm. Donor Info Subform - This form accesses fields from the table Donor Info. It is never opened directly but is pulled into the Main Form when the Main Form is opened. Tickets Purchased Subform - This form accesses fields from the table Tickets Purchased. It is never opened directly but is pulled into the Main Form when the Main Form is opened. In addition, it contains a calculated field called Order Total which was created by multiplying the number of tickets purchased by the ticket price. MainForm - This form is based off the table Customer info and contains the two subforms Donor Info Subform and Tickets Purchased Subform. When we are finished, it will have everything MainForm - Complete has. For more information on creating subforms, see the handout: Forms - Beginning which can be found at the following web address: http://www.marshall.usc.edu/computing/training/Handouts.htm Note that to create a mainform containing two subforms, you can not use the form wizards but must use the Subform/SubReport button found on the Toolbox toolbar while in form Design View.

EXAMINING Mainform - Complete


1. 2. Click on the Forms tab and open the form MainForm - Complete. Press ENTER or TAB to move through the fields. To go from the Tickets Purchased subform to the Donations subform, press: Control + Tab. To go to a specific record, click the down arrow at Select a Name and select the record you wish to view. Note that Order Total in the Tickets Purchased subform is a calculated field and that you will never type there. Note the three calculations at the bottom of the screen. These will change automatically when you move to a different record. To add a record, click the button Add a Record. Close the MainForm - Complete after examining it.

Access_Macros.Doc

February 26, 1999

Page 6 of 48

Marshall School of Business

University of Southern California

SWITCHBOARDS
A Switchboard is a screen with buttons on it that automate database functions. The purpose of a switchboard is to make Access easier to use for novice users and while keeping sensitive areas of the database protected from misuse. The buttons on the switchboard activate either macro or Visual Basic code sequences. Switchboards are created from Unbound forms. (A form which is not based upon a table.) The buttons placed on the switchboard activate macros, events, or modules when pressed. This handout will deal primarily with events and macros.

Examining A Completed Switchboard


Below is a completed switchboard which we will recreate. It contains five command buttons which were created using wizards and three controls which employ macros. To view the form: 1. 2. Click on the Forms tab. Double click the form Switchboard - Complete to open it.

Open Mainform is a macro which opens Mainform - Complete and Attendance History & Donation History are macros which search for data based on the combo box.

These 3 buttons were created using the Command Button Wizards and run saved queries.

These 2 buttons were created using the Command Button Wizards and open saved forms which contain charts.

Access_Macros.Doc

February 26, 1999

Page 7 of 48

Marshall School of Business

University of Southern California

CREATING A SWITCHBOARD
As mentioned above, a switchboard is created from an unbound form. The steps in this section show how to create the unbound form. 1. Click on the Forms tab. 2. Click on the New button. 3. Select Design View and click on OK. 4. Resize the form to fill most of the screen 5. Click on the Save icon and name the switchboard Switchboard.

The Toolbox Toolbar


When working with forms, the Toolbox contains many of the buttons you will need. If it is not visible while in form design view, then click the Toolbox icon on the menu: Note that if the Control Wizards icon on the Toolbox toolbar is not pressed, the command wizards will not help you.
Select Objects: Allows the selection of objects. Label: Used for placing text on any part of your form. Option Group: Used in conjunction with option buttons, this allows you to select between a group of choices. Option Button: Use either with a Yes/No field or in an option group. Control Wizards: When turned on, wizards will help with using other tool box controls. Text Box: Used to create calculations. Toggle Button: Toggles between two choices. Check Box: Used with Yes/No fields. List Box: Allows selection from a list of choices. Combo Box: Allows selection from a drop down list of choices. Command Button: Use to activate macros & module commands. Unbound Object Frame: Use to place OLE objects (sounds, pictures, etc.) from an outside source in your form. Page Break: Forces a page break. Line: Use to place lines on your form. SubForm/SubReport: Use to create a form within a form. Rectangle: Places a rectangle in the form. More Controls: Opens a list of more advanced controls.

Image: Use to place pictures from a source outside the database on the form. Bound Object Frame: Used to display OLE objects (such as pictures) that are stored in the table in the form. Tab Control: Allows you to place controls behind one another using tabs.

Access_Macros.Doc

February 26, 1999

Page 8 of 48

Information Resources

University of Southern California

Create the Button: Dollars to Goal


We will use the command button wizard to create this button. When pressed, the button will open a query called $ to Goal which subtracts the total current donations from the goal of $50,000. The query was based on the table Donor Info and is designed as shown here. Note that it employs the SUM function rather than using the Totals row. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. The Switchboard form is still open and you are in Design View. From the Toolbox, click on the Command Button icon: Click in the upper right corner of the form. From the Command Button Wizard, select the Miscellaneous category. In the Action window, select Run Query and click NEXT. Select the query $ to Goal and click NEXT. Select the Text option and type: Dollars to Goal. Click on NEXT. Name the button: Dollars to Goal and click FINISH. Go into Form View and click the command button. It should run the query. Close the query window and then click the Save icon to save the form.

Create the Button: Total Donations


We will use the command button wizard to create this button. When pressed, the button will open a query called Total Current Donations. The query was based on the table Donor Info and is designed as shown here. It will total all donations made using the Totals row.

1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11.

The form Switchboard is still open and you are in Design View. From the Toolbox, click on the Command Button icon: Click below the last button created. From the Command Button Wizard, select the Miscellaneous category. In the Action window, select Run Query and click NEXT. Select the query Total Current Donations and click NEXT. Select the Text options and type: Total Donations. Click on NEXT. Name the button: Total Donations and click FINISH. Go into Form View and click the command button. It should run the query. Close the query window and then click the Save icon to save the form.

Access_Macors.Doc

September 25, 1998

Page 9 of 48

Information Resources

University of Southern California

Create the Button: Non Donating Patrons


We will use the command button wizard to create this button. When pressed, the button will open a query called Not Donated. The query (shown below) was created by creating an outer joint between two linked tables: Customer Info and Donor Info. All clients will be in Customer Info but Donor Info. will only have a matching client ID if the client has made a donation. The query then lists only those patrons who do not have a match.

For more information on how this query was created and the principles behind it, download the handouts: Queries-Advanced on the following web site: http://www.marshall.usc.edu/computing/training/Handouts.htm
1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. The Switchboard form is still open and you are in Design View. From the Toolbox, click on the Command Button icon: Click below the last button created. From the Command Button Wizard, select the Miscellaneous category. In the Action window, select Run Query and click NEXT. Select the query Not Donated and click NEXT. Select the Text options and type: Non Donating Patrons. Click on NEXT. Name the button: Non Donating Patrons and click FINISH. Go into Form View and click the command button. It should run the query. Close the query window and then click the Save icon to save the form.

Viewing Visual Basic Code


To view the code for this button: 1. Go in form Design View then right mouse click the button and then select Properties. 2. Click on the Event tab. 3. Click the field containing [Event Procedure] then click the three periods to the right. 4. When finished viewing the code, close the Module window.

Access_Macors.Doc

September 25, 1998

Page 10 of 48

Information Resources

University of Southern California

MACROS
Three of the buttons on our switchboard employ macros: Open Mainform, Attendance History, and Donations History. Some basics on macros are listed below.

Macro Basics
You must save your macros before you can run them. If you name a macro Autoexec, access will run it when you open the database. A single macro can perform one or many actions. A macro object can contain multiple macros. This means that when you click on the macros tab in the database window, each macro listed can contain multiple sub macros. Sub macros are created by placing a name in the Name column. If there is no name in the name column then Access will read all of the code in the macro. Macro code reads from top to bottom in the macro pane window until it finds no more code or it sees another macro name in the name column. A blank row will not stop a macro from reading. Comments are optional and are ignored by Access. Every task you want Access to perform is called an Action and there are 47 different actions you can have a macro perform.

Exploring an Existing Macro


1. 2. Click on the Macros tab. Select the macro: Macro - Complete and click the Design button.

The macro window is divided up into 4 parts: The menus. The Tool Bars The Action Pane (top part of the window) where the specific action is selected. The Argument Pane (bottom portion of the window) where parameters are set. Macro - Complete contains several macros: Open Mainform - Complete: This macro opens the form Mainform - Complete.

Show History: This macro runs the drop down list on the switchboard and runs a query called Patron Show History. It then filters the query to only show the records for the name chosen from the drop down list. Donor History: This macro runs the drop down list on the switchboard and runs a query called Patron Donor History. It then filters the query to only show the records for the name chosen from the drop down list. Add New Records: This macro takes the cursor to a new record in the Mainform - Complete form and then positions the cursor in the First_Name field.

Access_Macors.Doc

September 25, 1998

Page 11 of 48

Information Resources

University of Southern California

Macro Names: Click this button to display/hide the Macro Names column in the macro pane. Condition: Click this button to display/hide the Conditions column in the macro pane.

Macro Name: For a macro object to contain several macros, you must name the individual macros in the Macro Name column. Access reads code from top to bottom and will stop reading when it reaches another macro name. If you did not use macro names, access would read all of the code in the macro object.

Condition: If you place a condition in this column, Access will only execute the code next to the condition if the condition is true. Note that true or false, the line below will be read. An example of a condition might be to check to see if an order date is before the required date.

Action: This is the actual macro code that is executed by access. You can select from 49 different actions. Once an action is selected, any specifics are set below in the arguments pane.

Comments: Comments are optional and serve as reminders or explanations to yourself for what each line of code is for. Access ignores everything in the Comments section.

Action Arguments: This area allows the user to specify arguments for the currently selected action. This pane will change depending on the action selected and always reflects the currently selected action.

Access_Macors.Doc

September 25, 1998

Page 12 of 48

Information Resources

University of Southern California

MACRO 1: OPEN THE MAINFORM


This macro will be assigned to the Open Mainform button on the switchboard. When pressed, the macro will open the form called Mainform. 1. 2. 3. 4. 5. 6. Close the Macros - Complete module if it is still open. Click on the Macros tab if you are not currently there. Click on the New button to start a new macro. Click the Macro Names icon to display the macro name column. Name the macro: Open Main form. In the Action column, select OpenForm.

Setting Arguments for the Action Make sure the cursor is still on the Open Mainform line in the action pane before going to the Arguments section. 7. Set the Form Name to MainForm. 8 Set the View to Form. 9. Leave Filter Name and Where Condition blank. 10. Set the Data Mode to Edit. 11. Set the Window Mode to Normal. 12. Save the macro as My Macros and close it.

Assign the Macro to the Switchboard Button


1. Click on the Forms tab. 2. Select the form Switchboard and then click the DESIGN button. 3. From the Toolbox, click on the Command Button and then click the form. (The wizard should start.) 4. Select the Miscellaneous category. 5. Select the Run Macro action. 6. Click on NEXT. 7. Select the macro created above: My Macros.Open Main Form and click NEXT. 8. Select the Text option and label the button Open Mainform. 9. Click on NEXT. 10. Name the button Open Mainfom and click FINISH.

Test the Macro


1. Save the form and go to Form View. 2. Click on the command button: Open Mainform. (The Mainform should have opened.) 3. Close Mainform.

Access_Macors.Doc

September 25, 1998

Page 13 of 48

Information Resources

University of Southern California

Macro 2: Add New Records Macro


This macro will be assigned to Main Form and will tell Access to begin a new record and position the cursor in the cursor in the First_Name field. 1. 2. 3. 4. 5. Click on the Macros tab. Click the macro My Macros and then click the DESIGN button. Skipping a row, place the cursor below the previous macro. In the Macro Names column, type: Add New Records In the Action column, click the down arrow and select: GotoRecord 6. Click in the row below Go to Record and click the down arrow to select: GoToControl

Now that we have told Access that we wish to go to a specific record and field (control), we must tell it which record and which field.

Set the Arguments for GoToRecord


Here we will tell access which record to go to. (a new record) 1. In the top pane, click anywhere in the words: GotoRecord 2. In the Arguments Pane, make the following settings: Object Type: Form This tells Access what type of object it will be opening. Object Name: Mainform This tell Access the name of the form it will be opening. Record: New This tells access to begin a new record in the form. Offset is not used but if we had selected in Record the option Goto then in Offset we could have specified which record to go to.

Set the Arguments for GoToControl


Here we will tell Access to position the cursor in the First_name field. 1. In the top pane, click anywhere in the words: GoToControl 2. In the Arguments Pane, make the following settings: Control Name: First_Name

3. Save the Macro as My Macros and then close it.

Access_Macors.Doc

September 25, 1998

Page 14 of 48

Information Resources

University of Southern California

Assign the Macro to the MainForm without the Wizards Help


1. 2. 3. 2. 3. 4. 5. 6. 7. Click on the Forms tab and open Mainform in Design View. From the Toolbox toolbar, shut off the wizards by clicking the Control Wizards button. From the Toolbox toolbar, click on the Command button and then click the form. Right mouse click the command button we just created and select Properties. Click on the Event tab. Click in the box on the line: On Click. Click the down arrow and select the macros called: My Macros.Add New Records Save the form and go to form view. Click on the Input Data button. Access should have positioned the cursor in the First_Name field of a new record. 8. Close Mainform

UNDERSTANDING EVENTS
Macros are usually triggered by an Event such as a mouse click or a keystroke but macros can be triggered by other actions as well such as opening a form or when an error message occurs. To view a list of possible events used in a form: 1. 2. 3. Open any form in design view. Click on one of the Text controls and open the properties window. Click on the Event tab.

Note that to get more information than whats shown below, you can click on an event line and press F1 on the keyboard. Focus: A control is said to have the focus when it can receive input through the mouse or keyboard. Before Update: After Update: On Change: Not on List: On Enter: On Exit: On Got Focus: On Lost Focus: The event occurs before the data in a control (field) is updated (saved). The event occurs after the data in a control (field) is updated (saved). The event occurs when the contents of a text box changes. The event occurs when test is entered into a combo box that isnt on the list. The event occurs before the control actually receives the focus. The event occurs just before the control loses the focus to another control on the same form. The event occurs when the control gets the focus. The event occurs when the controls loses the focus.

The remaining events should be self explanatory.

Access_Macors.Doc

September 25, 1998

Page 15 of 48

Information Resources

University of Southern California

MACRO 3: ATTENDANCE HISTORY


This macro will also be assigned to the Attendance History drop down menu on the switchboard and is made up of three macro actions. When a patrons name is selected from the drop down list, a query called Patron Show History will run and the macro will filtrate all names out except the one chosen from the list. 1. 2. 3. Click on the Macros tab. Click the macro My Macros and then click the DESIGN button. Place the cursor two rows below the previous macro.

4. 5. 6. 7.

Name the macro Show History. Select OpenQuery in the Action column. Below OpenQuery, select ApplyFilter as the next action. Below ApplyFilter, select Save as the last action for this macro.

Setting Arguments for the Actions


1. 2. 3. 4. 5. Click on the OpenQuery action. In the Arguments pane, click in Query Name & select the query: Patron show History. Set the View to Datasheet and the Data Mode to Edit. Above, select the Action ApplyFilter In the Arguments pane, click in Where Condition and type the following:

[client_id]=[Forms]![switchboard].[show history]
In English, this basically means: Show only the client from the query where the client id is equal to the client chosen from the drop down menu (called show history) on the form called switchboard. 6. 7. 8. Above, select the Action Save. In the Arguments pane, set the Object Type to Query and the Object Name to Patron Show History. Save and close the macro.

Access_Macors.Doc

September 25, 1998

Page 16 of 48

Information Resources

University of Southern California

Create the Combo Box


1. 2. 3. 4. 5. 6. 7. 8. 9. Click on the Forms tab and open the form Switchboard in design view. Make sure that the Control Wizards icon on the toolbar is active. From the Toolbox, click the Combobox button and then click the form. Select I want the combo box to lookup the values in a table or query then click NEXT. Select the table Customer Info then click NEXT. Place the fields: Client_ID, First_Name, Last_Name then NEXT. Adjust the column widths if necessary and then click NEXT. Select the option: Remember the value for later use and click NEXT. Label the combo box: Attendance History and click FINISH.

Assign the Macro to the Drop Down List


1. 2. 3. 4. 5. 6. 7. Right mouse click the combo box (on the right side) and select Properties from the list. Click on the Event tab and then on the On Change line. Click the down arrow and select the macro: Macro - Show History Click on the Name line and name the combo box: Show History (It must be named Show History because our macro refers to an object of that name.) Save the form and go into Form View. Test the macro by clicking the down arrow and selecting a name form the list. The query should run and show only the attendance for the person you selected. Close the query.

Access_Macors.Doc

September 25, 1998

Page 17 of 48

Information Resources

University of Southern California

MACRO 4: DONATION HISTORY


This Macro is almost exactly the same as macro number 3 except it shows the selected patrons Donation History rather than their Attendance History. The macro will also be assigned to the Donation History drop down menu on the switchboard and is made up of three macro actions. When a patrons name is selected from the drop down list, a query called Patron Donor History will run and the macro will filtrate all names out except the one chosen from the list. 1. 2. 3. Click on the Macros tab. Click the macro My Macros and then click the DESIGN button. Place the cursor two rows below the previous macro.

4. 5. 6. 7.

Name the macro Donor History. Select OpenQuery in the Action column. Below OpenQuery, select ApplyFilter as the next action. Below ApplyFilter, select Save as the last action for this macro.

Setting Arguments for the Actions


1. 2. 3. Click on the OpenQuery action. In the Arguments pane, click in Query Name & select the query: Patron Donor History. Set the View to Datasheet and the Data Mode to Edit.

4. 5.

Above, select the Action ApplyFilter In the Arguments pane, click in Where Condition and type the following:

[client_id]=[Forms]![switchboard].[Donation history]
In English, this basically means: Show only the client from the query where the client id is equal to the client chosen from the drop down menu (called Donation history) on the form called switchboard. 6. Above, select the Action Save. 7. In the Arguments pane, set the Object Type to Query and the Object Name to Patron Donor History. 8. Save and close the macro. Access_Macors.Doc September 25, 1998 Page 18 of 48

Information Resources

University of Southern California

Create the Combo Box


1. 2. 3. 4. 5. 6. 7. 8. 9. Click on the Forms tab and open the form Switchboard in design view. Verify that the Control Wizards icon on the toolbar is active. From the Toolbox, click the Combobox button and then click the form. Select I want the combo box to lookup the values in a table or query then click NEXT. Select the table Customer Info then click NEXT. Place the fields: Client_ID, First_Name, Last_Name then NEXT. Adjust the column widths if necessary and then click NEXT. Select the option: Remember the value for later use and click NEXT. Label the combo box: Donation History and click FINISH.

Assign the Macro to the Drop Down List


6. 7. 8. 9. 10. 11. 12. Right mouse click the combo box (on the right side) and select Properties from the list. Click on the Event tab and then on the On Change line. Click the down arrow and select the macro: Macro - Donor History Click on the Name line and name the combo box: Donation History (It must be named this because our macro refers to an object named Donation History.) Save the form and go into Form View. Test the macro by clicking the down arrow and selecting a name form the list. The query should run and show only the donations from the person you selected. Close the query.

Access_Macors.Doc

September 25, 1998

Page 19 of 48

Information Resources

University of Southern California

MACRO 5: CONDITION COLUMN


The Condition column allows for the creation of If-Then-Else conditions that control under what circumstances Access will run the macro code in the Action column. When you place a criteria in the condition column (such as [Quantity]>5 for example), the code placed in the action column of the same row as the condition will only be executed if the condition is true. Code placed on the next line down will be executed whether the condition above is true or false. If you only want the code on the next line to be executed if the condition is true, then either: - Place the same condition on the line below. - Or place three dots on the line below which is like saying repeat the condition above.

As with all macros: The macro will keep reading the lines below until: A name is encountered in the Macro Name column. Or the StopMacro action is encountered in the Action column. There are two examples below which demonstrate using the condition column.

Condition Example 1
In this example, if the user purchases more than 6 tickets for a show, they get a 10% discount on the total cost. The SetValue action is used in this macro to place the results of our calculation into the Total field. This is different then simply placing a calculation in a form. Calculations are display only, they do not write to the table, but the SetValue action does place data in the actual table.

1. 2. 3. 4. 5. 6. 7. 8. 9.

Click on the Macros tab. Click the macro My Macros and then click the DESIGN button. Click the Condition icon to make the Condition column visible. Skip a row from the bottom of the last macro and name for your macro: QuantityDiscount Click in the Condition column and type the following equation: [No_of_Tickets]>6 Click in the Action column and select the SetValue action. Click the row below the pervious condition and type the equation: [No_of_Tickets]<=6 On the same row, set the action to SetValue. Select StopMacro for the last action. (This isnt really necessary, we just havent used it yet.)

Access_Macors.Doc

September 25, 1998

Page 20 of 48

Information Resources

University of Southern California

Setting Action Arguments


1. 2. 3. Click on the top SetValue action. Click in the Item section of the Arguments pane and type: [Total] (This tells Access the name of the field whose value is to be set.) Click in the Expression section and type: [No_of_Tickets]*[Ticket_Price]*0.9 (This tells Access to multiply the [No_of_Tickets] by the [Ticket_Price] by .9 but only if the number of tickets purchased is 6 or over) Click on the second SetValue action. Click in the Item section of the Arguments pane and type: [Total] (This tells Access the name of the field whose value is to be set.) Click in the Expression section and type: [No_of_Tickets]*[Ticket_Price] (This tells Access to multiply the [No_of_Tickets] by the [Ticket_Price] but only if the number of tickets purchased is less than 6.) Save and close the macro.

4. 5. 6.

7.

Assign the Macro to the Form


Although Mainform is the form that we open when we wish to enter data, Tickets Purchased Subform is the form that contains the fields that are actually typed in. Therefore, we need to assign our macro to Tickets Purchased Subform. Because the user may decide to enter data into the [Ticket_Price] or [No_of_Tickets] fields in a random order, we will assign the macro triggering event to both fields. 1. 2. 3. 4. 5. 6. 7. 8. 9. Click on the Forms tab and then open Tickets Purchased Subform in Design View. Right mouse click the text box control Ticket_Price and select Properties. In the Properties window, click the Event tab and then click on the On Lost Focus line. Click the down arrow and select the macro: My Macros.QuantityDiscount. Leave the Properties window open and click, click the text box control: No_of_Tickets. On the On Lost Focus line, select the macro: My Macros.QuantityDiscount. Go to Form View. Change the number of tickets purchased or ticket price to test the macro. Save and close the form.

Access_Macors.Doc

September 25, 1998

Page 21 of 48

Information Resources

University of Southern California

Condition Example 2
To a point, this macro very similar to Condition Example 1 except that it gives a 10% discount based on whether or not the patron has made a donation, not on the quantity of tickets purchased. This macro is also more complicated because it must look into a subform that is a different subform then where the calculation is taking place. If you recall, the donation information is kept in the Donor Info Subform and the ticket information is kept in the Tickets Purchased Subform.

1. 2. 3. 4. 5.

Click on the Macros tab. Click the macro My Macros and then click the DESIGN button. If necessary, click the Condition icon to make the Condition column visible. Skip a row from the bottom of the last macro and name for your macro: DonationDiscount Create the macro shown in the figure above. The conditions cover three possibilities: What to do if the Amount Donated is greater than zero. What to do if the Amount Donated is blank. (This uses the ISNULL( ) function which would return a True condition if the field contained a blank.) What to do if the Amount Donated is equal to zero. (A blank is not considered zero.)

[Forms]![mainform]![Donor Info subform]![Amount_Donated]>0


This is the type of object we are accessing. This is the name of the mainform, containing the sumform, containing the field we are basing our condition on. This is the name of the form, containing the field we are basing our condition on. This is the name of the field we are basing our condition on.

In English, this condition might read: If the Amount_Donated field which exists in the form Donor Info Subform which exists in the form called mainform is greater than 0, then execute the action to the left

Access_Macors.Doc

September 25, 1998

Page 22 of 48

Information Resources

University of Southern California

Setting the Arguments


1. 2. In the action pane, select the >0 action then click in the arguments pane. Type the Item & Expression code shown below.

Item: Expression:
3. 4.

[Forms]![Mainform]![Tickets Purchased Subform]![Total] [Ticket_Price]*[No_of_Tickets]*0.9

In the action pane, select the ISNULL action then click in the arguments pane. Type the Item and Expression code shown below.

Item: Expression:
5. 6.

[Forms]![Mainform]![Tickets Purchased Subform]![Total] [Ticket_Price]*[No_of_Tickets]

In the action pane, =0 action then click in the arguments pane. Type the Item and Expression code shown below.

Item: Expression:
7.

[Forms]![Mainform]![Tickets Purchased Subform]![Total] [Ticket_Price]*[No_of_Tickets]

Save and close the macro.

Assign the Macro to the Form


Although Mainform is the form that we open when we wish to enter data, Tickets Purchased Subform is the form that contains the fields that are actually typed in. Therefore, we need to assign our macro to Tickets Purchased Subform. Because the user may decide to enter data into the [Ticket_Price] or [No_of_Tickets] fields in a random order, we will assign the macro triggering event to both fields. 1. 2. 3. 4. 5. 6. 7. 8. 8. Click on the Forms tab and then open Tickets Purchased Subform in Design View. Right mouse click the text box control Ticket_Price and select Properties. In the Properties window, click the Event tab and then click on the On Lost Focus line. Click the down arrow and select the macro: My Macros.DonationDiscount. Leave the Properties window open and click, click the text box control: No_of_Tickets. On the On Lost Focus line, select the macro: My Macros.DonationDiscount. Save and close the form. Open Mainform in formview. Change the number of tickets purchased or ticket price to test the macro.

Note: This macro is not without its faults. If the user happens to move the current record indicator in the Donation Info Subform to a new record, Access will not see any donations.

Access_Macors.Doc

September 25, 1998

Page 23 of 48

Information Resources

University of Southern California

MACRO 6: USING MESSAGE BOXES


You can use the MSGBOX action to send messages to the user. When combined with the condition column, this can be an effective method of ensuring that the user enters data as desired. In this example, if the patron selected in a form has the Status of No Checks, a message box will open with a notice not to accept checks from the patron. 1. 2. 3. 4. 5. 6. Click on the Macros tab. Click the macro My Macros and then click the DESIGN button. If necessary, click the Condition icon to make the Condition column visible. Skip a row from the bottom of the last macro and name for your macro: NoChecksMSG Create the macro as shown below. Save and close the macro.

Creating a Drop Down List to go to a Record - Mainform


We will use the wizards to create a drop down list that the user can pick the name of the person whose record they wish to view. Access will then go to that record. The code for the drop down list is stored within the drop down list as Visual Basic code. 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. Go into Design View of Mainform. If the Toolbox is not active, press the Toolbox icon to make it visible: Make sure that the Control Wizards button on the Toolbox is depressed. Click on the Combo Box button from the Toolbar: Click in the indented light blue area at the top of the form. (The combo box wizard starts.) Select the option: Find a record on my form based on the value I selected in my combo box. Click on NEXT. Double click: Client_ID, First_Name, and Last_Name. Click on NEXT and then NEXT again to use the default settings. Type Select a Name as the label and click on FINISH. Save the form: File - Save and go into form view: View - Form View Test the drop down list by clicking it. It should have brought you to the record you selected.

Access_Macors.Doc

September 25, 1998

Page 24 of 48

Information Resources

University of Southern California

Assign the Macro to the Form


1. 2. 3. 4. 5. 6. Click on the Forms tab and then open Mainform in Design View. Right mouse click the Select a Record combo box field and select Properties. In the Properties window, click the Event tab and then click on the On Change line. Click the down arrow and select the macro: My Macros.NoChecksMSG. Save the form then go to form view. Click the down arrow for Select a Record and select Tonya Harding. You should get the message box shown.

Access_Macors.Doc

September 25, 1998

Page 25 of 48

Information Resources

University of Southern California

MACRO 7: OPTION BOXES


An option box is an interface that allows the user to pick from a list of choices. The option box shown to the right was created from an unbound form called Labels - Complete. When the user selects an option and clicks Print Mailing Labels, a macro runs which prints the appropriate labels from a report called Customer Labels.

Examining the Query: Donation Status


The report (Customer Labels) was created using the label wizards and is based off a query called Donation Status. Donation Status was based off two linked tables (Customer Info & Donor Info) . The query is shown below.

The query uses an outer joint which specifies that all records from Customer Info should be shown but matches from Donor Info. Any person who hasnt make a donation will have a blank in their Amount_Donated column. Grouping is used because some patrons have made more than one donation and we do not want more than one label for each person. The IIF Statement is combined with the IS NULL operator to look for blanks. When a blank is found, the words Not Donated appear in the Status column. If it is not blank, Donated appears in the Status column. These two choices will be used as a where condition in the macro.

Creating the Option Group


1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. Click on the Forms tab and click the New button. Select Design View and then click OK. Resize the form to about 3 by 3. On the Toolbox, verify that the Control Wizards are active. From the Toolbox, click on the Option Group icon: Click on your form. In the pop-up window, type the options as shown: Click on NEXT. Select either option concerning the default choice. Click on NEXT. Leave the values set to 1, 2, & 3 and click NEXT. Select Option Buttons as the type of control and any style you desire then click NEXT. September 25, 1998 Page 26 of 48

Access_Macors.Doc

Information Resources 13. 14.

University of Southern California

For the caption of the frame, type: What Labels Do You Wish To Print? and click FINISH. Click the SAVE icon and name your form LABLES.

How Option Groups Work


When you place either radio buttons, check boxes, or toggle switches in an Option Group, only one of the items can be selected at a time. When one is selected, its assigned value is temporarily stored by the Option Group. In our case the three possible values are 1, 2, & 3. The condition column of our macro uses this later in the condition column. Note that option choices must be numbers.

Naming the Option Group


Because we will be using the name of the option group in our macro code, we need to give it a descriptive name prior to creating the macro. 1. 2. 3. 4. 5. Be in form design view of the Labels form. Right mouse click the Option Group frame and select Properties. (The title bar of the properties window should say: Option Group: frame number) Click on the All tab and scroll up to the Name line. Type: LabelChoice in the name column. Close the properties window and then save and close the form.

Creating the Macro


1. 2. 3. 4. Click on the Macros tab and then open My Macros in Design View Make sure both the Condition and Name columns are visible. Skipping a row, place the cursor in the names column below the last macro. Create the macro shown on the next page. Condition Action CLOSE OpenReport Description This action is used to close the Labels form after the user makes a selection and clicks OK. This Open Report line will print labels for all patrons if the user selects option 1 (Print All Labels in the option group called LabelChoice. This Open Report line will print labels just for Donators if the user selects option 2 (Print All Labels in the option group called LabelChoice. This Open Report line will print labels for non donating patrons if the user selects option 3 (Print All Labels in the option group called LabelChoice.

[LabelChoice]=1

[LabelChoice]=2

OpenReport

[LabelChoice]=3

OpenReport

Access_Macors.Doc

September 25, 1998

Page 27 of 48

Information Resources 5. Save and close My Macros.

University of Southern California

Note that the where condition tells Access to look in the Status column of the query upon which the Customer Labels report is based. It then uses either Donated or Not Donated as a criteria for deciding which labels to print.

Assigning the Macro to the Labels Form


Now that we have created the macro, we must create an OK button on our form to activate it and an Cancel button to cancel it. Create the OK Button 1. Click on the forms tab and open the Labels from in Design View. 2. Verify that the Control Wizard button on the toolbox is avtive. 3. From the Toolbox, select the Command button and then click on the form. 4. Click in the Miscellaneous category and then select the Run Macro action. 5. Click on NEXT. 6. Select the macro: My Macros.Labels and then click on NEXT. 7. Click in the Text box and type: OK then click on NEXT. 8. Name the button OKLables then click FINISH. Create the Cancel Button 1. From the Toolbox, select the Command button and then click on the form. 2. Select Form Operations category and then the Close Form action. 3. Click on NEXT. 4. Click in the Text box and type CANCEL then click on NEXT. 5. Name the object CancelLabel and then click on FINISH. Go into From View to test your macros. To place a button on the switchboard which will open the Labels form, use the Command button and select the Open Form action and select the form Labels.

Access_Macors.Doc

September 25, 1998

Page 28 of 48

Information Resources

University of Southern California

KEYSTROKE MACROS
Keystroke macros allow you execute menu commands by pressing keyboard shortcuts. Normally, the RunCommand action is used to create keystroke macros. The RUNCOMMAND action executes menu items. Below are the characteristics of keystroke macros. All of your keystroke macros must be saved in a single macro object called Autokeys. You name your submacros with the keystrokes you wish to activate them with. The keystroke macros will only work in the current database. (You can import macro objects into other databases.) The keystroke macro shortcut keys will override any of Accesses built-in keyboard shortcut keys.

Naming the Keystroke Macros


Below is a list of keys commonly used in a macro and their code equivalents. Key on Keyboard Control Shift Any Function key Insert Delete Code equivalent ^ + Place { } around the key. {INSERT} {DELETE} Examples Control A would be: ^A Shift R would be: +R Control, Shift, F7 would be: ^+{F7}

Keystroke Macro Example


We will create 3 keystroke macros to Run any query (if the query is open in design view.) Freeze the current column in any open table. Unfreeze all columns in any open table. 1. 2. 3. 4. In the database window, click on the Macros tab. Click on the New button to start a new macro. If necessary, press the Macro Names button to make the Macro Name column appear. Create the macros and their arguments as shown below.

Note that if you click in the Run argument box you can pick commands from a list of commands.

Command: Command: Command:

Run FreezeColumn UnfreezeAllColumns


Page 29 of 48

Access_Macors.Doc

September 25, 1998

Information Resources

University of Southern California

Save the Macro


The macro must be named Autokeys for the keystroke macros to function. 1. Click on Save. 2. Name the macro: Autokeys 3. Close the macro

Testing the Macro Freeze & Unfreeze Columns Macro


1. 2. 3. Click on the Tables tab and open the table Customer Info Click in the Last_Name column. From the keyboard, press: CONTROL F

The column should have moved to the extreme left. If you use the scroll bars, the other columns will move but the Last_Name column should remain frozen on the left. 4. To unfreeze the column, press: CONTROL SHIFT F

Note that the column will remain on the left but it is unfrozen. 5. Close the table.

Testing the Run Query Macro


1. 2. Click on the Queries tab and open the query Totals in Design View. To run the query, press: CONTROL + R

Access_Macors.Doc

September 25, 1998

Page 30 of 48

Information Resources

University of Southern California

MACRO 7: SELF EXECUTING MACROS


If you name a macro object Autoexec, the macro will run automatically when the database is opened. Note that Autoexec must be the name of the entire macro object (i.e. what you see if you click on the Macros tab of the database window), not what you specify in the Macro Name column within the macro object. There is an unbound form call Splash which simply says Welcome to the 24th Theatre on it. Whenever the user opens the database, we want the Autoexec macro to open the splash screen. 1. 2. Click on the Macros tab and then click the NEW button. Create the macro as shown bellow:

3. 4.

From the menu, click on: Name the Macro Object:

FILE - SAVE AUTOEXEC

Run the Autoexec Macro


1. 2. Close the database and reopen it. The splash screen should have opened automatically. Click OK to close the splash screen.

Note that the OK button on the splash screen is a command button created using the wizards.

Bypass the Autoexec Macro


To bypass an Autoexec macro, hold down the SHIFT key on the keyboard when opening the database file.

Access_Macors.Doc

September 25, 1998

Page 31 of 48

Information Resources

University of Southern California

HIDING FORM CONTROLS


To limit the users ability to affect the from itself, you may wish to hide such things as close buttons, scroll bars, etc. This section shows how to alter the controls on the form. 1. 2. 3. 4. 5. Open the form Switchboard in Design View. Right click the box in the forms upper left corner to set the properties for the entire form. Select Properties from the pop-up list. Click on the Format tab. Make the settings shown below: Views Allowed: Form Allows only form view. The other choice was datasheet. Scroll Bars: Neither - Hides the scrollbars. Record Selector: No - Hides the record selectors. Navigation Buttons: No - Hides the navigation buttons. Dividing Lines: No - Hides lines between records. Auto Resize: Yes - Resizes the form to show all records. Auto Center: Yes - Centers the from. Control Box: No - Hides the control box. Min Max Buttons: None: - Hides the Min/Max buttons. Close Button: No: - Hides the close button on the form. Whats This Button: No: - Hides the ? button. 6. Save the form and go into Form View to see the changes.

Access_Macors.Doc

September 25, 1998

Page 32 of 48

Information Resources

University of Southern California

SETTING STARTUP PARAMETERS


Here we can have the switchboard load automatically when the file containing it is opened, hide menu items, toolbars, and the database window, thus preventing users from going places we may not wish them to be. 1. 2. 3. 4. From the menu, click on: TOOLS - START UP Click the Advanced button to see all options. Set the Display Form to Switchboard. Remove checks from all boxes. This will remove the users access to most Access menus and all icons thus forcing them to use your switchboard and removing the chances of them harming your database.

5. 6.

Click on OK and close the database. Reopen the database. Only your switchboard and a limited menu should be visible.

Temporarily Bypassing the Startup Limitations


To open the database without the startup limitations in effect, simply hold down the SHIFT key on the keyboard while opening the database.

Removing Startup Limitations


To permanently remove the startup options, you must open the database with the SHIFT key held down, and then access: TOOLS - STARTUP from the menu and place the checks back in the boxes and remove the form from Display Form.

Access_Macors.Doc

September 25, 1998

Page 33 of 48

Information Resources

University of Southern California

HIDING DATABASE OBJECTS


If you need to display the database window but would like to hide certain database objects such as saved queries, tables, forms, reports, or macros, you can. This is a wise precaution if you have several people working on a database and you do not wish them to delete one of your objects. This is a two step procedure: a. Hide the objects. b. Tell Access not to display hidden objects. Step 1: Hide the Object: 1. Right mouse click the table, query, report, etc.. to be hidden. 2. Select Properties from the pop-up list. 3. Check the Hidden attribute and click on OK. (The object is dimmer but still visible.) Step 2: Dont Display Hidden Objects: 1. From the menu, click on: TOOLS - OPTIONS. 2. Click on the View tab. 3. Remove the check from Hidden Objects and click on OK. The object should be invisible.

Unhiding Database Objects


To unhide a database object, you merely need to reverse the procedure above. 1. From the menu, click on: TOOLS - OPTIONS. 2. Click on the View tab. 3. Check Hidden Objects and click on OK. (The object is now visible but dim.) 4. Right mouse click the table, query, report, etc., to be unhidden. 5. Select Properties from the pop-up list. 6 Uncheck the Hidden attribute and click on OK. (The object is now completely visible.)

Access_Macors.Doc

September 25, 1998

Page 34 of 48

Information Resources

University of Southern California

ADVANCED FORM CALCULATIONS


The bottom of the form contains 3 calculations: Total Amount Donated: This adds up all of the donations for the current patron. It uses an access function called DSUM. Total Spent: This adds up the total amount spent on all shows seen by the current patron. It uses an Access function called DLOOUP which pulls the answer from a query called Totals. Pulling the calculation from a query was necessary because of DSUM limitations. Number of Visits: This counts the number of shows the patron has seen. It also employees the DLOOKUP function to pull the answer from the Totals query.

For the basics on creating calculations in forms, see the handout Access Forms - Beginning located on the web at: http://www.marshall.usc.edu/computing/training/Handouts.htm

The Query Used by Dlookup


Both of the Dlookups are based off a query called Totals which was based off the table Tickets Purchased. Design view of the query is shown below. Note that for our Dlookup to function, we had to include the primary key (Client_ID) in the query. This is because we need to see the total spend for a particular client and Access needs a way to connect a client in the query to a client in the form. Field Client_ID Total Spent: Sum([Ticket_Price]*[No_of_Tickets]) Expression Number of Tickets: No_of_Tickets Sum Visit Count: Client_ID Count

Total Sort Show Criteria

Group by

For more information on how this query was created and the principles behind it, download the handouts: Queries-Beginning & Queries-Advanced on the following web site: http://www.marshall.usc.edu/computing/training/Handouts.htm

Access_Macors.Doc

September 25, 1998

Page 35 of 48

Information Resources

University of Southern California

The DSUM Function


We will use the DSUM function to add up the total amount spent by the currently displayed patron. Note that there is also a SUM function. SUM can also be used to sum up the total for a field; however, it will sum up the total for all patrons, not just the currently displayed one. DSUM works by accessing the table that the field exists in and adding that up, but only for the record currently displayed in the form. The syntax for DSUM is as shown below. Note that the placement of commas, periods, braces, parenthesis, and quotes is crucial.

=DSUM([Name of field to be summed],Table field is in,[Linking field in table]=form.[Linking field in form])


In our example DSUM would read as follows:

=DSum("[Amount_Donated]","Donor info","[Client_ID]=form.[Client_ID]")
This is the name of the field to be summed. This is the name of the table that the field to be summed exists in. This is the name of the field in the table that is the primary key. This is the name of the field in the form that links the data to the table.

In English, this statement would read something like this: Sum up the Amount_Donated field in the Donor Info table but only for records where the Client_ID in the Donor Infotable is equal to this forms currently displayed Client_ID. 1. 2. 3. 4. 4. 5. While in form Design View, click on the Text Control icon on the Toolbox: Click in the blue area at the bottom of the form. Click inside of the box on the right (text control), type the equation above and then press ENTER. Click inside of the box on the left (label control) and type: Total Amount Donated Save the form and then go to form view: Veiw - Form View Go to the next record to see the Total Amount Donated change.

Access_Macors.Doc

September 25, 1998

Page 36 of 48

Information Resources

University of Southern California

The DLOOKUP Function


DLOOKUP tells Access to display a field from a related table or query in the current form (or report). It provides a method of making a field which is not part of the table that the form was based on show up in the form. The syntax of DLOOKUP is as follows:

=Dlookup([Field to be displayed],Table field is in,[Linking Field in Table]=form.[Linking field in form]) For our example, the equation will be as follows:

=DLookUp("[Total Spent]","Totals","[Client_ID]=form.[Client_ID]")
This is the name of the field to be displayed. This is the name of the query containing the field to be displayed.. This is the name of the field in the query that links the query to the form. It is the primary field. This is the name of the field in the form that links to the query and tells Access for which client should it display information.

In English, this might read: Display the field called Total Spent from the query called Totals and make sure you display the Total Spent for the client whose Client_ID in the query, matches the Client_ID currently displayed in the form. This last part is the most confusing but it is necessary. Without it, Access would know which column to display but not which row. Dlookup for Number of Visits To get the Number of Visits, simply copy the previous Dlookup and replace [Total Spent] with [Visit Count]

Access_Macors.Doc

September 25, 1998

Page 37 of 48

Information Resources

University of Southern California

Removing Tab Stops


Note that when you move through the form by pressing tab, the cursor goes to the calculated fields. Since you will never be typing in the calculated fields, this is undesirable. 1. 2. 3. 4. 5. Go into Form Design View: View - Design View Right mouse click on one of the calculations and select Properties from the drop down list. Click on the Other tab and set Tab Stop to NO. Do the same for the other calculated fields and the macros. Test the form again in Form View then save the form.

Access_Macors.Doc

September 25, 1998

Page 38 of 48

Information Resources

University of Southern California

MODULES: CREATING CUSTOM FUNCTIONS


Modules use Visual Basic code which as mentioned previously, can not be learned is just a few hours; however, creating custom functions is fairly simple and can be mastered within a few minutes. Like built-in functions, the purpose of custom functions is to save the user time when typing often used mathematical formulas. Rather than typing a long formula, the user can enter a shorter and usually simpler function. Further, custom functions can be used in queries, forms, and reports..

Function Basics
A function must begin with the word Function and end with End Function The name of a function must be unique. (i.e. a name not already used by another function.) Separate multiple variables with commas. Variable names used within the same function must be unique but different functions can have the same variable names. To place comments or remarks in your function, precede the comment with an apostrophe .

Function Example 1: OC Tax Rate


This is a very simple function which calculates tax on a given amount. The function assumes a 0.0775 tax rate. 1. 2. Click on the Modules tab and then NEW. Type the function shown below:

You must give your function a unique name followed by an opening and closing round brace. Place all variables within the braces. When functions employ multiple variables, separate the variables with commas. i.e. OCTax(x,y,z) All functions must begin with the word Function and end with the words End Function.

Function OCTax(X) OCTax = X * 0.0775 End Function


Here is where you define what the function does and what to do with the variable.

Access_Macors.Doc

September 25, 1998

Page 39 of 48

Information Resources

University of Southern California

Testing Functions
The function created above can be used in a form, query, or report in the same manner any function is used. However, Access provides a method of testing it from within the module it was created. 1. 2. 3. You are still in the module which you created the function above. From the toolbar, click on the Debug Window icon: In the bottom pane of either the Locals or Watch window, type whats shown below and then press ENTER. (Note that when testing a function in the debug window, you must precede the function with a question mark.

?OCTax(100)
4. 5. Access should have returned 7.75. Close the Debug Window. Save the Module as Functions. (Note that it can be named anything.)

Function Example 2: Fahrenheit to Celsius


This example will create a custom function that will convert Fahrenheit temperatures into Celsius. The formula for converting Fahrenheit to Celsius is: C=(5F-160)/9 The formula is not too lengthy, but a custom function would make it even easier to use. 1. 2. You are still in the Function module . Click below your previous function and type whats shown below. Remember to press enter after each line.

' Fahrenheit To Celsius ' This function converts Fahrenheit to Celsius ' The name of the function is FtoC ' The Variable F is for Fahrenheit

Function FtoC(F) FtoC = (5 * F - 160) / 9 End Function


3. Open the Debug Window and type the following to test the function: Access should have returned 100. Close the debug window and save the function.

?FtoC(212)

4.

Access_Macors.Doc

September 25, 1998

Page 40 of 48

Information Resources

University of Southern California

Function Example 3: IF Statements & Multiple Variables


IF statements insert flexibility into equations by allowing different outcomes based upon a criteria. Simple IF statements allow two different possible outcomes. IF Statements must begin with IF and end with END IF The ELSE line tells the program what to do if the condition is false. The ELSE line may be omitted if nothing is to happen when the condition is not true. When ELSE is omitted, and the answer is false, Excel executes any code after the END IF line but before the END FUNCTION line. IF statements can be nested by using the ELSE IF option. Operators allowed: > >= < <= <> = The keywords: AND & OR may also be used. Syntax: IF Condition THEN What to do if the condition is true ELSE What to do if the condition is false END IF

Discounts Based Upon Quantity Purchased


The purpose of this function is to multiply the COST of an item times the QUANTITY purchased. However, if the QUANTITY purchased is 50 or greater, then the there is a 15% discount on the price. 1. Position the cursor below the previous function and type the following:

The name of this function is TOTAL C stands for COST Q stands for QUANTITY

Function Total(C, Q) If Q >= 50 Then Total = C * Q * 0.85 Else Total = C * Q End If End Function
2. Open the Debug Window and type the following: =Total(10,100) (Because COST is $10 and the QUANTITY of 100 is greater than 50, the discount applies and Access should return: 850) Try one where the quanty is less than 50: =Total(10,10) (Because COST is $10 and the QUANTITY of 10 is less than 50, the discound does not apply and Access returns: 100) Close the Debug Window and save the module. September 25, 1998 Page 41 of 48

3.

4.

Access_Macors.Doc

Information Resources

University of Southern California

Example 4:

Nested If Statements

This IF example utilizes the AND operator and the ElseIF command (one word) to provide for more than two possible answers. The table below shows the discounts available. Quantity ordered 0-50 51 to 999 1000 and over 1. Discount No discount 15% 25%

Click below the previous function and type the following:

Function DISCOUNT (C,Q) If Q > 50 And Q < 1000 Then DISCOUNT = C * Q * .85 ElseIf Q > 999 Then DISCOUNT = C * Q * .75 Else DISCOUNT = C * Q End If End Function
2. Open the Debug Window and try the formulas shown below:

Formula used
?Discount(1,10) ?Discount(1,100) ?Discount(1,1000)

Result
10 85 750

Access_Macors.Doc

September 25, 1998

Page 42 of 48

Information Resources

University of Southern California

Function Example 5: Select Case


Select Case is similar to an IF statement in that it provides for multiple outcomes; however, when there are numerous possible outcomes, If Statements become unwieldy and Select Case a better choice. SYNTAX Function Name Select Case Expression (What is being evaluated) Case Condition Action What to do if Case is true Case Else Action to take if no other cases are true (Case Else is optional) End Select End Function The Select Case statement must begin with Select Case and end with End Case. Select Case reads from top down and stops when it finds a match. CASE IS must be used when employing comparison operators (>,<, >=, <=, <>, =). An optional Case Else may be used for any input which is not covered by the other cases.

The Condition can take several forms: Comma lists: Case 1, 3, 5 Ranges: Case 5 to 10 (Note the use of TO and that smaller numbers must be listed first) Comparison Operators: Case Is >40 (Note use of IS when using >, <, etc.)

Determining Letter Grades Based on a Test Score


In this example, we wish to assign a letter grade based upon a numeric test grade: 100 to 90 = A, 80 to 89 = B, 70 to 79 = C, 60 to 69 = D, and anything less than 60 is an F. 1. Click below the previous function and type what is shown on the next page.

Access_Macors.Doc

September 25, 1998

Page 43 of 48

Information Resources

University of Southern California

Function letter(score) Custom functions must end with the End Function command.
The Select Case statement must end with the End Select Statement

Select Case score Case 60 To 69.999999 letter = "D" Case 70 To 79.999999 letter = "C" Case 80 To 89.999999 letter = "B" Case 90 To 100 letter = "A" Case Is < 60 letter = "F" Case Else letter = "Pending" End Select End Function

Note that the name of the variable is Score and it is used again in Select Case

Note that text must be enclosed in quotes.

Use Case is when using Comparison Operators.

Case Else (optional) covers anything not falling under any other cases (101 or blanks for example).

2.

Open the Debug Window and try the following: Should return an A Should return a D Should return a C Should return a B Should return an F Should return Pending

?Letter(98) ?Letter(60) ?Letter(75) ?Letter(80) ?Letter(50) ?Letter(101)

3.

Close the debug window and save the module.

Access_Macors.Doc

September 25, 1998

Page 44 of 48

Information Resources

University of Southern California

Function Example 6: Working With Dates


In this example, we will take an employees Hire Date and then express in years and months how long they have worked for us. This combines several Access functions into one simple custom function. The functions used are explained below. You may want to test with these functions in the Debug Window.

Functions Employed:

Now()
This returns the current date on time according to your computer clock. To test it in the Debug Window, type: ?Now()

DateDiff(Units of measure,#First date#,#Second date#)


This function subtracts the First Date from the Second Date and expresses the answer in units of your choice (days, months, years, etc.) Units of Measure Available Unit of Measure Description yyyy In Years d In Days w In Weeks y Numeric Day of Year h In Hours To test it in the Debug Window, type:

Unit of Measure n s q ww m

Description In Minutes In Seconds In Quarters The Week Number In Months

?DateDiff(yyyy,#1/1/70#,Now())

This would subtract January 1, 1970 from todays date and express the answer in years.

Int(number)
For example, For example, For example,

or

\
would return just 44. would return just 2 (Three goes into seven two times.) would also return just 2 (Three goes into seven two times.)

This function returns only whole numbers (what is to the left of the decimal) and does not round up or down. ?Int(44.99) ?Int(7/3) ?7\3

MOD
This operator divides one number by another and returns only the

2.3 3 7 6 1

1 is the remainder

remainder. We will use this to get months. For example, 7 Mod 3 would return 1, not 2.3. (Three goes into seven two times with one left over. Remember doing division before calculators?) Access_Macors.Doc September 25, 1998

Page 45 of 48

Information Resources

University of Southern California

Finding the Number of Years


We will attempt to find the number of years using the DateDiff() function with yyyy units. 1. Click below the previous function and type the following:

Function Tenure(b, e) Tenure = DateDiff("yyyy", b, e) & " Years " End Function

2. 3.

Open the Debug window and type the following: When you press enter you should get: 38 Years

? Tenure (#1/1/60#,#12/2/98#)

However, there is a slight problem with using this method. In the debug window, type the following and press Enter:

? Tenure (#12/1/98#,#1/1/99#)
Note that Access returns: 1 Years This is incorrect, there is not a full year between December 1, 1998 and January 1, 1999. The problem occurs because when using yyyy as the units, Access only looks at the year, not the day or month. To Access, the difference between 99 and 98 is 1. To get more accurate results, we will express the units in months m and then divide by 12 to find the years. 4. Alter the function as shown:

There is a slight problem with the DateDiff function. When you are finding the difference between December date and a January date of the following year, it returns 1 even though only a month has passed, not an entire year.

Tenure
5.

= DateDiff("m", b, e) /12 & " Years "

In the debug window, type the following and then press enter after each one:

? Tenure(#12/1/98#,#1/1/99#) ? Tenure(#1/1/60#,#1/1/99#)

Access returns 8.33E-02 Years Access returns 38.9 Years

This is more accurate but we do not wish to see anything to the left of the decimal being that we will be expressing the remainder in months. Therefore, we will use the Int() function to display only whole numbers. Access_Macors.Doc September 25, 1998 Page 46 of 48

Information Resources 6. 7. Edit the function as shown: Tenure =

University of Southern California

Int(DateDiff("m", b, e) /12) & " Years "


Access returns 0 Years Access returns 38 Years

In the Debug Window, try the two examples shown:

? Tenure(#12/1/98#,#1/1/99#) ? Tenure(#1/1/60#,#1/1/99#)
Getting Months

We will use the MOD command to pick up the remaining months. (MOD divides two number and returns only the remainder. 1. Create the following function:

Function Mon(b,e) Mon=DateDiff("m", b, e) Mod 12 & " Months" End Function


2. Try the following in the Debug Window

? Mon(#1/1/60#,#1/1/99#) ?Mon(#1/15/98#,#5/1/98#) ?Mon(#12/30/98#,#1/1/99#)

Access returns 0 Months Access returns 4 Months Access returns 1 Months

as in 38 years, 0 months as in 0 years, 4 months as in 0 years, 1 months

Note that the last example returns 1 month when really only a few days have passed. This occurs because when using m, Access looks only at the month number when finding the difference With more effort this could be solved too but we will end our efforts here.

Combine the Two Tunctions into a Single Function


Combine the previous functions into a new function called Tenure. Note the use of & to join the two functions together. Function tenure(b, e)

tenure = Int(DateDiff("m", b, e) / 12) & " Years, " &


End Function Access_Macors.Doc September 25, 1998

DateDiff("m", b, e) Mod 12 & " Months"

Page 47 of 48

Information Resources

University of Southern California

Access_Macors.Doc

September 25, 1998

Page 48 of 48

You might also like