Professional Documents
Culture Documents
Access 97
Macros & Switchboards
Topics:
Creating Forms Calculations in Forms Command Button Wizard Switchboards Macros Start Up Parameters Charts
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
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.
Access_Macros.Doc
Page 4 of 48
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
Page 5 of 48
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.
Access_Macros.Doc
Page 6 of 48
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.
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
Page 7 of 48
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.
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
Page 8 of 48
Information Resources
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
Page 9 of 48
Information Resources
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.
Access_Macors.Doc
Page 10 of 48
Information Resources
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.
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
Page 11 of 48
Information Resources
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
Page 12 of 48
Information Resources
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.
Access_Macors.Doc
Page 13 of 48
Information Resources
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.
Access_Macors.Doc
Page 14 of 48
Information Resources
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.
Access_Macors.Doc
Page 15 of 48
Information Resources
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.
[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
Page 16 of 48
Information Resources
Access_Macors.Doc
Page 17 of 48
Information Resources
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.
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
Access_Macors.Doc
Page 19 of 48
Information Resources
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
Page 20 of 48
Information Resources
4. 5. 6.
7.
Access_Macors.Doc
Page 21 of 48
Information Resources
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.)
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
Page 22 of 48
Information Resources
Item: Expression:
3. 4.
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.
In the action pane, =0 action then click in the arguments pane. Type the Item and Expression code shown below.
Item: Expression:
7.
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
Page 23 of 48
Information Resources
Access_Macors.Doc
Page 24 of 48
Information Resources
Access_Macors.Doc
Page 25 of 48
Information Resources
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.
Access_Macors.Doc
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.
[LabelChoice]=1
[LabelChoice]=2
OpenReport
[LabelChoice]=3
OpenReport
Access_Macors.Doc
Page 27 of 48
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.
Access_Macors.Doc
Page 28 of 48
Information Resources
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.
Note that if you click in the Run argument box you can pick commands from a list of commands.
Access_Macors.Doc
Information Resources
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.
Access_Macors.Doc
Page 30 of 48
Information Resources
3. 4.
Note that the OK button on the splash screen is a command button created using the wizards.
Access_Macors.Doc
Page 31 of 48
Information Resources
Access_Macors.Doc
Page 32 of 48
Information Resources
5. 6.
Click on OK and close the database. Reopen the database. Only your switchboard and a limited menu should be visible.
Access_Macors.Doc
Page 33 of 48
Information Resources
Access_Macors.Doc
Page 34 of 48
Information Resources
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
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
Page 35 of 48
Information Resources
=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
Page 36 of 48
Information Resources
=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
Page 37 of 48
Information Resources
Access_Macors.Doc
Page 38 of 48
Information Resources
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 .
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.
Access_Macors.Doc
Page 39 of 48
Information Resources
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.)
' Fahrenheit To Celsius ' This function converts Fahrenheit to Celsius ' The name of the function is FtoC ' The Variable F is for Fahrenheit
?FtoC(212)
4.
Access_Macors.Doc
Page 40 of 48
Information Resources
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
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%
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
Page 42 of 48
Information Resources
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.)
Access_Macors.Doc
Page 43 of 48
Information Resources
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
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
3.
Access_Macors.Doc
Page 44 of 48
Information Resources
Functions Employed:
Now()
This returns the current date on time according to your computer clock. To test it in the Debug Window, type: ?Now()
Unit of Measure n s q ww m
?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
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.
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#)
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
? 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:
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.
Page 47 of 48
Information Resources
Access_Macors.Doc
Page 48 of 48