BOOK 1999 Macros and SwitchBoard

download BOOK 1999 Macros and SwitchBoard

of 48

Transcript of BOOK 1999 Macros and SwitchBoard

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    1/48

    Information Resources

    .

    Access 97Macros & Switchboards

    Topics: Creating Forms

    Calculations in Forms Command Button Wizard

    Switchboards

    Macros

    Start Up Parameters

    Charts

    Marshall School of BusinessUniversity of Southern California

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    2/48

    Table of Contents

    DEFINITIONS.................................................................................................................................... 4Switchboard..................................................................................................................................... 4MACRO.......................................................................................................................................... 4Module ............................................................................................................................................ 4

    Where Macros/Modules Are Stored................................................................................................. 4ABOUT THE DATABASE................................................................................................................. 5DATA ENTRY FORM........................................................................................................................ 6

    EXAMINING Mainform - Complete............................................................................................ 6SWITCHBOARDS.............................................................................................................................. 7

    Examining A Completed Switchboard ............................................................................................. 7CREATING A SWITCHBOARD........................................................................................................ 8

    The Toolbox Toolbar.................................................................................................................... 8Create the Button: Dollars to Goal............................................................................................... 9Create the Button: Total Donations.............................................................................................. 9Create the Button: Non Donating Patrons .................................................................................. 10

    MACROS.......................................................................................................................................... 11Macro Basics ................................................................................................................................. 11Exploring an Existing Macro ......................................................................................................... 11

    MACRO 1: OPEN THE MAINFORM ............................................................................................. 13Assign the Macro to the Switchboard Button ................................................................................. 13Test the Macro............................................................................................................................... 13

    Macro 2: Add New Records Macro ................................................................................................... 14Set the Arguments for GoToRecord............................................................................................... 14Set the Arguments for GoToControl .............................................................................................. 14Assign the Macro to the MainForm without the Wizards Help...................................................... 15

    UNDERSTANDING EVENTS......................................................................................................... 15

    MACRO 3: ATTENDANCE HISTORY ........................................................................................... 16Setting Arguments for the Actions ................................................................................................. 16Create the Combo Box................................................................................................................... 17Assign the Macro to the Drop Down List....................................................................................... 17

    MACRO 4: DONATION HISTORY................................................................................................. 18Setting Arguments for the Actions ................................................................................................. 18Create the Combo Box................................................................................................................... 19Assign the Macro to the Drop Down List....................................................................................... 19

    MACRO 5: CONDITION COLUMN................................................................................................ 20Condition Example 1 ..................................................................................................................... 20Setting Action Arguments.............................................................................................................. 21

    Assign the Macro to the Form........................................................................................................ 21Condition Example 2 ..................................................................................................................... 22Setting the Arguments ................................................................................................................... 23Assign the Macro to the Form........................................................................................................ 23

    MACRO 6: USING MESSAGE BOXES........................................................................................... 24Assign the Macro to the Form........................................................................................................ 25

    MACRO 7: OPTION BOXES........................................................................................................... 26Examining the Query: Donation Status ......................................................................................... 26Creating the Option Group............................................................................................................. 26

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    3/48

    How Option Groups Work............................................................................................................. 27Naming the Option Group ............................................................................................................. 27Creating the Macro........................................................................................................................ 27Assigning the Macro to the Labels Form........................................................................................ 28

    KEYSTROKE MACROS.................................................................................................................. 29Naming the Keystroke Macros....................................................................................................... 29

    Keystroke Macro Example............................................................................................................. 29Save the Macro.............................................................................................................................. 30Testing the Macro Freeze & Unfreeze Columns Macro.................................................................. 30Testing the Run Query Macro........................................................................................................ 30

    MACRO 7: SELF EXECUTING MACROS...................................................................................... 31Run the Autoexec Macro ............................................................................................................... 31Bypass the Autoexec Macro........................................................................................................... 31

    HIDING FORM CONTROLS........................................................................................................... 32SETTING STARTUP PARAMETERS ............................................................................................. 33

    Temporarily Bypassing the Startup Limitations ............................................................................. 33Removing Startup Limitations ....................................................................................................... 33

    HIDING DATABASE OBJECTS...................................................................................................... 34Unhiding Database Objects............................................................................................................ 34ADVANCED FORM CALCULATIONS.......................................................................................... 35

    The DSUM Function ..................................................................................................................... 36The DLOOKUP Function .............................................................................................................. 37Dlookup for Number of Visits........................................................................................................ 37Removing Tab Stops ..................................................................................................................... 38

    MODULES: CREATING CUSTOM FUNCTIONS .......................................................................... 39Function Basics ............................................................................................................................. 39Function Example 1....................................................................................................................... 39Testing Functions .......................................................................................................................... 40Function Example 2: Fahrenheit to Celsius ................................................................................... 40Function Example 3: IF Statements & Multiple Variables............................................................. 41Discounts Based Upon Quantity Purchased.................................................................................... 41Example 4: Nested If Statements................................................................................................... 42Function Example 5: Select Case................................................................................................. 43Determining Letter Grades Based on a Test Score ......................................................................... 43Function Example 6: Working With Dates.................................................................................... 45Functions Employed: ..................................................................................................................... 45Finding the Number of Years......................................................................................................... 46Getting Months.............................................................................................................................. 47Combine the Two Tunctions into a Single Function....................................................................... 47

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    4/48

    Marshall School of Business University of Southern California

    Access_Macros.Doc February 26, 1999 Page 4 of 48

    DEFINITIONS

    Switchboard

    A Switchboard is a screen with buttons on it that automate database functions. Its purpose is tomake Access easier to use for novice users while keeping sensitive areas of the database protectedfrom misuse. The switchboard screen itself is created from an unbound form (a form which is notbased on a table) and the buttons on the switchboard activate either macro or Visual Basic codesequences. 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 placingthe hourglass on the screen.

    Module

    A module is a unit of Visual Basic programming code that you can use to add additional functionalityto Access. By using Visual Basic, Access can be used to perform operations its designers did not buildinto 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 arecalled stand alone because they can be made to work alone or assigned to an Access object such as aform, query, etc.

    Form Created Macros/Modules - When you create a Command Button in a form to automateoperations, the macro is stored within the button as visual basic code and will not appear within theMacros or modules tab.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    5/48

    Marshall School of Business University of Southern California

    Access_Macros.Doc February 26, 1999 Page 5 of 48

    ABOUT THE DATABASEThis handout utilizes a database called 24th Street Theatre.mdb. The database can be found in twolocations:

    From HOH300, HOH401, & Bri202, it can be copied from: M:\Prof\Training

    to yourA 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 werepurchased, and how much money they have donated to the theatre. It is made up of 3 tables which arerelated 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 thisdatabase. 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 oftickets, and ticket price will appear in this database. If they have seen more than one show, then theirClient_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 atthe following web address: http://www.marshall.usc.edu/computing/training/Handouts.htm

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    6/48

    Marshall School of Business University of Southern California

    Access_Macros.Doc February 26, 1999 Page 6 of 48

    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 twosubforms Donor Info Subform and Tickets Purchased Subform. It also contains three calculatedfields and two command controls. It is there as an example of what we will create using theMainForm.

    Donor Info Subform - This form accesses fields from the table Donor Info. It is never openeddirectly 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 isnever opened directly but is pulled into the Main Form when the Main Form is opened. Inaddition, 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 DonorInfo Subform and Tickets Purchased Subform. When we are finished, it will have everythingMainForm - Complete has.

    For more information on creating subforms, see the handout: Forms - Beginning which can befound 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. 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.

    2. Close the MainForm - Complete after examining it.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    7/48

    Marshall School of Business University of Southern California

    Access_Macros.Doc February 26, 1999 Page 7 of 48

    SWITCHBOARDS

    A Switchboard is a screen with buttons on it that automate database functions. The purpose of aswitchboard is to make Access easier to use for novice users and while keeping sensitive areas of thedatabase 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 whichwere created using wizards and three controls which employ macros. To view the form:

    1. Click on the Forms tab.2. Double click the form Switchboard - Complete to open it.

    These 3 buttonswere createdusing theCommandButtonWizards andrun saved

    queries.

    These 2 buttons were created using the Command Button Wizards and open

    saved forms which contain charts.

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

    box.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    8/48

    Marshall School of Business University of Southern California

    Access_Macros.Doc February 26, 1999 Page 8 of 48

    Select Objects: Allows the selection of

    objects.

    Control Wizards: When turned on,

    wizards will help with using other tool

    box controls.Label: Used for placing text on any part

    of your form.

    Text Box: Used to create calculations.

    Toggle Button: Toggles between two choices.

    List Box: Allows selection from a list of choices.

    Image: Use to place pictures from a

    source outside the database on the form.

    Option Group: Used in conjunctionwith 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.

    Check Box: Used with Yes/No fields.

    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.

    Line: Use to place lines on your form.

    More Controls: Opens a list of more

    advanced controls.

    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.

    SubForm/SubReport: Use to create a

    form within a form.

    Rectangle: Places a rectangle in the

    form.

    Combo Box: Allows selection from a

    drop down list of choices.

    CREATING A SWITCHBOARDAs mentioned above, a switchboard is created from an unbound form. The steps in this section showhow 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 screen5. 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 notvisible 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 commandwizards will not help you.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    9/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 9 of 48

    Create the Button: Dollars to Goal

    We will use the command button wizard to create this button. When pressed, the button will open aquery 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 SUMfunction rather than using the Totals row.

    1. The Switchboard form is still open and you are inDesign View.

    2. From the Toolbox, click on the Command Button icon:3. Click in the upper right corner of the form.4. From the Command Button Wizard, select the Miscellaneous category.5. In the Action window, select Run Query and click NEXT.6. Select the query $ to Goal and click NEXT.7. Select the Text option and type: Dollars to Goal.

    8. Click on NEXT.9. Name the button: Dollars to Goal and click FINISH.10. Go into Form View and click the command button. It should run the query.11. 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. Whenpressed, 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. The form Switchboard is still open and you are in Design View.2. From the Toolbox, click on the Command Button icon:3. Click below the last button created.4. From the Command Button Wizard, select the Miscellaneous category.5. In the Action window, select Run Query and click NEXT.6. Select the query Total Current Donations and click NEXT.7. Select the Text options and type: Total Donations.8. Click on NEXT.

    9. Name the button:Total Donationsand click FINISH.10. Go into Form View and click the command button. It should run the query.11. Close the query window and then click the Save icon to save the form.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    10/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 10 of 48

    Create the Button: Non Donating Patrons

    We will use the command button wizard to create this button. When pressed, the button will open aquery called Not Donated. The query (shown below) was created by creating an outer joint betweentwo linked tables: Customer Info and Donor Info. All clients will be in Customer Info butDonor Info. will only have a matching client ID if the client has made a donation. The query thenlists 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. The Switchboard form is still open and you are in Design View.2. From the Toolbox, click on the Command Button icon:3. Click below the last button created.4. From the Command Button Wizard, select the Miscellaneous category.5. In the Action window, select Run Query and click NEXT.6. Select the query Not Donated and click NEXT.7. Select the Text options and type: Non Donating Patrons.8. Click on NEXT.

    9. Name the button: Non Donating Patronsand click FINISH.10. Go into Form View and click the command button. It should run the query.11. 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.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    11/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 11 of 48

    MACROSThree of the buttons on our switchboard employ macros: Open Mainform,Attendance History, andDonations 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 inthe database window, each macro listed can contain multiple sub macros. Sub macros are createdby placing a name in the Name column. If there is no name in the name column then Access willread 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 itsees 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 youcan have a macro perform.

    Exploring an Existing Macro

    1. Click on the Macros tab.2. 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 PatronShow History. It then filters the query to only show the records for the name chosen from the dropdown list.

    Donor History: This macro runs the drop down list on the switchboard and runs a query calledPatron Donor History. It then filters the query to only show the records for the name chosen fromthe drop down list.

    Add New Records: This macro takes the cursor to a new record in the Mainform - Complete formand then positions the cursor in the First_Name field.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    12/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 12 of 48

    Macro Name: For amacro object to containseveral macros, you mustname the individualmacros in the Macro

    Name column. Accessreads code from top to

    bottom and will stopreading when it reaches

    another macro name. Ifyou did not use macronames, access would readall of the code in the

    macro object.

    Condition: If youplace a condition inthis column, Accesswill only execute thecode next to thecondition if thecondition is true. Notethat true or false, theline below will be

    read. An example of acondition might be tocheck to see if an orderdate is before the

    required date.

    Action: This is theactual macro code thatis executed by access.You can select from 49different actions.

    Once an action isselected, any specificsare set below in the

    arguments pane.

    Comments:

    Comments are optionaland serve as remindersor explanations toyourself for what eachline of code is for.Access ignoreseverything 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.

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

    Macro Names: Click this button to display/hide the Macro Names column in themacro pane.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    13/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 13 of 48

    MACRO 1: OPEN THE MAINFORMThis macro will be assigned to the Open Mainform button on the switchboard. When pressed, themacro will open the form called Mainform.

    1. Close the Macros - Complete module if it is still open.2. Click on the Macros tab if you are not currently there.

    3. Click on the New button to start a new macro.4. Click the Macro Names icon to display the macro name column.5. Name the macro: Open Main form.6. In theAction column, select OpenForm.

    Setting Arguments for the ActionMake sure the cursor is still on the Open Mainform line in the action pane before going to theArguments section.7. Set theForm Name to MainForm.8 Set the View to Form.9. LeaveFilter Name and Where Condition blank.10. Set theData 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 Button1. Click on the Forms tab.2. Select the form Switchboard and then click the DESIGNbutton.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.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    14/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 14 of 48

    Macro 2: Add New Records MacroThis macro will be assigned to Main Form and will tell Access to begin a new record and position thecursor in the cursor in the First_Name field.

    1. Click on the Macros tab.2. Click the macro My Macros and then click the DESIGN button.

    3. Skipping a row, place the cursor below the previous macro.4. In the Macro Names column, type: Add New Records5. In the Action column, click the down arrow and select:

    GotoRecord

    6. Click in the row below Go to Record and click the downarrow to select: GoToControl

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

    Set the Arguments for GoToRecordHere we will tell access which record to go to. (a new record)1. In the top pane, click anywhere in the words: GotoRecord2. 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: GoToControl2. In the Arguments Pane, make the following settings:

    Control Name: First_Name

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

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    15/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 15 of 48

    Assign the Macro to the MainForm without the Wizards Help

    1. Click on the Forms tab and open Mainform in Design View.2. From the Toolbox toolbar, shut off the wizards by clicking the Control Wizards button.3. From the Toolbox toolbar, click on the Command button and then click the form.2. Right mouse click the command button we just created and select Properties.3. Click on the Event tab.

    4. Click in the box on the line: On Click.5. Click the down arrow and select the macros called: My Macros.Add New Records6. Save the form and go to form view.7. 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 betriggered by other actions as well such as opening a form or when an error message occurs. To view alist of possible events used in a form:

    1. Open any form in design view.2. Click on one of the Text controls and open the properties window.3. Click on the Event tab.

    Note that to get more information than whats shown below, you can click on an event line and pressF1 on the keyboard.

    Focus: A control is said to have the focus when it can receive input through the mouse or keyboard.

    Before Update: The event occurs before the data in a control (field) is updated (saved).After Update: The event occurs after the data in a control (field) is updated (saved).On Change: The event occurs when the contents of a text box changes.Not on List: The event occurs when test is entered into a combo box that isnt on the list.On Enter: The event occurs before the control actually receives the focus.On Exit: The event occurs just before the control loses the focus to another control on

    the same form.On Got Focus: The event occurs when the control gets the focus.On Lost Focus: The event occurs when the controls loses the focus.

    The remaining events should be self explanatory.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    16/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 16 of 48

    MACRO 3: ATTENDANCE HISTORY

    This macro will also be assigned to the Attendance History drop down menu on the switchboard andis made up of three macro actions. When a patrons name is selected from the drop down list, a querycalled Patron Show History will run and the macro will filtrate all names out except the one chosenfrom the list.

    1. Click on the Macros tab.2. Click the macro My Macros and then click the DESIGN button.3. Place the cursor two rows below the previous macro.

    4. Name the macro Show History.5. Select OpenQuery in theAction column.6. Below OpenQuery, select ApplyFilter as the next action.7. Below ApplyFilter, select Save as the last action for this macro.

    Setting Arguments for the Actions

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

    4. Above, select theAction ApplyFilter5. 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 theclient chosen from the drop down menu (called show history) on the form called switchboard.

    6. Above, select theAction Save.7. In the Arguments pane, set the Object Type to Query and the Object Name to PatronShow History.

    8. Save and close the macro.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    17/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 17 of 48

    Create the Combo Box

    1. Click on the Forms tab and open the form Switchboard in design view.2. Make sure that the Control Wizards icon on the toolbar is active.3. From the Toolbox, click the Combobox button and then click the form.4. Select I want the combo box to lookup the values in a table or query then clickNEXT.

    5. Select the table Customer Info then clickNEXT.6. Place the fields: Client_ID, First_Name, Last_Name then NEXT.7. Adjust the column widths if necessary and then clickNEXT.8. Select the option: Remember the value for later use and clickNEXT.9. Label the combo box: Attendance History and clickFINISH.

    Assign the Macro to the Drop Down List

    1. Right mouse click the combo box (on the right side) and select Properties from the list.2. Click on the Event tab and then on the On Change line.3. Click the down arrow and select the macro: Macro - Show History

    4. 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.)

    5. Save the form and go into Form View.6. 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.7. Close the query.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    18/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 18 of 48

    MACRO 4: DONATION HISTORYThis Macro is almost exactly the same as macro number 3 except it shows the selected patronsDonation History rather than their Attendance History. The macro will also be assigned to theDonation History drop down menu on the switchboard and is made up of three macro actions. Whena 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. Click on the Macros tab.2. Click the macro My Macros and then click the DESIGN button.3. Place the cursor two rows below the previous macro.

    4. Name the macro DonorHistory.5. Select OpenQuery in theAction column.6. Below OpenQuery, select ApplyFilter as the next action.7. Below ApplyFilter, select Save as the last action for this macro.

    Setting Arguments for the Actions

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

    4. Above, select theAction ApplyFilter

    5. 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 theclient chosen from the drop down menu (called Donation history) on the form calledswitchboard.

    6. Above, select theAction 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.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    19/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 19 of 48

    Create the Combo Box

    1. Click on the Forms tab and open the form Switchboard in design view.2. Verify that the Control Wizards icon on the toolbar is active.3. From the Toolbox, click the Combobox button and then click the form.4. Select I want the combo box to lookup the values in a table or query then clickNEXT.5. Select the table Customer Info then clickNEXT.

    6. Place the fields: Client_ID, First_Name, Last_Name then NEXT.7. Adjust the column widths if necessary and then clickNEXT.8. Select the option: Remember the value for later use and clickNEXT.9. Label the combo box: Donation History and clickFINISH.

    Assign the Macro to the Drop Down List

    6. Right mouse click the combo box (on the right side) and select Properties from the list.7. Click on the Event tab and then on the On Change line.8. Click the down arrow and select the macro: Macro - Donor History9. 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.)10. Save the form and go into Form View.11. 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.12. Close the query.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    20/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 20 of 48

    MACRO 5: CONDITION COLUMN

    The Condition column allows for the creation of If-Then-Else conditions that control under whatcircumstances 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 codeplaced in the action column of the same row as the condition will only be executed if the conditionis 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 thetotal cost. The SetValue action is used in this macro to place the results of our calculation into theTotal field. This is different then simply placing a calculation in a form. Calculations are displayonly, they do not write to the table, but the SetValue action does place data in the actual table.

    1. Click on the Macros tab.2. Click the macro My Macros and then click the DESIGN button.3. Click the Condition icon to make the Condition column visible.

    4. Skip a row from the bottom of the last macro and name for your macro: QuantityDiscount

    5. Click in the Condition column and type the following equation: [No_of_Tickets]>66. Click in the Action column and select the SetValue action.

    7. Click the row below the pervious condition and type the equation: [No_of_Tickets]

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    21/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 21 of 48

    Setting Action Arguments

    1. Click on the top SetValue action.

    2. 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.)

    3. 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 thenumber of tickets purchased is 6 or over)

    4. Click on the second SetValue action.

    5. 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.)

    6. 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 numberof tickets purchased is less than 6.)

    7. 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 PurchasedSubform is the form that contains the fields that are actually typed in. Therefore, we need to assignour 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 eventto both fields.

    1. Click on the Forms tab and then open Tickets Purchased Subform in Design View.2. Right mouse click the text box control Ticket_Price and select Properties.3. In the Properties window, click the Event tab and then click on the On Lost Focus line.

    4. Click the down arrow and select the macro: My Macros.QuantityDiscount.5. Leave the Properties window open and click, click the text box control: No_of_Tickets.6. On the On Lost Focus line, select the macro: My Macros.QuantityDiscount.7. Go to Form View.8. Change the number of tickets purchased or ticket price to test the macro.9. Save and close the form.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    22/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 22 of 48

    Condition Example 2

    To a point, this macro very similar to Condition Example 1 except that it gives a 10% discount basedon whether or not the patron has made a donation, not on the quantity of tickets purchased. This macrois also more complicated because it must look into a subform that is a different subform then where thecalculation 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. Click on the Macros tab.2. Click the macro My Macros and then click the DESIGN button.

    3. If necessary, click the Condition icon to make the Condition column visible.4. Skip a row from the bottom of the last macro and name for your macro: DonationDiscount5. 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 whichwould 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 DonorInfo Subform which exists in the form called mainform is greater than 0, then execute the action to

    the left

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

    This is the name ofthe field we arebasing our conditionon.

    This is the nameof the form,containing thefield we arebasing ourcondition on.

    This is the name of themainform, containing thesumform, containing thefield we are basing ourcondition on.

    This is the type ofobject we areaccessing.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    23/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 23 of 48

    Setting the Arguments

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

    3. In the action pane, select the ISNULL action then click in the arguments pane.4. Type theItem andExpression code shown below.

    5. In the action pane, =0 action then click in the arguments pane.

    6. Type theItem andExpression code shown below.

    7. 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 assignour 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 eventto both fields.

    1. Click on the Forms tab and then open Tickets Purchased Subform in Design View.2. Right mouse click the text box control Ticket_Price and select Properties.3. In the Properties window, click the Event tab and then click on the On Lost Focus line.4. Click the down arrow and select the macro: My Macros.DonationDiscount.5. Leave the Properties window open and click, click the text box control: No_of_Tickets.6. On the On Lost Focus line, select the macro: My Macros.DonationDiscount.

    7. Save and close the form.8. Open Mainform in formview.8. 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 theDonation Info Subform to a new record, Access will not see any donations.

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

    Item: [Forms]![Mainform]![Tickets Purchased Subform]![Total]

    Expression: [Ticket_Price]*[No_of_Tickets]

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

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    24/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 24 of 48

    MACRO 6: USING MESSAGE BOXES

    You can use the MSGBOX action to send messages to the user. When combined with the conditioncolumn, this can be an effective method of ensuring that the user enters data as desired. In thisexample, 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. Click on the Macros tab.2. Click the macro My Macros and then click the DESIGN button.3. If necessary, click the Condition icon to make the Condition column visible.

    4. Skip a row from the bottom of the last macro and name for your macro: NoChecksMSG5. Create the macro as shown below.6. Save and close the macro.

    Creating a Drop Down List to go to a Record - MainformWe will use the wizards to create a drop down list that the user can pick the name of the person whoserecord they wish to view. Access will then go to that record. The code for the drop down list is storedwithin the drop down list as Visual Basic code.

    1. Go into Design View of Mainform.2. If the Toolbox is not active, press the Toolbox icon to make it visible:3. Make sure that the Control Wizards button on the Toolbox is depressed.

    4. Click on the Combo Box button from the Toolbar:5. Click in the indented light blue area at the top of the form.

    (The combo box wizard starts.)6. Select the option: Find a record on my form based on the value I selected in my combo box.7. Click on NEXT.8. Double click: Client_ID, First_Name, and Last_Name.

    9. Click on NEXT and then NEXT again to use the default settings.10. Type Select a Name as the label and click on FINISH.11. Save the form: File - Save and go into form view: View - Form View12. Test the drop down list by clicking it. It should have brought you to the record you selected.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    25/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 25 of 48

    Assign the Macro to the Form

    1. Click on the Forms tab and then open Mainform in Design View.2. Right mouse click the Select a Record combo box field and select Properties.3. In the Properties window, click the Event tab

    and then click on the On Change line.4. Click the down arrow and select the macro:

    My Macros.NoChecksMSG.5. Save the form then go to form view.6. Click the down arrow for Select a Record and

    select Tonya Harding. You should get the messagebox shown.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    26/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 26 of 48

    MACRO 7: OPTION BOXES

    An option box is an interface that allows the user to pick from a list ofchoices. The option box shown to the right was created from an unboundform called Labels - Complete. When the user selects an option and clicks

    Print Mailing Labels, a macro runs which prints the appropriate labelsfrom 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 calledDonation Status. Donation Status was based off two linked tables (Customer Info & DonorInfo) . The query is shown below.

    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 theStatus column. These two choices will be used as a where condition in the macro.

    Creating the Option Group

    1. Click on the Forms tab and click the New button.2. Select Design View and then clickOK.3. Resize the form to about 3 by 3.4. On the Toolbox, verify that the Control Wizards are active.

    5. From the Toolbox, click on the Option Group icon:6. Click on your form.7. In the pop-up window, type the options as shown:8. Click on NEXT.9. Select either option concerning the default choice.10. Click on NEXT.11. Leave the values set to 1, 2, & 3 and click NEXT.12. Select Option Buttons as the type of control and any

    style you desire then click NEXT.

    The query uses an outer joint which specifiesthat all records from Customer Info should beshown but matches from Donor Info. Anyperson who hasnt make a donation will have ablank in their Amount_Donated column.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    27/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 27 of 48

    13. For the caption of the frame, type: What Labels Do You Wish To Print? and clickFINISH.

    14. 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 oneof the items can be selected at a time. When one is selected, its assigned value is temporarily stored bythe Option Group. In our case the three possible values are 1, 2, & 3. The condition column of ourmacro 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 adescriptive name prior to creating the macro.

    1. Be in form design view of the Labels form.2. Right mouse click the Option Group frame and select Properties.

    (The title bar of the properties window should say: Option Group: frame number)3. Click on the All tab and scroll up to the Name line.

    4. Type: LabelChoice in the name column.5. Close the properties window and then save and close the form.

    Creating the Macro

    1. Click on the Macros tab and then open My Macros inDesign View2. Make sure both the Condition and Name columns are visible.3. Skipping a row, place the cursor in the names column below the last macro.4. Create the macro shown on the next page.

    Condition Action Description

    CLOSE This action is used to close the Labels form after the usermakes a selection and clicks OK.

    [LabelChoice]=1 OpenReport This Open Report line will print labels for all patrons if theuser selects option 1 (Print All Labels in the option groupcalled LabelChoice.

    [LabelChoice]=2 OpenReport This Open Report line will print labels just for Donators ifthe user selects option 2 (Print All Labels in the option groupcalled LabelChoice.

    [LabelChoice]=3 OpenReport This Open Report line will print labels for non donatingpatrons if the user selects option 3 (Print All Labels in theoption group called LabelChoice.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    28/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 28 of 48

    5. Save and close My Macros.

    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 anCancel 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 Button1. 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.

    Note that the where condition tells Access tolook in the Status column of the query uponwhich the Customer Labels report is based. Itthen uses either Donated or Not Donated asa criteria for deciding which labels to print.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    29/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 29 of 48

    KEYSTROKE MACROS

    Keystroke macros allow you execute menu commands by pressing keyboard shortcuts. Normally, theRunCommand action is used to create keystroke macros. The RUNCOMMAND action executesmenu 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 Code equivalent Examples

    Control ^ Control A would be: ^A

    Shift + Shift R would be: +R

    Any Function key Place { } around the key. Control, Shift, F7 would be: ^+{F7}

    Insert {INSERT}

    Delete {DELETE}

    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. In the database window, click on the Macros tab.2. Click on the New button to start a new macro.3. If necessary, press the Macro Names button to make the Macro Name column appear.4. 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: Run

    Command: FreezeColumn

    Command: UnfreezeAllColumns

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    30/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 30 of 48

    Save the Macro

    The macro must be named Autokeys for the keystroke macros to function.1. Click on Save.

    2. Name the macro: Autokeys3. Close the macro

    Testing the Macro Freeze & Unfreeze Columns Macro

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

    The column should have moved to the extreme left. If you use the scroll bars, the other columns willmove 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. Click on the Queries tab and open the query Totals in Design View.2. To run the query, press: CONTROL + R

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    31/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 31 of 48

    MACRO 7: SELF EXECUTING MACROS

    If you name a macro object Autoexec, the macro will run automatically when the database isopened. Note that Autoexec must be the name of the entire macro object (i.e. what you see if youclick on the Macros tab of the database window), not what you specify in theMacro 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. Click on the Macros tab and then click the NEW button.2. Create the macro as shown bellow:

    3. From the menu, click on: FILE - SAVE4. Name the Macro Object: AUTOEXEC

    Run the Autoexec Macro

    1. Close the database and reopen it. The splash screen should have opened automatically.

    2. Click OKto 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 databasefile.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    32/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 32 of 48

    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. Open the form Switchboard inDesign View.

    2. Right click the box in the forms upper left corner to set the properties for theentire form.

    3. Select Properties from the pop-up list.4. Click on the Format tab.5. Make the settings shown below:

    6. Save the form and go into Form View to see the changes.

    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.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    33/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 33 of 48

    SETTING STARTUP PARAMETERSHere we can have the switchboard load automatically when the file containing it is opened, hide menuitems, toolbars, and the database window, thus preventing users from going places we may not wishthem to be.

    1. From the menu, click on: TOOLS - START UP2. Click the Advanced button to see all options.3. Set the Display Form to Switchboard.4. 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 harmingyour database.

    5. Click on OKand close the database.6. 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 thekeyboard while opening the database.

    Removing Startup Limitations

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

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    34/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 34 of 48

    HIDING DATABASE OBJECTS

    If you need to display the database window but would like to hide certain database objects such assaved queries, tables, forms, reports, or macros, you can. This is a wise precaution if you have severalpeople working on a database and you do not wish them to delete one of your objects. This is a twostep 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.)

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    35/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 35 of 48

    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 aquery called Totals. Pulling the calculation from a query was necessarybecause of DSUM limitations.

    Number of Visits: This counts the number of shows the patron has seen. It also employees theDLOOKUP function to pull the answer from the Totals query.

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

    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

    The Query Used by Dlookup

    Both of the Dlookups are based off a query called Totals which was based off the table TicketsPurchased. Design view of the query is shown below. Note that for our Dlookup to function, we hadto include the primary key (Client_ID) in the query. This is because we need to see the total spend for aparticular 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])

    Number of

    Tickets:No_of_Tickets

    Visit Count:

    Client_ID

    Total Group by Expression Sum Count

    Sort

    Show

    Criteria

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    36/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 36 of 48

    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:

    In English, this statement would read something like this: Sum up the Amount_Donated field in the Donor Info table but only forrecords where the Client_ID in the Donor Infotable is equal to this forms currently displayed Client_ID.

    1. While in form Design View, click on the Text Control icon on the Toolbox:2. Click in the blue area at the bottom of the form.3. Click inside of the box on the right (text control), type the equation above and then press ENTER.4. Click inside of the box on the left (label control) and type: Total Amount Donated4. Save the form and then go to form view: Veiw - Form View5. Go to the next record to see the Total Amount Donated change.

    =DSum("[Amount_Donated]","Donor info","[Client_ID]=form.[Client_ID]")

    This is the name of

    the field to besummed.

    This is the name of

    the table that thefield to be summed

    exists in.

    This is the name of

    the field in thetable that is the

    primary key.

    This is the name of

    the field in theform that links the

    data to the table.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    37/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 37 of 48

    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:

    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 displayedin the form.This last part is the most confusing but it is necessary. Without it, Access would know which column to display but notwhich row.

    Dlookup for Number of Visits

    To get the Number of Visits, simply copy the previous Dlookup and replace [Total Spent] with [Visit Count]

    =DLookUp("[Total Spent]","Totals","[Client_ID]=form.[Client_ID]")

    This is the name ofthe field to bedisplayed.

    This is the name ofthe query containingthe field to bedisplayed..

    This is the name ofthe field in the querythat links the queryto the form. It is the

    primary field.

    This is the name of the field inthe form that links to the queryand tells Access for which clientshould it display information.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    38/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 38 of 48

    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 thecalculated fields, this is undesirable.

    1. Go into Form Design View: View - Design View2. Right mouse click on one of the calculations and select Properties from the drop down list.3. Click on the Other tab and set Tab Stop to NO.4. Do the same for the other calculated fields and the macros.

    5. Test the form again in Form View then save the form.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    39/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 39 of 48

    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. Likebuilt-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 usuallysimpler 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.0775tax rate.

    1. Click on the Modules tab and then NEW.2. Type the function shown below:

    Function OCTax(X)

    OCTax = X * 0.0775

    End Function

    All functionsmust begin withthe wordFunction andend with thewords End

    Function.

    You must give your function a unique name followed by anopening and closing round brace. Place all variables within thebraces. When functions employ multiple variables, separate thevariables with commas. i.e. OCTax(x,y,z)

    Here is where you definewhat the function does andwhat to do with thevariable.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    40/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 40 of 48

    ?FtoC(212)

    Testing Functions

    The function created above can be used in a form, query, or report in the same manner any function isused. However, Access provides a method of testing it from within the module it was created.

    1. You are still in the module which you created the function above.2. From the toolbar, click on the Debug Window icon:

    3. 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 aquestion mark.

    Access should have returned 7.75.4. Close the Debug Window.5. 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)/9The formula is not too lengthy, but a custom function would make it even easier to use.

    1. You are still in the Function module .2. Click below your previous function and type whats shown below. Remember to press enter

    after each line.

    3. Open the Debug Window and type the following to test the function:

    Access should have returned 100.4. Close the debug window and save the function.

    ?OCTax 100

    ' 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

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    41/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 41 of 48

    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 theanswer is false, Excel executes any code after the END IF line but before the END FUNCTIONline.

    IF statements can be nested by using the ELSE IF option.

    Operators allowed: > >= < = 50 Then

    Total = C * Q * 0.85Else Total = C * Q

    End IfEnd 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 andAccess should return: 850)

    3. 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 applyand Access returns: 100)

    4. Close the Debug Window and save the module.

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    42/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 42 of 48

    Example 4: Nested If Statements

    This IF example utilizes the AND operator and the ElseIF command (one word) to provide for morethan two possible answers. The table below shows the discounts available.

    Quantity ordered Discount

    0-50 No discount

    51 to 999 15%1000 and over 25%

    1. 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 Result?Discount(1,10) 10

    ?Discount(1,100) 85

    ?Discount(1,1000) 750

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    43/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 43 of 48

    Function Example 5: Select Case

    Select Case is similar to an IF statement in that it provides for multiple outcomes; however, when thereare numerous possible outcomes, If Statements become unwieldy and Select Case a better choice.

    SYNTAX

    Function NameSelect Case Expression (What is being evaluated)

    Case ConditionAction 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 (>,=, 40 (Note use of IS when using >,

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    44/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 44 of 48

    2. Open the Debug Window and try the following:

    ?Letter(98) Should return an A?Letter(60) Should return a D?Letter(75) Should return a C?Letter(80) Should return a B?Letter(50) Should return an F?Letter(101) Should return Pending

    3. Close the debug window and save the module.

    Function letter(score)

    Select Case score

    Case 60 To 69.999999letter = "D"

    Case 70 To 79.999999letter = "C"

    Case 80 To 89.999999letter = "B"

    Case 90 To 100letter = "A"

    Case Is < 60letter = "F"

    Case Elseletter = "Pending"

    End Select

    End Function

    Use Case is when usingComparison Operators.

    Case Else (optional)covers anything notfalling under any

    other cases (101 or blanksfor example).

    Note that text must beenclosed in quotes.

    Customf

    unctionsmustendwiththeEndFunctioncom

    mand.

    TheSelectCasestatementmustendwiththeEndSelectSta

    tement

    Note that the name of thevariable is Score and it isused again in Select Case

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    45/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 45 of 48

    3.2

    1

    6

    73 1 is theremainder

    Function Example 6: Working With Dates

    In this example, we will take an employees Hire Date and then express in years and months how longthey 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 DebugWindow.

    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 yourchoice (days, months, years, etc.)

    Units of Measure Available

    Unit of Measure Description Unit of Measure Description

    yyyy In Years n In Minutes

    d In Days s In Seconds

    w In Weeks q In Quarters

    y Numeric Day of Year ww The Week Number

    h In Hours m In Months

    To test it in the Debug Window, type: ?DateDiff(yyyy,#1/1/70#,Now())

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

    Int(number) or \This function returns only whole numbers (what is to the left of the decimal) and does not round up ordown.

    For example, ?Int(44.99) would return just 44.For example, ?Int(7/3) would return just 2 (Three goes into seven two times.)For example, ?7\3 would also return just 2 (Three goes into seven two times.)

    MODThis operator divides one number by another and returns only the

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

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    46/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 46 of 48

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

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

    ? Tenure(#12/1/98#,#1/1/99#) Access returns 8.33E-02 Years? Tenure(#1/1/60#,#1/1/99#) Access returns 38.9 Years

    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:

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

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

    Note that Access returns: 1 Years

    This is incorrect, there is not a full year between December 1, 1998 and January 1, 1999. The problemoccurs 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 theyears.

    4. Alter the function as shown:

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

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

    This is more accurate but we do not wish to see anything to the left of the decimal being that we willbe expressing the remainder in months. Therefore, we will use the Int() function to display only wholenumbers.

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

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

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    47/48

    Information Resources University of Southern California

    Access_Macors.Doc September 25, 1998 Page 47 of 48

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

    ? Tenure(#12/1/98#,#1/1/99#) Access returns 0 Years? Tenure(#1/1/60#,#1/1/99#) Access returns 38 Years

    ? Mon(#1/1/60#,#1/1/99#) Access returns 0 Months as in 38 years, 0 months?Mon(#1/15/98#,#5/1/98#) Access returns 4 Months as in 0 years, 4 months

    ?Mon(#12/30/98#,#1/1/99#) Access returns 1 Months as in 0 years, 1 months

    6. Edit the function as shown:

    7. In the Debug Window, try the two examples shown:

    Getting Months

    We will use the MOD command to pick up the remaining months. (MOD divides two number andreturns only the remainder.

    1. Create the following function:

    2. Try the following in the Debug Window

    Note that the last example returns 1 month when really only a few days have passed. This occursbecause when using m, Access looks only at the month number when finding the difference Withmore 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 twofunctions together.

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

    End Function

    Function tenure(b, e)

    tenure = Int(DateDiff("m", b, e) / 12) & " Years, " &DateDiff("m", b, e) Mod 12 & " Months"End Function

  • 7/28/2019 BOOK 1999 Macros and SwitchBoard

    48/48

    Information Resources University of Southern California