Events and Macros

Embed Size (px)

Citation preview

  • 7/29/2019 Events and Macros

    1/43

    Events Fundamentals

    IntroductionAn event is the result of initiating an action on an object. The action could be as simple aspositioning the mouse on an object even without clicking. The action could consist of (left)

    clicking, right-clicking, dragging (with the mouse, or dragging with the mouse whileholding a key on the keyboard), double-clicking, rolling the wheel (on a mouse), typing(with the keyboard), pressing a key, scrolling (a scroll bar), etc

    Sending a Message

    When an action is performed on an object, the object must send a message to the operatingsystem (OS), letting the OS know what happened. The OS must then decide what to do,whether to respond to the message or send the message to another object. Obviously, for amessage to accomplish its purpose, it must carry some information. Because there are

    different types of objects and there are various types of actions that can be performed onthem, there are also various types of messages.

    Although events primarily have to do with computer programming, in our lessons, we willknow write code. Instead, we will use other friendly means that Microsoft Access providesto deal with events.

    To access the events of an object, display the form or report in Design View. In theProperty Sheet, click the Event tab. This would display the names of the events associatedwith whatever is selected on the form or report:

  • 7/29/2019 Events and Macros

    2/43

    The names of most events start with On , which means, "at the time this is done". Becausemost, if not all, events have to do with time, an event is said to be fired. That is, the objectfires an event at the time something happens. When an event is fired, if necessary, it gathersthe necessary message to be transmitted where appropriate.

    Again, remember that most events have to do with time (they are occurrences). In somecases, something must be done before the actual action is applied. For this reason, thenames of some events start with Before . When something must be taken care of after theaction has applied, the event that must be used to implement the desired behavior startswith After .

    Events Categories

    Introduction

    Some events are general and they are shared by most objects. For example, almost all

    objects can be clicked. Some events are based on a category objects, such as only objectsthat can receive text. Some other events are very restricted because their object needsparticular functionality.

    As mentioned already, some events are shared by almost all objects.

    Regular Click Events

    Probably the most common event fires when an object is clicked. The event is called OnClick . This event doesn't carry any information other than letting the target know that theobject has been clicked. This event doesn't identify what mouse button was used oranything else. Therefore, use this event for a normal click action.

    Another common event of Windows controls is fired when an object is double-clicked. This

    event is represented as On Dbl Click .

    Focus-Based Events

    Some controls must be clicked before being used. A user can also press Tab a few timesfrom one or other controls to move focus on a particular control. In both cases, when acontrol receives focus, it fires an event named On Got Focus :

  • 7/29/2019 Events and Macros

    3/43

    Text-based controls are controls that a user can click to type text. Those controls are thetext box and the combo box. When such a control is clicked, whether it already containstext or not, it fires an event named On Enter . Like On Got Focus , the On Enter eventindicates that the control has received focus:

    After using a control, a user can press Tab. In this case, the focus would move from thecurrent object to the next control in the tab sequence. The control that looses focus fires anevent named On Lost Focus . If the control is text-based, the control fires the On Exit event.

    Mouse Events

    The mouse and the keyboard are the most regularly used objects. In fact, some applicationscan be completely used with the mouse only. This makes this object particularly important.In Microsoft Access, the mouse is responsible for at least three events:

    If the user positions the mouse on top of a control but doesn't click, the control fires anevent named On Mouse Move . Remember that this event fires when the mouse passes overan object, whether the user is doing anything on the object or not.

  • 7/29/2019 Events and Macros

    4/43

    When the user positions the mouse on an object and presses a (mouse button), the objectfires the On Mouse Down . To make its action effective, the message of this event holds thefollowing pieces of information:

    Button : This is a natural number that specifies the button that was clicked

    Shift : This is a natural number that specifies whether the user was holding a specialkey (Ctrl, Alt, or Shift) when the mouse button was pressed X: This a decimal number (Single type) that represents the left coordinate of the

    mouse cursor with regards to the container, which can be a form header, a reportheader, a detail section, a report footer, a form footer, or any object that can hold acontrol

    Y: This is a decimal number that is the vertical coordinate of the cursor from the topborder to the current area where the mouse landed

    If a user had pressed a mouse button, when she releases the (mouse) button, the controlfires an event named On Mouse Up . The message of this event carries the same types of information as the On Mouse Down event.

    Keyboard Events

    There are various ways a user uses the keyboard. For example, a user can press a key on acontrol:

    The user can press Tab to move focus from one control to another. A user can also click atext-based control and start typing. Either way when the user presses a key, the control thathas focus fires an On Key Down event. The message of this event carries two pieces of information:

    KeyCode : This is a natural number that represents the integral (ASCII) value of the

    key that was pressed Shift : This is a natural number that specifies whether the user was holding a specialkey (Ctrl, Alt, or Shift) when the actual key pressed

    After pressing the key, when the user releases or depresses it, the control fires an eventnamed On Key Up . The message of this event carries the same types of information as theOn Key Down event.

  • 7/29/2019 Events and Macros

    5/43

    When the user presses a key, if you are interested only on the key that was pressed and noton any combination of keys, use the On Key Press event. The message of this event carriesonly one piece of information, which is the ASCII code of the key.

    Control-Based Events

    Form Events

    To use a form, the user muse open it, either from the Navigation Pane or from anotherobject you provide them. When the form is being opened, it fires an event named On Open .

    As the form is opening, it must occupy memory. As this is happening, the form fires anevent named On Load .

    To make itself known to the operating system and to other applications on the samecomputer, the form must draw its border. When this is being done, the form fires the OnResize event.

  • 7/29/2019 Events and Macros

    6/43

    After the form has had the size it needs, the operating system must activate it. If the form isbeing opened as the first object, it gets positioned in the interface body of Microsoft Access.If the form was already opened and there are other forms (or reports and/or tables), if theuser wants to bring it to the front, she must click either its title bar or an area of the form.When this is done, the operating system must paint its title bar with a bright color. Either

    case, when a form comes to the front of other windows, it fires an event named OnActivate .

    Once a form has been loaded is currently the active form, the user can use it. After usingthe form the user can close (the user can either use the system close button or you mustprovide other means of closing the form). As this starts, the form must lose focus. If theform was the only object opened in Microsoft Access, the body of the application isemptied. If there are other objects, the form would be closed and another object wouldbecome active. As this is done, the form fires the On Deactivate event.

    When the form is being closed, it must be removed from memory to release the resources itwas using (so that those resources can be used by other applications). While this is beingdone, the form fires the On Unload event.

    Once the form has been removed from memory, it (the form) fires an event called On Close.

    Text Box Events

    As you know already, to use a text box or a combo box, the user can click the control andstart typing. If the control already contained some text, the user can edit it using the Space,the Backspace, the Delete, and the other letter keys. When the text is being entered oredited, the control fires the On Change event.

    Combo Box Events

    A combo box is a control that holds a list of items. To use it, the user can click the arrow of the control to display the list and select an item. Some versions of the combo box allow auser to click the text box part of the control and start typing. The control would then try tofind an item that matches what the user is typing or has typed. Sometimes, after the user hasfinished typing and press Enter or Tab to move focus, Microsoft Access (the databaseengine) may not find a match and would display an error. This means that the text the usertyped did not match any of the items of the combo box. In this case, the control would firean event named On Not List . You can use this event to friendly display a message to the

    user and to take an appropriate action.Web Browser Events

    The web browser has many events appropriate for its functionality:

  • 7/29/2019 Events and Macros

    7/43

    We already know that you can submit the path of a file or a URL to it. When a file path or aURL is given to a web browser, before it processes it, the control fires an event named OnBefore Navigate . If there is no problem in this event, the control shows the file or the webpage. When the control has finished displaying the document, the web browser fires the OnDocument Complete event. If there is a change on the document, the control fires an OnProgress Change event.

    When a web browser has receives a file path or a URL, it makes an attempt to show thatfile or the web page. If it encounters a problem, it fires an On Navigation Error event.

    At any time, and if you allow it, the user can change the document the control is displaying.When a new document must be displayed, the control fires an On Updated event.

    Fields and Record-Based Events

    Fields-Related Events

    Because Microsoft Access is a database application, it provides some event that are

    particular to records and their fields on a form or report.

    To create a new record, the user must move to an empty record on a form. The user canclick a control such as a text box and start typing. When this happens, the form fires anevent named Before Insert .

    Records-Related Events

  • 7/29/2019 Events and Macros

    8/43

    If a record exists already, the user can open or access, click one of its fields and start typingor editing. When at least one value in the record has been changed, the form fires the OnDirty event.

    After a record has been changed and submitted to the database, the form would fire an

    event named Before Update .When a new record has been created, it must be submited to the database. When this isdone, the form fires an After Insert event. After an existing record has been modified, thechange must be submitted to the database. In this case, the form fires the After Update event.

    If a table contains more than one record, after the user has opened its corresponding form,the user can navigate from one record to another. When the user moves from record torecord, the form fires an event named On Current .

    Record-Deletion Events

    We know that, to delete a record, a user can click the record and press Delete. This woulddisplay a warning message. Before that message comes up, the form fires the Before DelConfirm event. After the user has clicked one of the buttons on the message box, the formfires an After Del Confirm event.

    If the user decides to delete a record, before the record is actually deleted, the form fired anOn Delete event.

    Macros Fundamentals

    Introduction

    A macro is an (automatic) action that must be performed on an object of a database. Anexample would consist of saving something when a key is pressed on the keyboard.Another example would consist of printing something when an object is clicked. MicrosoftAccess provides an easy and visual mechanism to create and manage macros.

    Macros in Microsoft Access have nothing to do with macros in other MicrosoftOffice applications. In fact, it should be fair to state that they are completelydifferent. For example, macros in Microsoft Excel and Microsoft Word directly

    lead to actual Visual Basic programming. Macros in Microsoft Access don't writereal (VBA) code: they are actions you create and the database engine executesthem behind the scenes at the right time. If you want, you can convert MicrosoftAccess to VBA but then, they become code and not real macros anymore.

    The Macros Windows

    To create a macro in Microsoft Access, you can use an intuitive dialog box that allows youto select the action to be performed and the options the action needs. In reality, when you

  • 7/29/2019 Events and Macros

    9/43

    create a macro, Microsoft Access creates a type of script that contains names, expressions,and operations for the action, sparing the details. Still, if you know what is necessary forthe macro, you can "manually" create it.

    To create a macro, on the Ribbon, click Create. In the Marros & Code section, click the

    Macro button . Two windows would display and they are separated by a split bar:

    To give more room to one of the window, position the mouse between them, click and dragin the desired direction.

    The left window presents a tab or a title bar labeled Macro1. By default, that windowdisplays a combo box.

    The right window displays buttons with +. This means that they are nodes. To expand anode, click its + button. When you do, the node would display its items.

    The Program Flow node allows you to create a condition:

  • 7/29/2019 Events and Macros

    10/43

    The Actions node holds most of the actions you will create for your macros. If if expand it,you will see that it organizes its actions in categories, each represented by a node:

    To access the actual action you want, expand its node. This would display the actions inthat category:

  • 7/29/2019 Events and Macros

    11/43

    Creating a Macro

    To create a macro from the left window, click the arrow of the combo box to display theavilable actions:

  • 7/29/2019 Events and Macros

    12/43

    If you see the action you want, you can click it. The left window would display the objects(controls) needed for the options of the action you selected. The objects in that windowdepend on the action you selected.

  • 7/29/2019 Events and Macros

    13/43

    To create an action using the right window, expand the node(s). Many names of actions areexplicit or can be infered logically. Otherwise, you can click an action. The bottom sectionwould show a description of the action:

    If you see the action you want, click and drag it to the left window.

    In both cases, if you selected an action you don't want anymore, you can click the Deletebutton .

    The Actions of a Macro

    To actions its action(s), a macro may need some additional information. This information isreferred to as the argument of a macro. The argument can be made of one or more values.The argument(s) depend(s) on the (type of) macro. Some macros take 0 argument whilesome others take 1, 2 or more arguments.

    If you select an action that doesn't take an argument, its name would display in the topsection and nothing else:

    If you select an action that needs one argument, its name would display followed by a boxfor the corresponding argument:

  • 7/29/2019 Events and Macros

    14/43

    If you select an action that needs more than one argument, it would appear, followed by abox for each argument:

    An argument is said to be required if it must always be provided, otherwise the actioncannot be performed. If you select a macro that takes a required argument, an empty textfield would appear and you must type the necessary values:

    An argument is referred to as optional if it can be omitted, in which case the macro woulduse a default value. Normally, when you are creating a macro, its corresponding box(es)would display the default value(s). If you select an action that takes one argument and theargument is optional, its corresponding arguments fields would display the default value:

  • 7/29/2019 Events and Macros

    15/43

    When an action takes more than one argument, some arguments can be required whilesome others are optional. The person (Microsoft) who created the macro also decided whatarguments would be required and what arguments would be optional. The macro creatoralso decided about the order of the arguments, which one(s) would appear first and whichone(s) would appear last.

    If you select a macro that takes more than one argument that are a combination of requiredand optional arguments, for each argument that is optional, the default value would appearin its placeholder of its corresponding boxes.

    Using a Macro

    After creating a macro, you can use it. This is usually done by assigning it to an event of aform, a report or a control. For example, you can first create a button that would be used toaccess a section of a page break. To assign a macro to an object, access the Property Sheetfor the object and access the Event or the All tab. You can type the name of the macro inthe event's field:

  • 7/29/2019 Events and Macros

    16/43

    Instead of first creating a macro before assigning it to command button, as anothertechnique, in the Design View of the form, you can right-click the object and click BuildEvents. In the Choose Builder dialog box, you can click Macro Builder and click OK. The

    new macro would be automatically assigned to the control.In Lesson 15, we saw how to create a page break . To implement it in the Action combo box,select GoToPage. In the Page Number box, enter the desired number of the section, andclose the macro. You would be asked to save it.

    Practical Learning: Using a Macro

    1. Start Microsoft Access2. Open the Bethesda Car Rental1 database from Lesson 153. In the Navigation Pane, under Forms, right-click Customers3 and click Design

    View4. On the Ribbon, click Create5. In the Macros & Code section, click Macro6. In the Macro1 window, click the arrow of the combo box and select GoToPage

    http://www.functionx.com/access/Lesson15.htm#Page%20Breakshttp://www.functionx.com/access/Lesson15.htm#Page%20Breakshttp://www.functionx.com/access/Lesson15.htm#Page%20Breakshttp://www.functionx.com/access/Lesson15.htm#Page%20Breaks
  • 7/29/2019 Events and Macros

    17/43

    7. In the Page Number text box, type 1

    8. Click the Close button to close the macro window9. When asked whether you want to save, click Yes10. Set the name to mcrPage1 and click OK11. To create another macro, in the bottom section of the form, right-click the Personal

    Information button and click Build Events...12. In the Choose Builder dialog box, click Macro Builder

    13. Click OK14. In the Action combo box, select GoToPage15. In the Page Number, type 2 16. Close the macro window17. When asked whether you want to save, click Yes18. On the Ribbon, click Create19. In the Macros & Code section, click Macro20. In the right window, click the + button of Actions to expand it21. Double-click Database Objects to expand it22. Drag GoToPage from the right to the left window23. In the Page Number, type 324. Close the macro window25. When asked whether you want to save, click Yes

  • 7/29/2019 Events and Macros

    18/43

    26. Set the name to mcrPage3 and press Enter27. In the bottom section of the form, double-click the Contact button28. On the Property Sheet, click Event29. Click On Click, then click the arrow of its combo box and select mcrPage130. In the bottom section of the form, click Comments

    31. In the Event tab of the Property Sheet, click On Click, then click the arrow of itscombo box and select mcrPage3

    32. Close the form33. When asked whether you want to save the form, click Yes34. In the Navigation Page, under Forms, double-click Customers3 to open it in Form

    View

  • 7/29/2019 Events and Macros

    19/43

    35. Click the Personal Information button to test the functionality

    36. Click the Comments button

    37. Close the form38. Close Microsoft Office Access 2010

  • 7/29/2019 Events and Macros

    20/43

    Introduction to Built-In Functions

    Character RetrievalIn order to create expressions that complete a database as we saw in previous lessons, youcan use various functions available from Microsoft Access. These are referred to as built-in

    functions.

    The Chr() function is used to retrieve a character based on an ASCII character numberpassed to the function. It could be used to convert a number to a character. It could also beused to break a line in a long expression. The syntax of this function is:

    Chr( Number )

    Based on the table of ASCII characters, a call as Chr(65) would produce the letter A. Notall ASCII characters produce a known letter. For example, when Chr(10) is used in a string,it creates a "new line".

    The Input Box

    Although most of the user's data entry will be performed on fields positioned on a form,you can display a special form to the user and expect a value. This form (actually a dialogbox) is called an input box. To support this, Microsoft Access provides a function calledInputBox . The basic syntax of the InputBox() function is:

    InputBox( prompt )

    To use an input box, you can access the event of a control in the Property Sheet and type

    the code as we will see. As an alternative, after accessing the event of the control, click itsellipsis button, which would display the Expression Builder. In the left list, expand theFunctions node and expand Built-In Functions. In the middle list, click InputBox and noticeits syntx in the bottom part:

  • 7/29/2019 Events and Macros

    21/43

    The required argument passed to the InputBox() function is a message that would bedisplayed to the user. When the input box comes up, a form with a message and a text boxwould display to the user.

    To display an input box to the user, place a control, such as a Button, to a form. Then,access the Property Sheet for the control. In the Property Sheet, use an appropriate field,such as On Click from the Events tab, and assign the function to the field. An examplewould be:

    =InputBox("Enter the Radius of the Circle")

    When the user clicks the button, an input box would display:

  • 7/29/2019 Events and Macros

    22/43

    When an input box comes up, it does not display a caption in the title bar. If you want, youcan display a title of your choice. To do this, pass a second argument to the InputBox() function. Here is an example:

    =InputBox("Enter the Radius of the Circle" ,"Geometric Figures" )

    This would produce:

    When an input box comes up and you present a request, the user may not know what typeof value you are expecting. To guide the user, you can provide a sample or default value.This value would display in the text box and it would be selected so the user can type toreplace it.

    To provide a default value to the input box, you can pass a third argument to theInputBox() function. Here is an example:

    =InputBox("Enter the Radius of the Circle","Geometric Figures" ,10.5 )

    When the input box is called from this function, it would display as follows:

  • 7/29/2019 Events and Macros

    23/43

    The Message Box

    Introduction

    A message box is a Windows (operating system)-created form used to display someinformation to the user. As opposed to a regular form, the user cannot type anything on thebox. There are usually two ways you can use a message box: you can simply display amessage to, or request an answer from, the user.

    Practical Learning: Introducing the Message Box

    1. Start Microsoft Access2. To create a new database, in the File Name, replace the contents of the text box with

    Exercise1 3. Click Create4. Close the default table without saving it

    Creating a Message Box

    To create a message box, you have various options.

    To create a message box using a macro, after starting a new macro:

    In the left window, click the arrow of the combo box and select MessageBox In the right window, expand Actions and expand User Interface Commands. Drag

    MessageBox to the left window

  • 7/29/2019 Events and Macros

    24/43

    To manually create a message box, use a function called MsgBox . If you only want todisplay a message, the syntax you would use is:

    MsgBox( Message To Display )

    This function takes only one required argument, the message to display. If you are creatingthe message box using a macr, type the message in the Message text box. If you are

    manually typing the code, pass it to the parentheses of the function. The message can bepassed between double-quotes.

    To display a message to the user, place a command-based control, such as a Button, to aform. Then, access the Property Sheet for the control. In the Events tab of the Properties,click On Click and assign the function to the field. An example would be:

    =MsgBox("Remember to submit your time sheet")

    When the user clicks the button, a message box would come up:

  • 7/29/2019 Events and Macros

    25/43

    If you want to display the message box on various lines, edit the string to include a call toChr(10) . Here is an example:

    MsgBox("Remember to submit your time sheet" + Chr(10)"Only time sheets received on time will be honored", )

    This would produce:

    The message to display can also come from another control on the form. For example, youcan retrieve the value of a control and pass it as argument to the MsgBox() function.

    The simplest message box displays only a message to the user, with one button marked OK.If you want, you can display more than one button on the message box. To support this,you can bed the following syntax of the MsgBox() function:

    MsgBox( Message to display , Options )

    The second argument allows you to specify the button(s) to display. To do this, pass aconstant integer as argument from the following table:

    Value Buttons

    0

    12

    3

    4

    5

  • 7/29/2019 Events and Macros

    26/43

    Here is an example:

    =MsgBox("Do you want to submit your time sheet?" ,4 )

    This would produce:

    If you provide a value other than those in the list, the message box would display only theOK button.

    Besides displaying a button, the second argument is also used to display an icon. To get anicon, you add one of the following values:

    Value Icon Suited when

    16 Warning the user of an action performed onthe database

    32 Asking a question that expects a Yes or No,or a Yes, No, or Cancel answer

    48

    A critical situation or error has occurred.This icon is appropriate when informing theuser of a termination or deniability of anaction

    64 Informing the user of a non-critical situation

    To use one of these icons, add (a simple addition) its value to that of the desired button orcombination of buttons from the previous table. Here is an example created with

    =MsgBox("Do you want to submit your time sheet?", 4 + 32 )

  • 7/29/2019 Events and Macros

    27/43

    This is the same as:

    =MsgBox("Do you want to submit your time sheet?", 4 + 32 )

    This would produce:

    When the buttons of a message box display, if the message box has more than one button,one of them has a thick border. This button is referred to as the default button. If the userpresses Enter, such a button would be activated. Besides selecting the buttons anddisplaying an icon, the second argument can also be used to specify what button wouldhave focus, that is, which one would have a thick border and would be applied if the user

    presses Enter. The default button is specified using one of the following values:

    Value If the message box has more than

    one button, the default buttonwould be

    0 The first button

    256 The second button

    512 The third button

    768 The fourth button

    To specify this option, add the number to the second argument.

    To specify this option, add the number to the second argument.

    When a message box comes up, it displays a title as Microsoft Office Access. If you want,you can specify your own title. To support this, you can pass a third argument to theMsgBox() function. This third argument is referred to as the caption. The syntax to use is:

  • 7/29/2019 Events and Macros

    28/43

    MsgBox( Message to display , Options , Caption )

    Pass the third argument as a string, for example in double-quotes. Here is an example:

    =MsgBox("Do you want to submit your time sheet?",4 + 64,

    "Georgetown Cleaning Services" )

    This would produce:

    Because MsgBox is a function, you can retrieve the value it returns and use it as you see fit.The value this function returns corresponds to the button the user clicked on the messagebox. Depending on the buttons the message box is displaying, after the user has clicked, theMsgBox() function can return one of the following values:

    If the button(s) displayed was(were) And if the

    user clicked The MsgBox()

    function returned

    1

    1

    2

    3

    4

    5

    6

    7

    2

    6

    7

    4

    2

  • 7/29/2019 Events and Macros

    29/43

    Practical Learning: Creating Message Boxes

    The purpose of this exercise is to let you monitor the sequence of events of a form (whiatevnt comes after which one?)

    1.

    On the Ribbon, click Create

    2. In the Macros & Code section, click Macro3. Click the arrow of the combo box and select MessageBox4. In the Message text box, type A record has been accessed 5. In the Type combo box, select Information6. In the Title text box, type Microsoft Access Form Events

    7. Close the macro window

    8.

    When asked whether you want to save, click Yes9. Set the name to mcrCurrent and press Enter10. In the same way, create new macros as follows (use the same Type = Information

    and the same title = Microsoft Access Form Events for all of them):

    Message Name

    The form is loading to occupy the computer memory. mcrLoad

    The form is opening. mcrOpen

    The form is closing. mcrClose

    The form is resizing itself to signal its borders. mcrResizeThe form has been activated and is now the front runner. mcrActivate

    The form is either being closed or being sent behind anotherwindow. mcrDeactivate

    The form is unloading to be removed from the computermemory. mcrUnload

  • 7/29/2019 Events and Macros

    30/43

    11. On the Ribbon, click Create12. In the Forms section, click Form Design13. Double-click the button at the intersection of the rulers14. In the Property Sheet, click Event15. Click On Current and type mcrCurrent

    16. Click On Load and type mcrLoad 17. Click On Open and type mcrOpen

    18. Click On Close and type mcrClose 19. Click On Resize and type mcrResize 20. Click On Activate and type mcrActivate 21. Click On Deactivate and type mcrDeactivate 22. Click On Unload and type mcrUnload 23. Close the form24. When asked whether you want to save, click Yes25. Set the name to FormEvents and click OK26. In the Navigation Pane, double-click the FormEvents form27. Watch the sequence of message boxes and click OK on each28. Close the form

    Introduction to Data Types

    Visually Specifying a Data Type

    A data type represents the kind of information that a particular field should, would, or musthold. Every field in your database objects (tables, forms, and reports) should have the righttype and you should select the most appropriate of them. This helps both you and the userwho performs data entry. Furthermore, a good design will cause you less headache when

    creating calculated expressions.Microsoft Access can assist you with allowing or excluding categories of data in databasefields. Based on this, you can make sure that the user would not type a contract's date in aproject's contact name. To manage different types of information you enter in a database,Microsoft Access helps you organize data by categories.

    Practical Learning: Introducing Data Entry Assistance

    1. To create a new database, in the File Name, replace the contents of the text box withReal Estate1

    2. Click Create3. Double-click ID, type PropertyID , and press Enter4. Right-click the Table1 tab and click Save5. Set the name to Properties and click OK6. Right-click the Properties tab and click Design View

    Setting the Data Type of a Field

  • 7/29/2019 Events and Macros

    31/43

    To make your database efficient, in some circumstances, or depending on the project (orcustomer), you should exercise as much control as possible on data entry. This aspect ismostly controlled at two levels: tables and forms.

    We know that, when creating a table in Datasheet View, to create a column, you can click

    Click to Add, select a field type from the list:

    Type a name for the column. After creating a column, if you want to change it, on theRibbon, click Fields. In the Formatting section, click the arrow of the Data Type combobox and select from the list.

    Besides the Datasheet View, you can use the Design View of a table to specify the type of value that a field can hold. To do this, after specifying the column name, click the arrow of the corresponding box in the Data Type column and select the desired type:

  • 7/29/2019 Events and Macros

    32/43

    After a field has been configured on a table, when that field is used in a form, it wouldrespect the formatting that was done on the table. Even if you create an unbound field on aform, you can still control how it accepts or rejects data. Therefore, data entry can also beconfigured at the form level. To provide this functionality, a form provides the sameproperties as the lower portion of the table's Design View.

    Practical Learning: Introducing Data Types

    1. Click under PropertyID and add the following fields

    Field Name

    Property #

    Address

    City

    State

    ZIP Code

    Bedrooms

    Bathrooms

    Year Built

    Market Value

    2. Notice that the default data type for all the fields is Text3. Save the table

    Data Type Properties

  • 7/29/2019 Events and Macros

    33/43

    To further control how data is entered and/or how it is displayed on a field, both the table inDesign View and the Property Sheet in Form Design provide special fields.

    Because the list of data types may appear short to you, each data type provides someconfiguration that allows you to control how data for that field either would be selectively

    entered or would display. To do this in the Datasheet View of a table, click any field underthe column header. On the Ribbon, click Fields. Use the options in the Properties, theFormatting, and the Field Validation tabs:

    To control the properties of a table in the Design View, after selecting a data type in theData Type column, in the lower section of the table, you can format or further configure thefield. The lower part of the table Design View is made of two sections: the property pageson the lower left and the properties help section on the lower right:

    The kind of Data Type you set for a field in the upper section controls what displays in thelower section of the view. The General property page controls the features of the selecteddata type. The options in the General property page depend on the data type that wasspecified:

  • 7/29/2019 Events and Macros

    34/43

    The Lookup tab allows you to specify a feature that is particular to the specific data typethat was specified. For some data types, it would display a combo box. For some other datatypes, the Lookup property page would be empty.

  • 7/29/2019 Events and Macros

    35/43

    Routine Assistance With Data Entry

    A Default Value for a Column

    Data entry consists of typing values in data fields or selecting values from bound controls.

    Some records happen to have the same value for a particular field, or most records hold acommon value for a certain field. When designing a table, you can assign the mostcommonly used value to such a field so the user would not have to type it. The user wouldchange the value only if it is different from the usual. For example, when creating adatabase for a small company, all employees may have the same telephone number but withindividual extensions. When a new record is being entered, the value would be set alreadyfor the field.

    To specify a regularly used value for a field:

    While the table is displaying in the Datasheet View, on the Ribbon, click Fields.

    On the Properties section, click Default View. This would open the ExpressionBuilder with = in the main text box. If you know the constant value you want to use,type it. Then click OK

    If the table is displaying in the Design View, in the top section, click the field. Inthe lower section of the window, click Default Value and type the desired value

    The default value should be appropriately typed:

    If the field is text-based, you can type the default text included in double-quotes.Examples are "M", "Virginia", "(301) 122-4738"

    If the field is numeric, you can type the number

    If the field is date-based and you want to specify a constant (fixed), type it betweentwo # signs. An example would be #2/5/1998#

    Instead of a constant value, you can use a value that depends on a built-in function. If youare using the Expression Builder, in the left list, expand Functions and expand Built-InFunction. In the middle list, click the category the function belongs to. From the right list,double-click the desired function, then configure the function appropriately.

    Practical Learning: Setting Default Values

    1. In the top section, click State

    2. In the bottom section, click Default Value and type MD 3. Save the table4. To switch it to Datasheet View, in the lower-right section, click the Datasheet View

    button

    Validation Rule

  • 7/29/2019 Events and Macros

    36/43

    A validation rule is a condition that the value entered in a field must meet in order to bevalid. To create a validation rule:

    If the table is displaying in the Datasheet View, on the Ribbon, click Fields. In theField Validation section, click Validation and click Field Validation Rule

    If the table is displaying in the Design View, click the field. In the lower section of the window, click Validation Rule and click its ellipsis button

    In both cases, the action would open the Expression Builder where you can create a rule.

    Validation Text

    When the condition in the Validation Rule field is not respected, you can display a messagebox to let the user know. To create the message:

    If the table is displaying in the Datasheet View, on the Ribbon, click Fields. In theField Validation section, click Validation and click Field Validation Message. Thiswould open the Enter Validation Message where you can type the desired message:

    If the table is displaying in the Design View, click the field. In the lower section of the window, click Validation Text and type the desired message

  • 7/29/2019 Events and Macros

    37/43

    Value Required for a Field

    If you think that there must be an entry for a particular field for each record, you canrequire it from the user. When performing data entry, after creating a record, the usercannot move to the next record if a value for that field has not been provided. You can

    specify that the value of a field is required when creating a table, whether you are workingin the Datasheet View or the Design View of the table:

    If you are creating or configuring a table in the Datasheet View, to specify that thevalues of a field are required, click any cell of the column. On the Ribbon, click Fields. In the Field Validation section, click the Required check box. By default, theRequired check box is not checked

    If you are creating or configuring a table in the Design View, in the top section,click the field. In the bottom section, click the arrow of the Required field and set itto Yes. Its default value is No

    Practical Learning: Specifying Required Fields

    1. On the table, click Property # and, on the Ribbon, click the Fields tab2. In the Field Validation section, click the Required check box

    3. To change the view, in the Views section of the Ribbon, click Design View4. In the upper section of the table, click Market Value 5. In the lower section of the table, double-click the Required field to set its value to

    Yes

    6.

    Save the tableIndexed Fields

    When data is entered in fields, it is possible to have the same value for a field in differentrecords, such as two people who live in the same state. This is considered as a duplicatevalue. In some other cases, this may not be acceptable. For example, you may not want twoemployees to have the same employee number.

    You can specify the indexation of a field when creating a table either in the Datasheet Viewor the Design View of the table. If you are creating or configuring a table in the Datasheet

    View, to specify the indexation of a field, click any cell of the column. Then, on the Ribbon,click Fields. In the Field Validation section, click the check box of the Unique option

    If you are creating or configuring a table in the Design View, in the top section, click thefield. In the bottom section, click the arrow of the Indexed property. This characteristic canbe set using one of 3 values:

    If set to No (its default), no duplicate value checking will be done

  • 7/29/2019 Events and Macros

    38/43

    If you want the database engine to check for duplicate but not necessary take anyaction, set this property to Yes (Duplicates OK)

    If you do not want a duplicate value of the same field in different records, set thefield's Indexed property to Yes (No Duplicates)

    Practical Learning: Controlling Indexed Fields

    1. In the upper section, click Property # 2. In the lower section, click Indexed to display its combo box. Click the arrow of the

    Indexed combo box and select Yes (No Duplicates)

    1. To change the view, in the Views section of the Design tab of the Ribbon, click

    Datasheet View2. When asked whether you want to save the table, click Yes

    Data Entry With a Lookup Field

    Introduction

    So far, to enter a string in a table, we assumed that the user would type it. In some cases,this is fine. Sometimes, you may want to limit the number of entries that a user can enterfor a field. For example, if you create a list of students and you want the user to specifytheir gender, if you leave it up to the person doing data entry, you may end up with entriessuch as W, Girl, Female, G, Woman, or F. Although all these could indicate that the recordsdesignate a female, when performing data entry, these entries would create confusion andunpredictable results. Fortunately, Microsoft Access provides various solutions to this typeof problem.

    On a table, you can create a list of values that the user would select for a field, instead of typing the value. Such a field is referred to as lookup. You can create the field whether inthe Datasheet View or in the Design View.

    The Lookup Field as a Combo Box

    A lookup field appears as a combo box. To use it, the user can click the arrow and selectfrom the list. There are various ways you can create a lookup field. In the Datasheet View:

    Click Click to Add. In the window that appears, click Lookup & Relationship

  • 7/29/2019 Events and Macros

    39/43

    Click a box under Click to Add. On the Ribbon, click Fields. In the Add & Delete

    section, click More Fields. In the window that appears, click Lookup &Relationship

    In both cases, this would start the Lookup Wizard. In the first page of the wizard, you mustselect the second radio button. In the second page of the wizard, you will be asked toprovide a value for each item that will eventually show in the list. To do that, you wouldclick under Col1, type a value, press and down arrow key, and continue populating the list.When the list is complete, you can click Next, give it a name, and click Finish.

    Microsoft Access provides a few configured lookup fields you can add to a table. To useone of them, display the table in Datasheet View. Click a cell under Click to Add. On the

    Ribbon, click Fields. In the Add & Delete section, click More Fields. In the list that appears,click Category, Priority, or Status. You can keep the list or change it. To change the list,click the arrow of the combo box. Under the list, a button would appear:

    You can then click that button. An Edit List Item dialog box would come up:

  • 7/29/2019 Events and Macros

    40/43

    To change an item, select it in the list and replace it with a new string. To add a new item,click under the other items or click the end of the last item, press Enter, and type the desireditem. The Default Value combo box allows you to specify what item would display as thedefault.

    To create a lookup field in the Design View of a table, after specifying a name for thecolumn, set its Data Type to Lookup Wizard... This would start the Lookup Wizard. Youuse exactly as we described the Lookup Column from the Datasheet View.

    Practical Learning: Setting a Preset List Of Items

    1. The Properties table should still be opened in Datasheet View.On the table, click the cell under Property #

    2. On the Ribbon, click Fields3. In the Add & Delete section, click More Fields and click Lookup & Relationship4. In the first page of the wizard, click the second radio button: I will type in the values

    that I want

  • 7/29/2019 Events and Macros

    41/43

    5. Click Next6. In the second page of the wizard, click the first empty field under Col1 and type

    Single Family 7. Press the down-arrow key and type Townhouse 8. Press the down-arrow key and type Condominium 9. Press the down-arrow key and type Unknown

    10. Click Next11. For the column label, type Property Type and click Finish

  • 7/29/2019 Events and Macros

    42/43

    12. On the table, click the cell under Property Type13. In the Add & Delete section of the Fields tab of the Ribbon, click More Fields.

    Scroll down. In the Quick Start section, click Category14. While the new column is still selected, in the Properties section of the Ribbon, click

    Name & Caption

    15. Change the Name to Condition 16. Change the Caption to Condition17. In the Description text box, type Possible Values are Excellent, Good Condition,

    Needs Some Repair, Bad Shape

    18. Click OK19. Click the arrow under the Condition column header and click the button that

    appears

    20. Press Ctrl + A to select everything in the list and press Delete21. Type Unknown and press Enter22. Complete the list with the following items Excellent , Good Condition , Needs

    Some Repair , Bad Shape

    23. Click the arrow of the Default Value combo box and select Unknown

    24. Click OK25. Enter a few records

    http://www.functionx.com/MSAXSDD2010/properties1.htmhttp://www.functionx.com/MSAXSDD2010/properties1.htmhttp://www.functionx.com/MSAXSDD2010/properties1.htmhttp://www.functionx.com/MSAXSDD2010/properties1.htm
  • 7/29/2019 Events and Macros

    43/43

    Lesson Summary

    Exercises

    World Statistics

    1. Open the World Statistics1 database2. Open the Countries table in Design View3. Use the Lookup Wizard on the GovernmentType column to create a list of the

    government types. The options will be Republic , Islamic Republic , Monarchy ,Communist State , Other , and Unknown . Set the Default Value to " Unknown "

    4. Save and close the table

    US Senate

    1. Open the US Senate1 database

    2. Open the Senators table3. Use the Lookup Wizard on the SeatingStatus column to create a list of the status.The options will be Active , Retired , Removed , and Deceased

    4. Use the Lookup Wizard on the Gender column to create a list of the genders. Theoptions will be Male , Female , and Unknown . Set the Default Value to " Unknown "

    5. Save and close the table