SlideShare a Scribd company logo
Microsoft Access Tutorials: Table of Contents
1. Introduction to Microsoft Access                 2. Tables
 1.1 Introduction: What is Access?              1    2.1 Introduction: The importance of good table
   1.1.1 The many faces of Access               1      design                                       1
   1.1.2 What is in an Access database file?    3    2.2 Learning objectives                        1
 1.2 Learning objectives                        3    2.3 Tutorial exercises                         1
 1.3 Tutorial exercises                         4      2.3.1 Datasheet basics                       2
   1.3.1 Starting Access                        4      2.3.2 Creating a new table                   2
   1.3.2 Creating a new database                4      2.3.3 Specifying the primary key             7
   1.3.3 Opening an existing database           6      2.3.4 Setting field properties               7
   1.3.4 Importing data from other applications 6      2.3.5 Using the input mask wizard            9
   1.3.5 Getting help                           9    2.4 Discussion                                 9
   1.3.6 Compacting your database               9      2.4.1 Key terminology                        9
 1.4 Discussion                                14      2.4.2 Fields and field properties           13
   1.4.1 The database file in Access           14        2.4.2.1 Field names                       13
   1.4.2 Compacting a database                 14        2.4.2.2 Data types                        13
   1.4.3 Renaming a database                   14        2.4.2.3 “Disappearing” numbers in autonumber
   1.4.4 Developing applications in Access     15           fields                                 14
   1.4.5 Use of linked tables                  16        2.4.2.4 Input masks                       15
 1.5 Application to the assignment             16        2.4.2.5 Input masks and literal values    16

© Michael Brydon (brydon@unixg.ubc.ca)
Last update: 25-Aug-1997                                    Home     Previous    1 of 8    Next



 2.5 Application to the assignment            17       4.3.1 Creating a query                       2
                                                       4.3.2 Five basic query operations            2
3. Relationships                                         4.3.2.1 Projection                         2
 3.1 Introduction: The advantage of using tables         4.3.2.2 Sorting                            7
   and relationships                           1         4.3.2.3 Selection                          7
   3.1.1 “Normalized” table design             3         4.3.2.4 Complex selection criteria         7
 3.2 Learning objectives                       4         4.3.2.5 Joining                           11
 3.3 Tutorial exercises                        4       4.3.3 Creating calculated fields            15
   3.3.1 Creating relationships between tables 4         4.3.3.1 Refining the calculated field     18
   3.3.2 Editing and deleting relationships    7         4.3.3.2 A more complex calculated field   18
 3.4 Discussion                                7       4.3.4 Errors in queries                     20
   3.4.1 One-to-many relationships             7     4.4 Discussion                                20
   3.4.2 Referential integrity                 9       4.4.1 Naming conventions for database
 3.5 Application to the assignment            10         objects                                   20
                                                       4.4.2 The ampersand (&) operator            21
4. Basic Queries Using QBE                             4.4.3 Using queries to populate tables on the
 4.1 Introduction: Using queries to get the              “many” side of a relationship             22
   information you need                        1       4.4.4 Non-updatable recordsets              23
 4.2 Learning objectives                       1     4.5 Application to the assignment             27
 4.3 Tutorial exercises                        2


                                                            Home     Previous    2 of 8    Next
5. Basic Queries using SQL                                      6.3.1.4 Binding an unbound text box to a field 9
 5.1 Introduction: The difference between QBE                 6.3.2 Creating a single-column form using the
   and SQL                                    1                 wizard                                        11
 5.2 Learning objectives                      1             6.4 Discussion                                    14
 5.3 Tutorial exercises                       1               6.4.1 Columnar versus tabular versus
   5.3.1 Basic SQL queries                    2                 datasheet forms                               14
   5.3.2 Complex WHERE clauses                4             6.5 Application to the assignment                 14
   5.3.3 Join queries                         4
 5.4 Discussion                               5            7. Subforms
                                                            7.1 Introduction: The advantages of forms
6. Form Fundamentals                                          within forms                              1
 6.1 Introduction: Using forms as the core of an            7.2 Learning objectives                     1
   application                                         1    7.3 Tutorial exercises                      1
 6.2 Learning objectives                               1      7.3.1 Creating the main form              3
 6.3 Tutorial exercises                                2      7.3.2 Creating the subform                3
   6.3.1 Creating a form from scratch                  2      7.3.3 Linking the main form and subform   3
     6.3.1.1 Adding bound text boxes                   2      7.3.4 Linking forms and subforms manually 9
     6.3.1.2 Using a field’s properties to protect its        7.3.5 Non-synchronized forms             13
        contents                                       6      7.3.6 Aesthetic refinements              13
     6.3.1.3 Adding an unbound text box                6        7.3.6.1 Changing the form’s caption    13



                                                                   Home      Previous     3 of 8     Next



    7.3.6.2 Eliminating unwanted scroll bars and              8.4.1 Why you should never use a combo box
       navigation buttons                        13             for a non-concatenated key.            19
 7.4 Application to the assignment               16           8.4.2 Controls and widgets               21
                                                            8.5 Application to the assignment          22
8. Combo Box Controls
 8.1 Introduction: What is a combo box?          1         9. Advanced Forms
 8.2 Learning objectives                         2          9.1 Introduction: Using calculated controls on
 8.3 Tutorial exercises                          2            forms                                           1
   8.3.1 Creating a bound combo box              2          9.2 Learning objectives                           1
   8.3.2 Filling in the combo box properties     5          9.3 Tutorial exercises                            1
   8.3.3 A combo box based on another table or                9.3.1 Creating calculated controls on forms 1
     query                                       6            9.3.2 Showing a total on the main form          2
     8.3.3.1 Showing more than one field in the                 9.3.2.1 Calculating the aggregate function on
        combo box                                9                 the subform                                5
     8.3.3.2 Hiding the key field               12              9.3.2.2 Hiding the text box on the subform    9
     8.3.3.3 Changing the order of items in the             9.4 Discussion                                    9
        combo box                               14          9.5 Application to the assignment                11
   8.3.4 Changing a form’s tab order            18
 8.4 Discussion                                 19




                                                                   Home      Previous     4 of 8     Next
10. Parameter Queries                                 11.3.2 Using an update query to rollback
 10.1 Introduction: Dynamic queries using               changes                                   3
  parameters                                 1        11.3.3 Using an update query to make
 10.2 Learning objectives                    1          selective changes                         8
 10.3 Tutorial exercises                     2        11.3.4 Rolling back the changes             9
  10.3.1 Simple parameter queries            2        11.3.5 Attaching action queries to buttons 9
  10.3.2 Using parameters to generate prompts        11.4 Application to the assignment          11
    4                                                 11.4.1 Rolling back your master tables     11
  10.3.3 Values on forms as parameters       4        11.4.2 Processing transactions             16
 10.4 Application to the assignment          7
                                                    12. An Introduction to Visual Basic
11. Action Queries                                   12.1 Introduction: Learning the basics of
 11.1 Introduction: Queries that change data    1     programming                                  1
  11.1.1 What is an action query?               1     12.1.1 Interacting with the interpreter      1
  11.1.2 Why use action queries?                1    12.2 Learning objectives                      2
 11.2 Learning objectives                       2    12.3 Tutorial exercises                       2
 11.3 Tutorial exercises                        3     12.3.1 Invoking the interpreter              2
  11.3.1 Using a make-table query to create a         12.3.2 Basic programming constructs          3
    backup                                      3       12.3.2.1 Statements                        3
                                                        12.3.2.2 Variables and assignment          3



                                                            Home     Previous    5 of 8    Next



    12.3.2.3 Predefined functions             4       13.1.2 The Access macro language              2
    12.3.2.4 Remark statements                5       13.1.3 The trigger design cycle               3
  12.3.3 Creating a module                    6      13.2 Learning objectives                       3
  12.3.4 Creating subroutines with looping and       13.3 Tutorial exercises                        4
    branching                                 7       13.3.1 The basics of the macro editor         4
    12.3.4.1 Declaring variables              7       13.3.2 Attaching the macro to the event       5
    12.3.4.2 Running the subroutine           9       13.3.3 Creating a check box to display update
    12.3.4.3 Conditional branching            9         status information                          9
  12.3.5 Using the debugger                  10       13.3.4 The SetValue command                 10
  12.3.6 Passing parameters                  11       13.3.5 Creating conditional macros          10
  12.3.7 Creating the Min() function         13         13.3.5.1 The simplest conditional macro   13
 12.4 Discussion                             14         13.3.5.2 Refining the conditions          15
  12.4.1 Interpreted and compiled languages 14          13.3.5.3 Creating a group of named macros 16
 12.5 Application to the assignment          16       13.3.6 Creating switchboards                17
                                                        13.3.6.1 Using a macro and manually-created
13. Event-Driven Programming Using                         buttons                                21
   Macros                                               13.3.6.2 Using the button wizard          21
 13.1 Introduction: What is event-driven              13.3.7 Using an autoexec macro              21
  programming?                                  1    13.4 Discussion                              25
  13.1.1 Triggers                               2     13.4.1 Event-driven programming versus
                                                        conventional programming                  25

                                                            Home     Previous    6 of 8    Next
13.5 Application to the assignment              26      14.5.1 Using a separate table to store system
                                                          parameters                                 20
14. Data Access Objects                                  14.5.2 Determining outstanding backorders21
 14.1 Introduction: What is the DAO hierarchy?1
  14.1.1 DAO basics                           1        15. Advanced Triggers
  14.1.2 Properties and methods               2         15.1 Introduction: Pulling it all together     1
  14.1.3 Engines, workspaces, etc.            3         15.2 Learning objectives                       1
 14.2 Learning objectives                     5         15.3 Tutorial exercises                        1
 14.3 Tutorial exercises                      5          15.3.1 Using a macro to run VBA code          1
  14.3.1 Setting up a database object         5            15.3.1.1 Creating a wrapper                 2
  14.3.2 Creating a Recordset object          7            15.3.1.2 Using the RunCode action           2
  14.3.3 Using a Recordset object             8          15.3.2 Using activity information to determine
  14.3.4 Using the FindFirst method          10            the number of credits                       4
  14.3.5 The DLookUp() function              12            15.3.2.1 Scenario                           4
    14.3.5.1 Using DLookUp() in queries      15            15.3.2.2 Designing the trigger              6
    14.3.5.2 Understanding the WHERE clause 15             15.3.2.3 Preliminary activities             8
 14.4 Discussion                             17            15.3.2.4 Looking up the default value       8
  14.4.1 VBA versus SQL                      17            15.3.2.5 Changing the Record Source of the
  14.4.2 Procedural versus Declarative       19                form                                   10
 14.5 Application to the assignment          20            15.3.2.6 Creating the SetValue macro       11



                                                               Home     Previous    7 of 8    Next



    15.3.2.7 Attaching a procedure to the After          15.4.3 Understanding the
       Update event                               11      UpdateBackOrders() function              24
  15.3.3 Use an unbound combo box to                     15.4.4 Annotated source code for the
    automate search                               12      backorders shortcut module.              27
    15.3.3.1 Manual search in Access              12      15.4.4.1 The UpdateBackOrders() function
    15.3.3.2 Preliminaries                        13                                               27
    15.3.3.3 Creating the unbound combo box 13            15.4.4.2 Explanation of the
    15.3.3.4 Automating the search procedure using            UpdateBackOrders() function          27
       a macro                                    16      15.4.4.3 The BackOrderItem() subroutine30
  15.3.4 Using Visual Basic code instead of a             15.4.4.4 Explanation of the BackOrderItem()
    macro                                         19          subroutine                           31
 15.4 Application to the assignment               20
  15.4.1 Triggers to help the user                20
  15.4.2 Updating the BackOrders table            22
    15.4.2.1 Create the pqryItemsToBackOrder
       query                                      23
    15.4.2.2 Import the shortcut function         23
    15.4.2.3 Use the function in your application 24
    15.4.2.4 Modifying the UpdateBackOrders()
       function                                   24



                                                               Home     Previous    8 of 8    Next
Access Tutorial 1: Introduction to Microsoft Access
The purpose of these tutorials is not to teach you       • Microsoft SQL Server
Microsoft Access, but rather to teach you some           • IBM DB2
generic information systems concepts and skills          • Informix
using Access. Of course, as a side effect, you will     Well-know PC-based (“desktop”) relational DBMSes
learn a great deal about the software—enough to         include
write your own useful applications. However, keep in      • Microsoft Access
mind that Access is an enormously complex, nearly-        • Microsoft FoxPro
industrial-strength software development environ-         • Borland dBase
ment. The material here only scrapes the surface of
Access development and database programming.            1.1.1 The many faces of Access
                                                        Microsoft generally likes to incorporate as many fea-
1.1 Introduction: What is Access?                       tures as possible into its products. For example, the
Microsoft Access is a relational database manage-       Access package contains the following elements:
ment system (DBMS). At the most basic level, a            • a relational database system that supports two
DBMS is a program that facilitates the storage and          industry standard query languages: Structured
retrieval of structured information on a computer’s         Query Language (SQL) and Query By Example
hard drive. Examples of well-know industrial-strength       (QBE);
relational DBMSes include
  • Oracle

© Michael Brydon (brydon@unixg.ubc.ca)
Last update: 24-Aug-1997                                         Home       Previous     1 o f 17    Next


1. Introduction to Microsoft Access                                                Introduction: What is Access?

 • a full-featured procedural programming lan-           • the procedural programming personality expects
   guage—essentially a subset of Visual Basic,             you to view your application as commands to be
 • a simplified procedural macro language unique           executed sequentially;
   to Access;                                            • the object-oriented personality expects you to
 • a rapid application development environment             view your application as objects which encapsu-
   complete with visual form and report develop-           late state and behavior information.
   ment tools;                                          Microsoft makes no effort to provide an overall logi-
 • a sprinkling of objected-oriented extensions;        cal integration of these personalities (indeed, it is
   and,                                                 unlikely that such an integration is possible). Instead,
 • various wizards and builders to make develop-        it is up to you as a developer to pick and choose the
   ment easier.                                         best approach to implementing your application.
For new users, these “multiple personalities” can be    Since there are often several vastly different ways to
a source of enormous frustration. The problem is        implement a particular feature in Access, recogniz-
that each personality is based on a different set of    ing the different personalities and exploiting the best
assumptions and a different view of computing. For      features (and avoiding the pitfalls) of each are impor-
instance,                                               tant skills for Access developers.
  • the relational database personality expects you
                                                        The advantage of these multiple personalities is that
    to view your application as sets of data;
                                                        it is possible to use Access to learn about an enor-
                                                        mous range of information systems concepts without


                                                                 Home       Previous     2 o f 17    Next
1. Introduction to Microsoft Access                                                              Learning objectives

having to interact with a large number of “single-per-      • macros and Visual Basic programs for extending
sonality” tools, for example:                                 the functionality of database applications.
 • Oracle for relational databases                         All these database objects are stored in a single file
 • PowerBuilder for rapid applications development,        named <filename>.mdb. When you are running
 • SmallTalk for object-oriented programming.              Access, a temporary “locking” file named <file-
Keep this advantage in mind as we switch back and          name>.ldb is also created. You can safely ignore
forth between personalities and different computing        the *.ldb file; everything of value is in the *.mdb file.
paradigms.
                                                           1.2 Learning objectives
1.1.2 What is in an Access database
      file?
                                                                 How do I get started?

Although the term “database” typically refers to a col-
                                                                 How do I determine the version I am using?

lection of related data tables, an Access database               How do I create or edit a database object?
includes more than just data. In addition to tables, an          What is the database window and what does
Access database file contains several different types             it contain?
of database objects:                                             How do I import an Excel spreadsheet?
                                                              
  • saved queries for organizing data,
  • forms for interacting with the data on screen,                How do I delete or rename database objects?
  • reports for printing results,


                                                                     Home      Previous      3 o f 17     Next


1. Introduction to Microsoft Access                                                                 Tutorial exercises

      How do I get help from the on-line help             Access from the main menu to see which version
       system?                                             you are using.
      How do I compact a database to save space?
                                                                  All the screen shots in these tutorials are
                                                                  taken from Access version 7.0 (released as
1.3 Tutorial exercises                                            part of Office 95). Although there are some
In this tutorial, you will start by creating a new data-          important differences between version 2.0
base file.                                                        and version 7.0, the concepts covered here
                                                                  are the same for both. Version 8.0 (released
1.3.1 Starting Access                                             as part of Office 97) is only slightly different
 • To start Access, you double click the Access icon              from version 7.0.
   (      for version 8.0 and 7.0 or    for version
   2.0) from within Microsoft Windows.
If you are working in the Commerce PC Lab, you will
                                                                 Whenever the instructions given in the tutorial
                                                                  differ significantly from version 7.0, a warning
                                                                  box such as this is used.
be working with Access version 2.0. If you are work-
ing at home, you will able be to tell what version you
                                                           1.3.2 Creating a new database
are using by watching the screen “splash” as the pro-
gram loads. Alternatively, select Help  About              • Follow the directions in Figure 1.1 to create a
                                                              new database file called myfile.mdb.



                                                                     Home      Previous      4 o f 17     Next
1. Introduction to Microsoft Access                                                                  Tutorial exercises


                FIGURE 1.1: Select the name and location of your new (empty) database.




                                                New from thedatabase by selecting File the
                                                 Create a new
                                                              main menu or by clicking
                                                     “new database” button on the tool bar.


                                                Note thata you are limited to 8-letter names in
                                                 Type in new database name and press Enter.

                                                     version 2.0.




                                                                      Home      Previous      5 o f 17     Next


1. Introduction to Microsoft Access                                                                  Tutorial exercises

 • Examine the main features of the database win-
   dow—including the tabs for viewing the different                If you are using version 8.0, you can use
                                                                    either univ0_v2.mdb or univ0_v7.mdb for
   database objects—as shown in Figure 1.2.                         the tutorials. When you open the file, Access
                                                                    will ask you if you want to convert it to version
1.3.3 Opening an existing database                                  8.0. Select yes and provide a new name for
Since an empty database file is not particularly inter-             the converted file (e.g., univ0_v8.mdb)
esting, you are provided with an existing database
                                                            • Open the univ0_vx.mdb file and examine the
file containing information about university courses.
                                                              contents of the Sections table, as shown in
For the remainder of this tutorial, we will use a file
                                                              Figure 1.3.
called univ0_v7.mdb, which is available from the
tutorial’s Internet site.
                                                          1.3.4 Importing data from other

      If you are using version 2.0, you will need to           applications
       use the univ0_v2.mdb database instead.             Access makes it easy to import data from other
       Although you can open a version 2.0 data-          applications. In this section, you will create a new
       base with version 7.0, you cannot open a ver-      table using data from an Excel spreadsheet.
       sion 7.0 database with version 2.0. Importing        • Select File  Get External Data  Import from the
       and exporting across versions is possible,             main menu and import the depts.xls spread-
       however.



                                                                      Home      Previous      6 o f 17     Next
1. Introduction to Microsoft Access                                                         Tutorial exercises


  FIGURE 1.2: The database window contains all the database objects for a particular application.


                                                                   The database window is always
                                                                   available from the Window menu.
       Tables —
       contain data
       in rows and                                                                  Modules —
       columns.                                                                     contain Visual
                                                                                    Basic
                                                                                    procedures and
                                                                                    functions.
      Queries — allow the
      information in                                                      Macros — are sets of high-
      tables to be sorted,                                                level commands that can be
      filtered, and shown                                                 used to process data and
      in different ways.                                                  perform repetitive tasks.
                             Forms — are for      Reports —are
                             displaying           for organizing
                             information on       and printing
                             the screen.          information.




                                                               Home      Previous    7 o f 17     Next


1. Introduction to Microsoft Access                                                         Tutorial exercises


  FIGURE 1.3: Open the univ0_vx.mdb file for the version of Access that you are using and then
                                 open the Sections table

                                           from the mainOpen Database
                                            Select File 
                                                          menu.
                                                                                      You can open a
                                                                                      database object for
                                                                                      viewing, for
                                                                                      modification, or
                                                                                      create a new object.




   correctthe and
    Select
            file
       open the
       Sections
       table.




                                                               Home      Previous    8 o f 17     Next
1. Introduction to Microsoft Access                                                            Tutorial exercises

   sheet as a new table called Departments (see         1.3.5 Getting help
   Figure 1.4).                                         A recent trend in commercial software (especially
                                                        from Microsoft) is a reliance on on-line help and doc-
     In version 2.0, the menu structure is slightly
      different. As such, you must use File  Import.
                                                        umentation in lieu of printed manuals. As a conse-
                                                        quence, a good understanding of how to use the on-
 • Use the import wizard specify the basic import       line help system is essential for learning any new
   parameters. You should accept all the defaults       software. In this section, you will use Access’ on-line
   provided by the wizard except for those shown in     help system to tell you how to compact a database.
   Figure 1.5.                                             • Press F1 to invoke the on-line help system. Find
 • Double click the Departments table to ensure it           information on compacting a database, as shown
   was imported correctly.                                   in Figure 1.6.
                                                           • Familiarize yourself with the basic elements of
      If you make a mistake, you can rename or               the help window as shown in Figure 1.7.
      delete a table (or any database object in the
      database window) by selecting it and right-       1.3.6 Compacting your database
      clicking (pressing the right mouse button          • Follow the directions provided by the on-line help
      once).                                               window shown in Figure 1.7 to compact your
                                                           database.



                                                                 Home       Previous    9 o f 17     Next


1. Introduction to Microsoft Access                                                            Tutorial exercises


            FIGURE 1.4: Import the dept.xls spreadsheet as a table called Departments.




                                                                            Double-click depts.xls.


 ImportFile the from the main menu
  Select
         from
               Get External Data 

      and move the directory containing the
      file you want to import.                                       with that extension *.xls (files
                                                                      Select files of type
                                                                                           will show in
                                                                          the file window).




                                                                 Home       Previous    10 o f 17    Next
1. Introduction to Microsoft Access                                                                     Tutorial exercises


               FIGURE 1.5: Use the spreadsheet import wizard to import the Excel file.



                                                                                   column headings option so
                                                                                    Select the first row contains

                                                                                        that the column headings in the
                                                                                        spreadsheet are not interpreted
                                                                                        as data.




                                                                             about primary keystalked
                                                                              Since we have not
                                                                                                 yet,
                                                                                    select no primary key.




                                                                       Home        Previous      11 o f 17     Next


1. Introduction to Microsoft Access                                                                     Tutorial exercises



                                     lettersin the first few
                                      Type                          FIGURE 1.6: Use the help system to find
                                              of the topic you          information on a specific topic
                                          are looking for.



                                            the list the best match from
                                             Select
                                                       (i.e., “compacting
                                                 databases”) and double-
                                                 click to get a list of topics.


                                                                                  Double click the most
                                                                                   promising entry in this list
                                                                                   to get the actual help topic.



       The Index is the best place to                                              For most students, the help
       start when you are looking for a                                            system in Access version
       specific topic. If you need more                                            2.0 is easier to navigate.
       structured information or are                                               Use the “cue cards” in
       looking for an overview, use the                                            version 2.0 to get step-by-
       Contents tab.                                                               step instructions for many
                                                                                   operations.


                                                                       Home        Previous      12 o f 17     Next
1. Introduction to Microsoft Access                                                                Tutorial exercises


            FIGURE 1.7: Follow the instructions provided by help to compact your database


                                                                       Minimize (rather than close) help
                                                                       when you are working so that you can
                                                                       use the Back button to return to
                                                                       previously visited topics without
                                                                       repeating the search.

                                                                       Press help topics to return to the
                                                                       index.

                                                                       Words underlined with a dashed line
                                                                       provide important definitions.




                                                                    Home      Previous      13 o f 17       Next


1. Introduction to Microsoft Access                                                                         Discussion

1.4 Discussion                                             1.4.2 Compacting a database
                                                           As the help system points out, Access database files
1.4.1 The database file in Access                          can become highly fragmented and grow to become
The term “database” means different things depend-         much larger than you might expect given the amount
ing on the DBMS used. For example in dBase IV, a           of data they contain (e.g., multiple megabytes for a
database is a file (filename.dbf) containing a           handful of records). Compacting the database from
single table. Forms and reports are also stored as         time to time eliminates fragmentation and can dra-
individual files with different extensions. The net        matically reduce the disk space requirement of your
result is a clutter of files.                              database.
In contrast, an Oracle database has virtually no rela-
tionship to individual files or individual projects. For   1.4.3 Renaming a database
instance, a database may contain many tables from          It is often the case that you are working with a data-
different projects/applications and may also be            base and want to save it under a different name or
stored split into one or more files (perhaps on differ-    save it on to a different disk drive. However, one
ent machines).                                             command on the File menu that is conspicuous by its
Access strikes a convenient balance—all the                absence is Save As.
“objects” (tables, queries, forms, reports, etc.) for a    However, when compacting your database, Access
single project/application are stored in a single file.    asks for the name and destination of the compacted
                                                           file. As a result, the compact database utility can be


                                                                    Home      Previous      14 o f 17       Next
1. Introduction to Microsoft Access                                                                        Discussion

used as a substitute for the Save As command. This           mended sequence for prototyping using Access is
is especially useful in situations in which you cannot       the following:
use the operating system to rename a file (e.g.,             1. Model the information of interest in terms of enti-
when you do not have access to the Windows file                 ties and relationships between the entities (this is
manager).                                                       covered in the lecture portion of the course).
                                                             2. Create a table for each entity (Tutorial 2).
1.4.4 Developing applications in Access                      3. Specify the relationships between the tables
In general, there are two basic approaches to devel-            (Tutorial 3).
oping information systems:                                   4. Organize the information in your tables using
  • in-depth systems analysis, design, and imple-               queries (Tutorial 4, Tutorial 5, Tutorial 10)
    mentation,                                               5. Create forms and reports to support input and
  • rapid prototyping (in which analysis, design, and           output transactions (Tutorial 6, Tutorial 7).
    implementation are done iteratively)                     6. Enhance you forms with input controls
Access provides a number of features (such as                   (Tutorial 8)
graphical design tools, wizards, and a high-level            7. Create action queries (Tutorial 11), macros
macro language) that facilitate rapid prototyping.              (Tutorial 13), or Visual Basic programs
Since you are going to build a small system and                 (Tutorial 12, Tutorial 14) to perform the transac-
since time is limited, you will use a rapid prototyping         tion processing functions of the application.
approach to build your application. The recom-


                                                                      Home       Previous     15 o f 17    Next


1. Introduction to Microsoft Access                                                     Application to the assignment

8. Create “triggers” (procedures attached to events)         machine, update the links to the data file, and the
   to automate certain repetitive tasks (Tutorial 15).       upgrade is done.

1.4.5 Use of linked tables                                          Do not used linked tables in the assignment.
                                                                    The links are dependent on the absolute
Most professional Access developers do not put their
                                                                    directory structure. As a result, if the directory
tables in the same database file as their queries,
                                                                    structure on your machine is different from
forms, reports, and so on. The reason for this is sim-
                                                                    that on the marker’s machine, the marker will
ple: keep the application’s data and interface sepa-
                                                                    not be able to use your application without
rate.
                                                                    first updating the links (a time consuming pro-
Access allows you to use the “linked table” feature to              cess for a large number of assignments).
link two database files: one containing all the tables
(“data”) and another containing all the interface and        1.5 Application to the assignment
logic elements of the application (“interface”). The
                                                             After completing this tutorial you should be ready to
linked tables from the data file show up in the inter-
face file with little arrows (indicating that they are not   create the database file that you will use for the
                                                             remainder of the course.
actually stored in the interface file).
                                                             1. Create an empty database file called your
In this way, you can modify or update the interface
file without affecting the actual data in any way. You          groupID.mdb. Remember that your group
                                                                number consists of eight digits.
just copy the new interface file over to the user’s


                                                                      Home       Previous     16 o f 17    Next
1. Introduction to Microsoft Access                                Application to the assignment

2. Import the inventor.xls spreadsheet as your
   Products table.
3. Use the compact utility to make a backup copy of
   your database (use a different name such as
   backup.mdb).




                                                      Home   Previous   17 o f 17   Next
Access Tutorial 2: Tables
2.1 Introduction: The importance                            2.2 Learning objectives
    of good table design                                          How do I enter and edit data in the datasheet
Tables are where data in a database is stored; con-                view of a table?
sequently, tables form the core of any database                   How do I create a new table?
application. In addition to basic data, Access permits
a large amount of domain knowledge (such as cap-
                                                                  How do I set the primary key for a table?

tions, default values, constraints, etc.) to be stored at         How do I specify field properties such as the
the table level.                                                   input mask and caption?

       Extra time spent thinking about table design
                                                                  Why won’t an autonumber field restart
                                                                   counting at one?
                                                               
       can result in enormous time savings during
       later stages of the project. Non-trivial changes            What are the different types of keys?
       to tables and relationships become increas-
       ingly difficult as the application grows in size     2.3 Tutorial exercises
       and complexity.                                      In this tutorial, you will learn to interact with existing
                                                            tables and design new tables.




© Michael Brydon (brydon@unixg.ubc.ca)
Last update: 25-Aug-1997                                              Home       Previous      1 o f 18       Next


2. Tables                                                                                             Tutorial exercises

2.3.1 Datasheet basics                                      such as lecturers, department heads, departmental
 • If you have not already done so, open the                secretaries, and so on.
   univ0_vx.mdb database file from Tutorial 1.               • Return to the database window and create a new
 • Open the Departments table. The important                   table as shown in Figure 2.3.
   elements of the datasheet view are shown in               • In the table design window shown in Figure 2.4,
   Figure 2.1.                                                 type in the following information:
 • Use the field selectors to adjust the width of the                                                     Description
                                                               Field name          Data type
   DeptName field as shown in Figure 2.1.                                                                  (optional)
 • Add the Biology department (BIOL) to the table,          EmployeeID          Text                 use employee
   as shown in Figure 2.2.                                                                           S.I.N.
 • Delete the “Basket Weaving” record by clicking           FName               Text                 First name
   on its record selector and pressing the Delete
                                                            LName               Text                 Last name
   key.
                                                            Phone               Text
2.3.2 Creating a new table                                  Salary              Currency
In this section you will create and save a very basic
skeleton for table called Employees. This table              • Select File  Save from the main menu (or press
could be used to keep track of university employees            Control-S) and save the table under the name
                                                               Employees.


                                                                      Home       Previous      2 o f 18       Next
2. Tables                                                                                               Tutorial exercises


                          FIGURE 2.1: The datasheet view of the Departments table.

    The field names are shown in the “field
    selectors” across the top of the columns.                      the columnDeptName draggingby clicking near
                                                                    Resize the
                                                                               border and
                                                                                          column
                                                                                                 the border to
                                                                       the right.
            You can temporarily sort the records
            in a particular order by right-clicking
            any of the field selectors.


    The records are shown as rows.


    The black triangle indicates the
    “current record”.
                                                                                    The asterisk (*) indicates a
    The grey boxes are “record selectors”.                                          place holder for a new record.

    The “navigation buttons” at the bottom of the window
    indicate the current record number and allow you to go
    directly to the first, previous, next, last, or new record.


                                                                         Home       Previous     3 o f 18     Next


2. Tables                                                                                               Tutorial exercises


                              FIGURE 2.2: Adding and saving a record to the table.



     of thea “newrecord byfield (marked byDeptCode field
      Add new
                   record”
                             clicking in the
                                             the asterisk).
                                                                                               It is seldom necessary to
                                                                                               explicitly save new
                                                                                               records (or changes to
                                                                                               existing records) since
                                                                                               Access automatically
                                                                                               saves whenever you
                                                                                               move to another record,
                                                                                               close the table, quit
                                                                                               Access, etc.




      data, click on thesave theselector (note the
       To permanently
                          record
                                  change to the

             icon changes from a pencil to a triangle).


                                                                         Home       Previous     4 o f 18     Next
2. Tables                                                                                    Tutorial exercises


                                         FIGURE 2.3: Create a new table.



          createthenew table. to
           Click
                  a
                     New button




             the table wizard at this point).
              Select “design view” (avoid using




                                                                  Home     Previous   5 o f 18     Next


2. Tables                                                                                    Tutorial exercises


   FIGURE 2.4: Use the table design window to enter the field properties for the Employees table.



     data typesfieldthe five and
      Enter the
                 for
                      names
                              fields.


    The “description” column allows
    you to enter a short comment
    about the field (this information
    is not processed in any way by
    Access).


    The “field properties” section
    allows you to enter information
    about the field and constraints on
    the values for the field.




                                                                  Home     Previous   6 o f 18     Next
2. Tables                                                                                         Tutorial exercises

2.3.3 Specifying the primary key
                                                             FIGURE 2.6: Set the field properties for the
Tables normally have a primary key that uniquely                        EmployeeID field.
identifies the records in the table. When you desig-
nate a field as the primary key, Access will not allow
you to enter duplicate values into the field.
  • Follow the steps in Figure 2.5 to set the primary
    key of the table to EmployeeID.

2.3.4 Setting field properties
In this section, you will specify a number of field
properties for the EmployeeID field, as shown in
Figure 2.6.
  • Since we are going to use the employees’ Social
    Insurance Number (S.I.N.) to uniquely identify
    them, set the Field Size property to 11 characters
    (9 for numbers and 2 for separating spaces)
  • Set the Input Mask property to the following:
    000 000 000;0
  • Set the Caption property to Employee ID


                                                                   Home      Previous      7 o f 18     Next


2. Tables                                                                                         Tutorial exercises


                        FIGURE 2.5: Set the primary key for the Employees table.



                                                               fields)on the greythe primary key.field (or
                                                                Click
                                                                        that form
                                                                                   box beside the



                                                                    To select more than one field for use as the
                                                                    primary key, hold down the Control key
                                                                    while clicking on the grey boxes.




                              select Edit the key-shaped from in the tool bar or
                               Either click
                                             Primary Key
                                                           icon
                                                                the menu.




                                                                   Home      Previous      8 o f 18     Next
2. Tables                                                                                                Discussion

 • Select View  Datasheet from the main menu to              three small dots ( ) to invoke the input mask
   switch to datasheet mode as shown in Figure 2.7.           wizard.
   Enter your own S.I.N. and observe the effect of          • Follow the instructions provided by the wizard as
   the input mask and caption on the EmployeeID               shown in Figure 2.8.
   field.                                                   • Press F1 while the cursor is still in the input mask
 • Select View  Table Design from the main menu              property. Scroll down the help window to find the
   to return to design mode.                                  meaning of the “0”, “9”, “” and “L” input mask
 • Set the field properties for FName and LName               symbols.
   (note that Length and Caption are the only two
   properties that are relevant for these two fields)     2.4 Discussion
2.3.5 Using the input mask wizard                         2.4.1 Key terminology
In this section, you will use the input mask wizard to    A key is one or more fields that uniquely determine
create a complex input mask for a standard field          the identity of the real-world object that the record is
type. You will also use the help system to learn more     meant to represent. For example, there is a record in
about the meaning of the symbols used to create           the student information system that contains infor-
input masks.                                              mation about you as a student. To ensure that the
  • Select the Phone field, move the cursor to the        record is associated with you and only you, it con-
    input mask property, and click the button with


                                                                    Home       Previous       9 o f 18   Next


2. Tables                                                                                                Discussion


   FIGURE 2.7: Observe the effect of the input mask and caption properties on the behavior of the
                               EmployeeID field during data entry


   numbers intovarious characters and
    Try entering
                 the EmployeeID
        field.
   If a caption is specified, it replaces the
                                                          done to clear the changes to the record.
                                                           Press the Escape key when you are

   field name in the field selector.
   Note that the input mask will not let you
   type any characters other than numbers
   from 0-9. In addition, the spaces between
   the groups of numbers are added
   automatically.
                                                    Input masks provide a relatively easy way to
                                                    avoid certain basic data input errors without
                                                    having to write complex error checking
                                                    programs. Note, however, that it is possible to
                                                    over-constrain a field so that users are unable to
                                                    enter legitimate values.




                                                                    Home       Previous      10 o f 18   Next
2. Tables                                                                                                Discussion


                     FIGURE 2.8: Use the input mask wizard to create an input mask.



  number” from the
   Select “phone

      list of commonly-
      used field types.

      The items in this
      list depend on the
      “international
      settings” specified
      for Windows (e.g.,
      “Zip Code” may
      show instead of                                                        Since the input mask controls how
      “Postal Code”).                                                        the information in the field looks, it
                                                                             is possible to save some disk space
                                                                             by storing the data without the
  edit the 2, youmask
   In Step
            input
                  may                                                        extras symbols, spaces, etc. For the
                                                                             size of system we are building,
      (e.g., remove the                                                      however, this savings is negligible.
      area code section).




                                                                   Home      Previous      11 o f 18     Next


2. Tables                                                                                                Discussion

tains a field called “student number” that is guaran-        nated key is made by joining together two or
teed to be unique.                                           more fields. Course numbers at UBC provide a
The advantage of using student number as a key               good example of a concatenated key made by
instead of some other field—like “student name”—is           joining together two fields: DeptCode and
that there may be more than one person with the              CrsNum. For example, department alone cannot
same first and last name. The combination of stu-            be the primary key since there are many courses
dent name and address is probably unique (it is              in each department (e.g., COMM 335, COMM
improbable that two people with the same name will           391). Similarly, course number cannot be used as
at the same address) but using these two fields as a         a key since there are many courses with the
key would be cumbersome.                                     same number in different departments (e.g.,
                                                             COMM 335, HIST 335, MATH 335). However,
Since the terminology of keys can be confusing, the
                                                             department and course number together form a
important terms are summarized below.
                                                             concatenated key (there is only one COMM 335).
1. Primary key — The terms “key” and “primary             3. Foreign key: In a one-to-many relationship, a
   key” are often used interchangeably. Since there          foreign key is a field (or fields) in the “child”
   may be more than one candidate key for an                 record that uniquely identifies the correct “parent”
   application, the designer has to select one: this is      record. For example, DeptCode and CrsNum in
   the primary key.                                          the Sections table are foreign keys since these
2. Concatenated key: The verb “concatenate”                  two keys taken together are the primary key of
   means to join together in a series. A concate-


                                                                   Home      Previous      12 o f 18     Next
2. Tables                                                                                              Discussion

   the Courses table. Foreign keys are identified in     In addition, you can use the comment field in the
   Access by creating relationships (see Tutorial 3).    table design window to document the meaning of
                                                         field names.
2.4.2 Fields and field properties
                                                                It is strongly recommended that you avoid all
2.4.2.1     Field names
                                                                non-alphanumeric characters whenever you
Access places relatively few restrictions on field              name a field or database object. Although
names and thus it is possible to create long, descrip-          Access will permit you to use names such as
tive names for your fields. The problem is that you             Customer#, non-alphanumeric characters
have to type these field names when building que-               (such as #, /, $, %, ~, @, etc.) may cause
ries, macros, and programs. As such, a balance                  undocumented problems later on.
should be struck between readability and ease of
typing. You are advised to use short-but-descriptive     2.4.2.2    Data types
field names with no spaces.                              The field's data type tells Access how to handle the
For example, in Section 2.3.2 you created a field        information in the field. For instance, if the data type
with name FName. However, you can use the caption        is date/time, then Access can perform date/time
property to provide a longer, more descriptive label     arithmetic on information stored in the field. If the
such as First name. The net result is a field name       same date is stored as text, however, Access treats
that is easy to type when programming and a field        it just like any other string of characters. Normally,
caption that is easy to read when the data is viewed.

                                                                   Home      Previous     13 o f 18   Next


2. Tables                                                                                              Discussion

the choice of data type is straightforward. However,        for use as a primary key when no other key is
the following guidelines should be kept in mind:            provided or is immediately obvious.
1. Do not use a numeric data type unless you are
                                                                Since an autonumber is really Long Integer
   going to treat the field as a number (i.e., perform
                                                                and since relationships can only be created
   mathematical operations on it). For instance, you
                                                                between fields with the same data type, it is
   might be tempted to store a person's student
                                                                important to remember that if an autonumber
   number as an integer. However, if the student
                                                                is used on the “one” side of a relationship, a
   number starts with a zero, then the first digit is
                                                                long integer must be used for the “many” side.
   dropped and you have to coerce Access into dis-
   playing it. Similarly, a UBC course number (e.g.,     2.4.2.3    “Disappearing” numbers in
   335) might be considered a number; however,                      autonumber fields
   since courses like 439B have to accommodated,
                                                         If, during the process of testing your application, you
   a numeric data type for the course number field is
                                                         add and delete records from a table with an auto-
   clearly inappropriate.
                                                         number key, you will notice that the deleted keys are
2. Access provides a special data type called Auto
                                                         not reclaimed.
   Number (Counter in version 2.0). An autonum-
   ber/counter is really a number of type Long Inte-     For instance, if you add records to your Customer
   ger that gets incremented by Access every time        table (assuming that CustID is an autonumber), you
   a new record is added. As such, it is convenient      will have a series of CustID values: 1, 2, 3… If you



                                                                   Home      Previous     14 o f 18   Next
2. Tables                                                                                                  Discussion

later delete customer 1 and 2, you will notice that           lutely no difference whether the first customer in your
your list of customers now starts at 3.                       customers table is CustID = 1 or 534.
Clearly, it would be impossible for Access to renum-          2.4.2.4   Input masks
ber all the customers so the list started at 1. What          An input mask is a means of restricting what the user
would happen, for instance, to all the printed
                                                              can type into the field. It provides a “template” which
invoices with CustID = 2 on them? Would they refer            tells Access what kind of information should be in
to the original customer 2 or the newly renumbered
                                                              each space. For example, the input mask LLLL
customer 2?                                                   consists of two parts:
       The bottom line is this: once a key is                 1. The right brace  ensures that every character
       assigned, it should never be reused, even if              the user types is converted into upper case.
       the entity to which it is assigned is subse-              Thus, if the user types comm, it is automatically
       quently deleted. Thus, as far as you are con-             converted to COMM.
       cerned, there is no way to get your customers          2. The characters LLLL are place holders for letters
       table to renumber from CustID = 1.                        from A to Z with blank spaces not allowed. What
                                                                 this means is that the user has to type in exactly
Of course, there is a long and complicated way to do             four letters. If she types in fewer than four or
it, but since used an autonumber in the first place,             types a character that is not within the A to Z
you do not care about the actual value of the key—               scope (e.g., , 7, %), Access will display an error
you just want it to be unique. In short, it makes abso-          message.

                                                                        Home     Previous     15 o f 18   Next


2. Tables                                                                                                  Discussion

There are a large number of special symbols used              The semicolon and zero at the end of this input mask
for the input mask templates. Since the meaning of            are important because, as the on-line help system
many of the symbols is not immediately obvious,               points out, an input mask value actually consists of
there is no requirement to remember the character             three parts (or “arguments”), each separated by a
codes. Instead, simply place the cursor on the input          semicolon:
mask property and press F1 to get help. In addition,            • the actual template (e.g., 000-0000),
the wizard can be used to provide a basic input mask            • a value (0 or 1) that tells Access how to deal with
which can later be modified.                                      literal characters, and
2.4.2.5     Input masks and literal values                      • the character to use as a place holder (showing
                                                                  the user how many characters to enter).
To have the input mask automatically insert a char-
                                                              When you use a literal character in an input mask,
acter (such as a space or a dash) in a field, use a
slash to indicate that the character following it is a lit-   the second argument determines whether the literal
                                                              value is simply displayed or displayed and stored in
eral.
                                                              the table as part of the data.
For example, to create an input mask for local tele-
                                                              For example, if you use the input mask 000-
phone numbers (e.g., 822-6109), you would use the
following template: 000-0000;0 (the dash is a lit-           0000;1, Access will not store the dash with the tele-
                                                              phone number. Thus, although the input mask will
eral value and appears automatically as the user
enters the telephone number).                                 always display the number as “822-6109”, the num-
                                                              ber is actually stored as “8226109”. By using the


                                                                        Home     Previous     16 o f 18   Next
2. Tables                                                                           Application to the assignment

input mask 000-0000;0, however, you are telling          2.5 Application to the assignment
Access to store the dash with the rest of the data.
                                                          You now have the skills necessary to implement your
      If you use the wizard to create an input mask,      tables.
      it asks you a simple question about storing lit-      • Create all the tables required for the assignment.
      eral values (as shown in Figure 2.8) and fills        • Use the autonumber data type (counter in version
      in the second argument accordingly. How-                2.0) for your primary keys where appropriate.
      ever, if you create the input mask manually,          • Specify field properties such as captions, input
      you should be aware that by default, Access             mask, and defaults where appropriate.
      does not store literal values. In other words,
                                                                 If you create an input mask for ProductID,
      the input mask 000-0000 is identical to the
                                                                 ensure you understand the implications of
      input mask 000-0000;1. This has impor-
                                                                 Section 2.4.2.5.
      tant consequences if the field in question is
      subject to referential integrity constraints (the    • Set the Default property of the OrderDate field
      value “822-6109” is not the same as                    so that the current date is automatically inserted
      “8226109”).                                            into the field when a new order is created (hint:
                                                             see the Date() function in the on-line help sys-
                                                             tem).




                                                                   Home      Previous    17 o f 18   Next


2. Tables                                                                           Application to the assignment

 • Do not forget to modify your Products table (the
   data types, lengths, and field properties of
   imported tables normally need to be fine tuned)
 • Populate (enter data into) your master tables. Do
   not populate your transaction tables.

      For the purpose of the assignment, the term
      “transaction” tables refers to tables that con-
      tain information about individual transactions
      (e.g., Orders, OrderDetails, Ship-
      ments, ShipmentDetails). “Master”
      tables, in contrast, are tables that either do
      not contain information about transactions
      (e.g., Customers) or contain only summary
      or status information about transactions (e.g.,
      BackOrders).




                                                                   Home      Previous    18 o f 18   Next
Access Tutorial 3: Relationships
3.1 Introduction: The advantage of                       1. Wasted space — Note that for COMM 290, the
    using tables and relationships                          same basic course information is repeated for
                                                            every section. Although the amount of disk space
A common mistake made by inexperienced data-
                                                            wasted in this case is trivial, this becomes an
base designers (or those who have more experience           important issue for very large databases.
with spreadsheets than databases) is to ignore the
                                                         2. Difficulty in making changes — What happens if
recommendation to model the domain of interest in           the name of COMM 290 is changed to “Mathe-
terms of entities and relationships and to put all the
                                                            matical Optimization”? This would require the
information they need into a single, large table.           same change to be made eight times. What if the
Figure 3.1 shows such a table containing information
                                                            person responsible for making the change for-
about courses and sections.
                                                            gets to change all the sections of COMM 290?
  • If you have not already done so, open the               What then is the “true” name of the course?
    univ0_vx.mdb database.
                                                         3. Deletion problems — What if there is only one
  • Open the Catalog View table.                            section of COMM 290 and it is not offered in a
The advantage of the single-table approach is that it       particular year? If section 001 is deleted, then the
requires less thought during the initial stages of          system no longer contains any information about
application development. The disadvantages are too          the course itself, including its name and number
numerous to mention, but some of the most impor-            of credits.
tant ones are listed below:

© Michael Brydon (brydon@unixg.ubc.ca)
Last update: 22-Aug-1997                                          Home       Previous     1 o f 10    Next


3. Relationships                                         Introduction: The advantage of using tables and relation-


   FIGURE 3.1: The “monolithic” approach to database design—the Catalog View table contains
                             information about courses and sections.


     The course “COMM 290” consists
     of many sections.


     Each section has some information
     unique to that section (such as
     Time, Days, Building,
     Room); however, the basic course
     information (e.g., Title,
     Credits) is the same for all
     sections of a particular course.




                                                                  Home       Previous     2 o f 10    Next
3. Relationships                                          Introduction: The advantage of using tables and relation-

4. Addition problems — If a new section is added to
                                                          FIGURE 3.2: A one-to-many relationship between
   any course, all the course information has to be
                                                                     Courses and Sections.
   typed in again. Not only is this a waste of time, it
   increases the probability of introducing errors into
   the system.

3.1.1 “Normalized” table design
The problems identified above can be avoided by
spitting the Catalog View table into two separate
tables:
1. Courses— information about courses only
2. Sections — information about sections only.            Access uses relationships in the following way:
The key to making this work is to specify a relation-     Assume you are looking at Section 004 of
ship between Courses and Sections so that when            COMM 290. Since Dept and CrsNum are included in
we look at a section, we know which course it             the Sections table, and since a relationship line
belongs to (see Figure 3.2). Since each course can        exists between the same two fields in the Courses
have one or more sections, such a relationship is         table, Access can trace back along this line to the
called “one-to-many”.                                     Courses table and find all the course-specific infor-
                                                          mation. All other sections of COMM 290 point back


                                                                   Home       Previous     3 o f 10    Next


3. Relationships                                                                               Learning objectives

to the same record in the Courses table so the             • Select Tools  Relationships from the main
course information only needs to be stored once.             menu.

3.2 Learning objectives
      Why do I want to represent my information in
                                                               In version 2.0 the menu structure is slightly
                                                                different. As such, you select Edit  Relation-
                                                                ships instead.
       multiple tables connected by relationships?
      How do I create relationships in Access?            • To add a table to the relationship window, select

      How do I edit or change relationships?
                                                             Relationships  Show Table from menu or press
                                                             the show table icon ( ) on the tool bar.
      What is referential integrity and why is it         • Perform the steps shown in Figure 3.3 to add the
       important?                                            Courses and Sections tables.
                                                           • Specify the relationship between the primary
3.3 Tutorial exercises                                       key in Courses and the foreign key in Sec-
                                                             tions. This is shown in Figure 3.4.
3.3.1 Creating relationships between
      tables                                                    Do not check cascading deletions or updates
 • Close the Catalog View table and return to                   unless you are absolutely sure what they
                                                                mean. See on-line help if you are curious.
   the database window.



                                                                   Home       Previous     4 o f 10    Next
3. Relationships                                                                                  Tutorial exercises


           FIGURE 3.3: Add the Courses and Sections tables to the relationship window.


       The rectangular “field list” represents a
       table. Note that the key (or keys) composing        double-click or presswish toRepeat aseither
                                                            Select the table you
                                                                                  Add.
                                                                                         add and
                                                                                                  necessary.
       the primary key are shown in bold type.




       If you accidently add a table more than once, it
       will show up with a table name_1 label.
       To delete the extra version, click anywhere on
       the unwanted rectangle and press the delete key.




                                                                  Home      Previous       5 o f 10        Next


3. Relationships                                                                                  Tutorial exercises


                       FIGURE 3.4: Create a relationship between the two tables.


   on the “one” side ofkey
    Select the primary
                         the                                           foreign key on thefields onsidethe the
                                                                        Drag the selected
                                                                                          “many”
                                                                                                    to
                                                                                                         of
       relationship.                                                       relationship.

       To select a concatenated
       key (more than one                                                                             If done
       field) hold down the                                                                           correctly, the
       Control key while                                                                              connectivity (1
       selecting.                                                                                     to ∞) shows on
                                                                                                      the relationship
                                                                                                      line(s).
      Ensure that the correct
       fields are associated
       with each other (this
       must be done manually
       for concatenated keys).

   enforcethe box to
    Check
            referential
       integrity.




                                                                  Home      Previous       6 o f 10        Next
3. Relationships                                                                                            Discussion

3.3.2 Editing and deleting relationships                           Note that simply deleting the table in the rela-
There are two common reasons for having to edit or                 tionship window does not delete the relation-
delete a relationship:                                             ship, it merely hides it from view.

1. You want to change the data type of one of the
                                                            3.4 Discussion
   fields in the relationship — Access will not let you
   do this without first deleting the relationship (after
                                                            3.4.1 One-to-many relationships
   you change the data type, you must re-create the
   relationship).                                           There are three types of relationships that occur in
2. You forget to specify referential integrity — if the     data modeling:
   “1” and “∞” symbols do not appear on the rela-           1. one-to-one — A one-to-one relationship exists
   tionship line, then you have not checked the box            between a student and a student number.
   to enforce referential integrity.                        2. one-to-many — A one-to-many relationship
In this section, assume that we have forgotten to              exists between courses and sections: each
enforce referential integrity between Courses and              course may consist of many sections, but each
Sections.                                                      section is associated with exactly one course.
  • Perform the steps shown in Figure 3.5 to edit the       3. many-to-many — A many-to-many relationship
    relationship between Courses and Sections.                 exists between students and courses: each stu-
                                                               dent can take many courses and each course
                                                               can contain many students.


                                                                     Home       Previous       7 o f 10     Next


3. Relationships                                                                                            Discussion


                                   FIGURE 3.5: Edit an existing relationship.

                                                                            The missing “1” and “∞” symbols
                                                                            indicate that referential integrity has
                                                                            not been enforced.
   the joiningrelationshipon either lineon
    Select the
                line (click
                            by clicking
                                          if
         the key is concatenated). If you do
         this correctly, the line becomes
         darker.


   click to get the edit/delete pop-up
    With the relationship selected, right-
         menu. If you do not get this menu,
         make sure you have correctly
         selected the relationship.




                                                                     Home       Previous       8 o f 10     Next
3. Relationships                                                                                        Discussion

Although the data modeling technique used most              “many” side of a relationship has a corresponding
often in information system development—Entity-             record on the “one” side.
Relationship diagraming—permits the specifica-              Enforcing referential integrity means that you cannot,
tion of many-to-many relationships, these relation-         for instance, create a new record in the Sections
ships cannot be implemented in a relational                 table without having a valid record in the Courses
database. As a consequence, many-to-many rela-              table. This is because having a section called
tionships are usually broken down into a series of          “BSKW 101 Section 001” is meaningless unless
one-to-many relationships via “composite entities”          there is a course called “BSKW 101”. In addition, ref-
(alternatively, “bridging tables”). Thus to implement       erential integrity prevents you from deleting records
the student-takes-course relationship, three tables         on the “one” side if related records exist on the
are used: Students, Courses, and Student-                   “many” side. This eliminates the problem of
TakesCourse.                                                “orphaned” records created when parent records are
                                                            deleted.
3.4.2 Referential integrity
                                                            Referential integrity is especially important in the
One important feature of Access is that it allows you       context of transaction processing systems. Imagine
to enforce referential integrity at the relationship        that someone comes into your store, makes a large
level. What is referential integrity? Essentially, refer-   purchase, asks you to bill customer number “123”,
ential integrity means that every record on the             and leaves. What if your order entry system allows
                                                            you to create an order for customer “123” without


                                                                     Home      Previous     9 o f 10    Next


3. Relationships                                                                      Application to the assignment

first checking that such a customer exists? If you                A primary key and a foreign key must be of
have no customer 123 record, where do you send                    the same data type before a relationship can
the bill?                                                         be created between them. Because of this, it
In systems that do not automatically enforce referen-             is important to remember that the autonumber
tial integrity, these checks have to be written in a pro-         data type (or counter in version 2.0) is really a
gramming language. This is just one example of how                long integer.
table-level features can save you enormous pro-
                                                                  It never makes sense to have a relationship
gramming effort.
                                                                  between two autonumber fields. A foreign key
       Enforcing referential integrity has obvious                cannot be an autonumber since referential
       implications for data entry: You cannot popu-              integrity constraints require it to take on a an
       late the “many” side of the table until you pop-           existing value from a parent table.
       ulate the “one” side.

3.5 Application to the assignment
 • Specify all relationships—including referential
   integrity constraints—between tables in your sys-
   tem. You are not responsible for cascading
   updates/deletions in this assignment.


                                                                     Home      Previous    10 o f 10    Next
Access Tutorial 4: Basic Queries Using QBE
4.1 Introduction: Using queries to                        Once a query is defined, it can be used in exactly the
    get the information you need                          same way as a table. Because of this, it is useful to
                                                          think of queries as “virtual tables”. Similarly, in some
At first glance, it appears that splitting information
                                                          DBMSes, queries are called “views” because they
into multiple tables and relationships creates more of    allow different users and different applications to
a headache than it is worth. Many people like to
                                                          have different views of the same data.
have all the information they need on one screen
(like a spreadsheet, for instance); they do not want to
                                                          4.2 Learning objectives
have to know about foreign keys and relationships
and so on.                                                      Do queries contain any data?

Queries address this problem. They allow the user to            How do I create a query?
join data from one or more tables, order the data in            What can I do with a query?
different ways, calculate new fields, and specify cri-
teria to filter out certain records.
                                                                How do I create a calculated field?

The important thing is that the query itself contains
                                                                Why does Access add square brackets
                                                                 around field names?
no data—it merely reorganizes the data from the
table (or tables) on which it is built without changing         What names should I give the queries I
the “underlying tables” in any way.                              create?
                                                                What does the ampersand operator () do?

© Michael Brydon (brydon@unixg.ubc.ca)
Last update: 25-Aug-1997                                            Home      Previous     1 o f 27     Next


4. Basic Queries Using QBE                                                                        Tutorial exercises

      What is a non-updatable recordset? How do I        4.3.2 Five basic query operations
       tell whether a query results in a non-
                                                          4.3.2.1   Projection
       updatable recordset?
                                                          Projecting a field into a query simply means includ-
4.3 Tutorial exercises                                    ing it in the query definition. The ability to base a
                                                          query on a subset of the fields in an underlying table
4.3.1 Creating a query                                    (or tables) is particularly useful when dealing with
                                                          tables that contain some information that is confiden-
 • Use the New button in the Queries pane of the
                                                          tial and some that is not confidential. For instance,
   database window to create a new query as
                                                          the Employees table you created in Tutorial 2 con-
   shown in Figure 4.1.
                                                          tains a field called Salary. However, most of the
 • Add the Courses table to the query as shown in
                                                          queries seen by end-users would not include this
   Figure 4.2.
                                                          information, thereby keeping it private.
 • Examine the basic elements of the query design
                                                            • Perform the steps shown in Figure 4.4 to project
   screen as shown in Figure 4.3.
                                                               the DeptCode, CrsNum, and Title fields into
 • Save your query (Control-S) using the name
                                                               the query definition.
   qryCourses.
                                                            • Select View  Datasheet from the menu to see
                                                               the results of the query. Alternatively, press the
                                                               datasheet icon ( ) on the tool bar.



                                                                    Home      Previous     2 o f 27     Next
4. Basic Queries Using QBE                                                                   Tutorial exercises


                                        FIGURE 4.1: Create a new query.



   the database window. in
    Select the Queries tab




   createthenew query. to
    Press
           a
              New button




       Avoid the use of the query wizard
       at this point. Queries are very
       important and it is best to learn to
       create them from scratch.




                                                                 Home     Previous    3 o f 27     Next


4. Basic Queries Using QBE                                                                   Tutorial exercises


                 FIGURE 4.2: Add tables to your query using the “show table” window.




   by selecting it and pressing Addquery
    Add the Courses table to the
       (alternatively, you can simply double-
       click on the table you want to add).

               table”Close when“modal”—you can
                Press
                      window is
                                 done (the “show                   The “show table” window is always
                                                                   available from the Query  Show Table
                     not do anything else in Access until a        menu. Alternatively, you can press the
                     modal window is closed).                      “show table” button on the tool bar.




                                                                 Home     Previous    4 o f 27     Next
4. Basic Queries Using QBE                                                                        Tutorial exercises


                       FIGURE 4.3: The basic elements of the query design screen.


  The upper                                    If you “lose” tables in the top
  pane contains                                pane, you have to use the
  field lists for                              horizontal and vertical scroll
  the tables on                                bars to return to the upper-left
  which the                                    corner of the pane.
  query is based.
                                                                         Field row— shows the name of the
                                                                         fields included in the query.

  The lower                                                              Table row— shows the name of the
  pane contains                                                          table that the field comes from. To get
  the actual                                                             table names in version 2.0, select View
  query                                                                   Table Names from the menu.
  definition.
                                                                         Sort row— allows you to specify the
                                                                         order in which the records are
         Criteria row — allows you        Show boxes— determine          displayed
         to specify criteria for          whether fields included
         including or excluding           in the query are actually
         records from the results set.    displayed.


                                                                  Home       Previous      5 o f 27     Next


4. Basic Queries Using QBE                                                                        Tutorial exercises


             FIGURE 4.4: Project a subset of the available fields into the query definition.


                                                             drag it the field querywish to project and
                                                              Select
                                                                      into the
                                                                                you
                                                                                      definition grid.
                                                                   Alternatively, double-click the field.

       To project all the fields in the
       Courses table (including
       any that might be added to the
       table after this query is
       created) drag the asterisk (*)
       into the query definition grid.



       To save time when
       projecting fields, select more
       than one field at once (by
       holding down the Control
       key) and dragging all the
       fields as a group.




                                                                  Home       Previous      6 o f 27     Next
4. Basic Queries Using QBE                                                                             Tutorial exercises

 • Select View  Query Design to return to design            4.3.2.3   Selection
   mode. Alternatively, press the design icon ( )            You select records by specifying conditions that each
   on the tool bar.                                          record must satisfy in order to be included in the
4.3.2.2     Sorting                                          results set. In “query-by-example” you enter exam-
                                                             ples of the results you desire into the criteria row.
When you use a query to sort, you do not change the
physical order of the records in the underlying table          • Perform the steps shown in Figure 4.6 to select
                                                                 only those courses with a DeptCode = “COMM”.
(that is, you do not sort the table). As a result, differ-
ent queries based on the same table can display the          4.3.2.4   Complex selection criteria
records in different orders.                                 It is also possible to create complex selection criteria
  • Perform the steps shown in Figure 4.5 to sort the        using Boolean constructs such as AND, OR, and
    results of qryCourses by DeptCode and                    NOT.
    CrsNum.                                                     • Project the Credits field into the query.
                                                                • Perform the steps shown in Figure 4.7 to create a
       Since a query is never used to display data to
                                                                  query giving the following result:
       a user, you can move the fields around within
                                                                  “Show the department, course number, and title
       the query definition to get the desired sorting
                                                                  of all courses in the Commerce department for
       precedence. You then reorder the fields in the
                                                                  which the number of credits is greater than
       form or report for presentation to the user.
                                                                  three.”



                                                                       Home       Previous      7 o f 27     Next


4. Basic Queries Using QBE                                                                             Tutorial exercises


                          FIGURE 4.5: Sorting the results set on one or more fields.



                            and “descending” for the CrsNum field.field
                             Select “ascending” for the DeptCode




                                                                              When multiple sort fields are specified,
                                                                              the sorting precedence is from left to
                                                                              right (e.g., DeptCode is sorted first
           the order of the records.
            View the results and notice                                       and then CrsNum is sorted within each
                                                                              set of matching DeptCodes).




                                                                       Home       Previous      8 o f 27     Next
4. Basic Queries Using QBE                                                                   Tutorial exercises


   FIGURE 4.6: Select a subset of records from the Courses table matching a specific criterion.




                                of the the expression “COMM”could also typerow
                                 Type
                                         DeptCode field. You
                                                              in the criteria

                                    = “COMM” but the equal sign is always implied
                                    unless another relational operator is used.


                                              matching results. Only records
                                               View the
                                                        the criteria are shown.




                                                             Home       Previous      9 o f 27     Next


4. Basic Queries Using QBE                                                                   Tutorial exercises


                       FIGURE 4.7: Select records using an AND condition.

                                                                    When multiple criteria are placed in the
                                                                    same row, they are AND-ed. In other
                                                                    words, the records in the results set
                              Show the result.                     must satisfy DeptCode = “COMM”
                                                                    AND Credits  3.


                                                                                     Note that the number
                                                                                     3 is not in quotation
                                                                                     marks whereas the
                                                                                     string of characters
                                                                                     “COMM” is.



                                                                                    Uncheck the “show”
                                                                                     box (Credits is
                                                                                     used as a criterion but
   “COMM” first criteria:
    Enter the
                                    the same row, enter the second
                                    In
                                       3
                                                                                     it is not displayed in
                                                                                     the results set)



                                                             Home       Previous     10 o f 27     Next
4. Basic Queries Using QBE                                                                     Tutorial exercises

 • Perform the steps shown in Figure 4.8 to create a     • Project Title from the Courses table and
   query giving the following result:                      DeptCode, CrsNum, Section and Catalog-
   “Show the department, course number, and title          Num from the Sections table (see Figure 4.9).
   of all courses from the Commerce department           • Follow the instructions in Figure 4.10 to move
   and also show those from the Creative Writing           CatalogNum to the far left of the query definition
   department for which the number of credits is           grid.
   greater than three.”                                 Access performs an automatic lookup of information
4.3.2.5     Joining                                     from the “one” side of the relationship whenever the
                                                        a valid value is entered into the foreign key of the
In Tutorial 3, you were advised to break you informa-
                                                        “many” side of the relationship. To see how this
tion down into multiple tables with relationships
between them. In order to put this information back     works, create a new section of “MUSC 105”:
                                                          • Scroll to the bottom of the query in datasheet
together in a usable form, you use a join query.
  • Close qryCourses.                                       mode and click on the department field.
  • Open the relationships window and ensure you          • Enter “MUSC”.
    have a relationship defined between Courses           • Enter “105” in the course number field.
    and Sections. If you do not, create one now (do     Once Access knows the DeptCode and CrsNum of
    not forget to enforce referential integrity).       a section, it can uniquely identify the course that the
  • Create a new query called qryCatalogNum             section belongs to (which means it also knows the
    based on the Courses and Sections tables.           values of Title, Credits, Activity, etc.)


                                                                 Home      Previous     11 o f 27    Next


4. Basic Queries Using QBE                                                                     Tutorial exercises


                       FIGURE 4.8: Select records using an AND and an OR condition.


          When multiple criteria are placed in
          different rows, then they are OR-ed. In
          other words, the records in the results set
          must satisfy DeptCode = “COMM”
          OR (DeptCode = “CRWR” AND
          Credits  3).




                                                                                        criterion in the
                                                                                         Enter the Credits

   DeptCode
    Enter the                                                                                 second row.
          criteria in
          different rows.




                                                                 Home      Previous     12 o f 27    Next
4. Basic Queries Using QBE                                                                  Tutorial exercises


                    FIGURE 4.9: Create a query that joins Courses and Sections.


   Note that the relationship betweeninto the query.
    Bring Courses and Sections
                                       the tables is
       inherited from the relationship window.




   the query definition.both tables into
    Project fields from




                                                              Home     Previous      13 o f 27    Next


4. Basic Queries Using QBE                                                                  Tutorial exercises


                       FIGURE 4.10: Move a field within the query definition grid.



                                                                              “column selector”grey
                                                                               Click once on the
                                                                                     above the field you
                                                                                     want to move (if
                                                                                     properly selected, the
                                                                                     column turns black).


                                                                                     To delete a field from
                                                                                     the query definition,
                                                                                     select it and press the
                                                                                     Delete key.




                                                         its new location. column to
                                                          Drag the selected




                                                              Home     Previous      14 o f 27    Next
4. Basic Queries Using QBE                                                                          Tutorial exercises

4.3.3 Creating calculated fields                            the expression involves two fields from the Courses
A calculated field is a “virtual field” in a query for      table (DeptCode and CrsNum) and the ampersand
which the value is a function of one or more fields in      operator (see Section 4.4.2 for more information on
the underlying table. To illustrate this, we will create    using the ampersand operator).
two calculated fields:                                        • Create a new query called qryCourseLengths
                                                                based on the Courses table.
1. one to combine DeptCode and CrsNum into one
                                                              • Follow the instructions in Figure 4.11 to create
   field,
                                                                the calculated field Course
2. one to translate the Credits field into a dichoto-
                                                              • Run the query to verify the results, as shown in
   mous string variable (full year or half
                                                                Figure 4.12.
   year).
The syntax of a calculated field is always the same:               When you use field names in expressions,
calc field name: definition                                    Access normally adds square brackets. This
For example, the syntax for the calculated field                   is not cause for concern because in Access,
called Course is:                                                  square brackets simply indicate the name of a
Course: DeptCode  CrsNum                                          field (or some other object in the Access envi-
                                                                   ronment). However, if your field name con-
The calculated field name can be just about any-
                                                                   tains blank spaces (e.g., Dept Code), the
thing, as long as it is unique. The definition is any
                                                                   square brackets are NOT optional—you must
expression that Access can evaluate. In this case,


                                                                      Home      Previous     15 o f 27       Next


4. Basic Queries Using QBE                                                                          Tutorial exercises


                     FIGURE 4.11: Create a calculated field based on two other fields.

                                               The zoom window provides more room to type than the tiny
                                               space in the query definition grid. Invoke the zoom window
                                               by moving to the area of the grid in which you wish to type
                                               and either right-click or press the Shift-F2 keys.




       the Field row of
        Put the cursor in

            the first column
            and invoke the
            zoom window.


       and the definition
        Type in the name
                                                                  Press OK when you
            of the calculated                                      have finished typing
            field. The name                                        the expression.
            cannot be the same
            as that of an
            existing field.


                                                                      Home      Previous     16 o f 27       Next
4. Basic Queries Using QBE                                                                          Tutorial exercises


                                   FIGURE 4.12: The resulting calculated field.


                                                                                         The name of the
                                                                                         calculated field shows in
                                                                                         the field selector.



          When the zoom window is
          closed, Access adds square
          brackets to the field names.
          Since the field names in this
          example do not contain
          spaces, the brackets are
          optional.



                                                                     The ampersand operator () simply tacks
                                                                     CrsNum onto the end of DeptCode.




                                                                    Home      Previous       17 o f 27    Next


4. Basic Queries Using QBE                                                                          Tutorial exercises

       type them every time you use the field name        three credits is a full-year course). To do this, we will
       in an expression.                                  use the “immediate if” (iif) function.
                                                            • Search on-line help for information about the
4.3.3.1     Refining the calculated field                     iif() function.
Instead of having DeptCode and CrsNum run                 Basically, the function uses the following syntax:
together in the new Course field, you may prefer to
                                                             iif(expression, true part,
have a space separating the two parts.                        false part)
  • Edit the Courses field by clicking on the field row
                                                          to implement the following logic:
    and invoking the zoom box.
                                                              IF expression = TRUE THEN
  • Add a space (in quotation marks) between the
                                                                 RETURN true part
    two constituent fields:
                                                              ELSE
    Course: DeptCode  ” ”  CrsNum
                                                                 RETURN false part
  • Switch to datasheet mode to see the result.
                                                              END IF
4.3.3.2     A more complex calculated field                 • Create a new calculated field called Length:
To create a calculated field that maps Credits to a           Length: iif(Credits  3, “full
dichotomous string variable, we need a means of               year”, “half year”)
testing whether the value of Credits exceeds a              • Verify the results, as shown in Figure 4.13.
certain threshold (e.g., any course with more than



                                                                    Home      Previous       18 o f 27    Next
4. Basic Queries Using QBE                                                                     Tutorial exercises


                FIGURE 4.13: Create a calculated field using the “immediate if” function


         Length: iif(Credits3, “fullwith the following expression:
          Create a calculated field called Length
                                                  year”, “half year”)




                                                                  Home      Previous    19 o f 27    Next


4. Basic Queries Using QBE                                                                            Discussion

4.3.4 Errors in queries                                  4.4 Discussion
It may be that after defining a calculated field, you
get the “enter parameter” dialog box shown in            4.4.1 Naming conventions for database
Figure 4.14 when you run the query. This occurs                objects
when you spell a field name incorrectly. Access can-     There are relatively few naming restrictions for data-
not resolve the name of the misspelled field and thus    base objects in Access. However, a clear, consistent
asks the user for the value. To eliminate the problem,   method for choosing names can save time and avoid
simply correct the spelling mistake.                     confusion later on. Although there is no hard and fast
  FIGURE 4.14: A spelling error in a calculated          naming convention required for the assignment, the
                    field.                               following points should be kept in mind:
                                                           • Use meaningful names — An object named
                                                             Table1 does not tell you much about the con-
                             Access cannot find the          tents of the table. Furthermore, since there is no
                             field named Creditz             practical limit to the length of the names, you
                                                             should not use short, cryptic names such as
                                                             s96w_b. As the number of objects in your data-
                                                             base grows, the time spent carefully naming your
                                                             objects will pay itself back many times.



                                                                  Home      Previous    20 o f 27    Next
4. Basic Queries Using QBE                                                                            Discussion

 • Use capitalization rather than spaces to separate      • Stick to standard alphanumeric characters — You
   words — Unlike many database systems, Access             should limit yourself to the characters [A...Z],
   allows spaces in object names. However, if you           [a...z], [0...9], and perhaps underscore (_) and
   choose to use spaces, you will have to enclose           dash (-). Although Access allows you to use virtu-
   your field names in square brackets whenever             ally any character, undocumented problems have
   you use them in expressions (e.g., [Back                 been encountered in the past with non-alphanu-
   Orders]). As such, it is slightly more efficient to      meric characters such as the pound sign (#).
   use a name such as BackOrders than Back               Table 4.1 shows a suggested naming convention for
   Orders.                                               Access database objects (you will discover what
 • Give each type of object a distinctive prefix (or     these objects are in the course of doing the tutorials).
   suffix) — This is especially important in the con-
   text of queries since tables and queries cannot       4.4.2 The ampersand () operator
   have the same name. For example, you cannot
                                                         The ampersand operator is like any other operator
                                                         (e.g., +, -, ×, ÷) except that it is intended for use on
   have a table named BackOrders and a query
   named BackOrders. However, if all your query
                                                         strings of characters. What the ampersand does is
   names are of the form qryBackOrders, then
                                                         simply add one string on to the end of another string
   distinguishing between tables and queries is
                                                         (hence its other name: the “concatenation” operator).
   straightforward.
                                                         For example, the expression
                                                            “First string”  “Second string”


                                                                  Home       Previous     21 o f 27   Next


4. Basic Queries Using QBE                                                                            Discussion

 Table 4.1: A suggested naming convention for            yields the result
            Access database objects.                        First stringSecond string
                                                         However, if a space is include within the quotation
 Object type    Prefix            Example                marks of the second string (“ Second string”),
table          (none) OrderDetails                       the result is:
query          qry       qryNonZeroBackOrders               First string Second string
parameter      pqry      pqryItemsInOrder
query                                                    4.4.3 Using queries to populate tables
form           frm       frmOrders                             on the “many” side of a
                                                               relationship
sub form       sfrm      sfrmOrderDetails
                                                         In Section 4.3.2.5, you added a record to the Sec-
switchboard    swb       swbMainSwitchboard
form                                                     tions table to demonstrate the automatic lookup
                                                         feature of Access. However, a common mistake
report         rpt       rptInvoice
                                                         when creating queries for entering data into tables
sub report     srpt      srptInvoiceDetails              on the “many” side of a relationship is to forget to
macro          mcr       mcrOrders                       project the table’s foreign key. That is, faced with two
Visual Basic   bas       basUtilities                    tables containing the fields DeptCode and CrsNum,
module                                                   you project the fields from the wrong table (the “one”
                                                         side) into your query definition.


                                                                  Home       Previous     22 o f 27   Next
4. Basic Queries Using QBE                                                                          Discussion

To illustrate the problem, do the following:           4.4.4 Non-updatable recordsets
 • Open the qryCatalogNum query and make the           Another problem that sometimes occurs when creat-
    changes shown in Figure 4.15.                      ing join queries is that the query is not quite right in
 • Attempt to save the new section of “MUSC 105”       some way. In such cases, Access will allow you to
    as shown in Figure 4.16.                           view the results of the query, but it will not allow you
There are two ways to avoid this error when deciding   to edit the data.
which fields to project into your join queries:        In this section, will look at a nonsensical query that
1. Always show the table names when creating a         results from an incompletely specified relationship.
   query based on more than one table. That way,       As you will probably discover, however, there are
   you can quickly determine whether the query         many different way to generate nonsensical queries.
   makes sense.                                          • Create a new query called qryNonUpdate
2. Always ask yourself: “What is the purpose of this       based on the Courses and Sections tables.
   query?” If the answer is: “To add new records to      • Delete the CrsNum relationship but leave the
   the Sections table,” you automatically have to          DeptCode relationship intact, as shown in
   include all the fields from the Sections table.         Figure 4.17.
   Fields from the Courses table are only shown        The result of this query is that every section in a
   for validation purposes.                            Commerce course will be associated with every
                                                       Commerce course. Since allowing the user to update



                                                                Home       Previous    23 o f 27    Next


4. Basic Queries Using QBE                                                                          Discussion


                      FIGURE 4.15: Create a data-entry query without a foreign key.




                                                                            In version 2.0 you have to
       Reorder the fields (by
        dragging and dropping) so
                                                                            select View  Table
                                                                            Names to display the
        that DeptCode and                                                   table row.
        CrsNum are on the far left.


   DeptCodesource table for
    Change the
               and CrsNum
        from Sections to
        Courses.


       Switch to datasheet mode
        and attempt to add a new
        section of “MUSC 105”.




                                                                Home       Previous    24 o f 27    Next
4. Basic Queries Using QBE                                                                              Discussion


     FIGURE 4.16: The result of attempting to save a record in which the foreign key is missing




                                                                                Since the fields are bound to the
                                                                                Courses table, you are
                                                                                attempting to replace the
                                                                                current record in the Courses
                                                                                table with “MUSC 105”. But
                                                                                since a “MUSC 105” already
                                                                                exists, you get an error.




    new sectionsave the
     Attempt to
                 by
         clicking its record
         selector.




                                                                 Home       Previous      25 o f 27     Next


4. Basic Queries Using QBE                                                                              Discussion


                               FIGURE 4.17: Create a non-updatable recordset.


                                                               view thefields fromdatasheet mode
                                                                Project
                                                                          query in
                                                                                    both tables and
                                                                    (i.e., view the “recordset”).




                                                                                             Attempt to
                                                                                              change a value in
                                                                                              the recordset.




   CrsNum relationship byquery, deleteitthe
    To create a nonsensical
                            clicking on              Note the absence of the asterisk and the “new record”
       and pressing the Delete key. Leave the        row. This is a sure sign that the recordset is non-updatable.
       DeptCode relationship intact.

                                                                 Home       Previous      26 o f 27     Next
4. Basic Queries Using QBE                                                     Application to the assignment

the values in this recordset would create anomalies,     should appear automatically. If they do not, see
Access designates the recordset as non-updatable.        Section 4.4.3.
                                                       • Create a calculated field in your qryOrderDe-
      A common mistake is to build data entry            tails query that calculates the extended price
      forms on nonsensical queries and to assume         (quantity shipped × price) of each order detail.
      that there is a mistake in the form when the     • Enter the first order into your system by entering
      forms do not work. Clearly, if a query is non-     the information directly into tables or queries.
      updatable, a form based on the query is also       This involves creating a single Orders record
      going to be non-updatable. A quick check for       and several OrderDetails records. You must
      a “new record” row in the query can save time      also consult the Products and BackOrders
      and frustration.                                   tables to determine the quantity of each item to
                                                         ship.
4.5 Application to the assignment
 • Create a query to sort the Products table by             Entering orders into your system will be much
   ProductID.                                               less work once the input forms and triggers
 • Create a query that joins the OrderDetails               are in place. The goal at this point is to get
   and Products tables. When you enter a valid              you thinking about the order entry process
   ProductID, the information about the product             and ways in which it can be automated.
   (such as name, quantity on hand, and so on)



                                                              Home      Previous     27 o f 27   Next
Access Tutorial 5: Basic Queries using SQL
5.1 Introduction: The difference                           Although you normally use QBE in Access, the ubiq-
    between QBE and SQL                                    uity of SQL in organizations necessitates a brief
                                                           overview.
Query-By-Example (QBE) and Structured Query
Language (SQL) are both well-known, industry-stan-
                                                           5.2 Learning objectives
dard languages for extracting information from rela-
tional database systems. The advantage of QBE (as                What is the difference between QBE and
you saw in Tutorial 4) that it is graphical and rela-             SQL?
tively easy to use. The advantage of SQL is that it              How do I create an SQL query?
has achieved nearly universal adoption within the
relational database world.                                 5.3 Tutorial exercises
With only a few exceptions (which you probably will        In this section, you will create a few simple queries in
not encounter in this assignment) QBE and SQL are          SQL.
completely interchangeable. If you understand the            • Create a new query but close the “show table”
underlying concepts (projection, selection, sorting,           dialog box with out adding tables.
joining, and calculated fields) of one, you understand       • Select View  SQL to switch to the SQL editor as
the underlying concepts of both. In fact, in Access            shown in Figure 5.1.
you can switch between QBE and SQL versions of
your queries with the click of a mouse.

© Michael Brydon (brydon@unixg.ubc.ca)
Last update: 22-Aug-1997                                            Home       Previous      1 of 5     Next


5. Basic Queries using SQL                                                                        Tutorial exercises

                                                           2. … FROM table … — specifies the underlying
     FIGURE 5.1: Open a query in SQL mode                     table (or tables) for the query;
                                                           3. … WHERE condition1 AND/OR
                                                              condition2, …, AND/OR conditionn —
                                                              specifies one or more conditions that each record
                                                              must satisfy in order to be included in the results
                                                              set;
                                                           4. ; (semicolon) — all SQL statements must end
                                                              with a semicolon (but if you forget it, Access will
                                                              add it for you).
5.3.1 Basic SQL queries                                    These can now be put together to build an SQL
A typical SQL statement resembles the following:           query:
SELECT DeptCode, CrsNum, Title FROM                         • Type the following into the SQL window:
Courses WHERE DeptCode = “COMM”;                              SELECT DeptCode, CrsNum, Title FROM
There are four parts to this statement:                       Courses WHERE DeptCode = “COMM”;
                                                            • Select View  Datasheet to view the results.
1. SELECT field1, field2, …, fieldn …
   — specifies which fields to project (the DIS-            • Select View  Query Design to view the query in
                                                              QBE mode, as shown in Figure 5.2.
   TINCTROW predicate shown in Figure 5.1 is
   optional and will not be discussed in this tutorial);    • Save your query as qryCoursesSQL.


                                                                    Home       Previous      2 of 5     Next
5. Basic Queries using SQL                                                                      Tutorial exercises


                       FIGURE 5.2: The SQL and QBE views are interchangeable.




       When you return to SQL mode
       after viewing your query in QBE
       mode, you will notice that Access
       has added some additional text.
       This optional text does not
       change the query in any way




                                                                    Home      Previous     3 of 5     Next


5. Basic Queries using SQL                                                                      Tutorial exercises

5.3.2 Complex WHERE clauses                                5.3.3 Join queries
You can use AND, OR, and NOT conditions in your            Join queries use the same elements as a basic
WHERE clauses in a straightforward manner.                 select query. The only difference is that the FROM
 • Change your query to the following to get all           statement is replaced with a statement that
   Commerce courses with more than three credits:          describes the tables to be joined and the relationship
   SELECT DeptCode, CrsNum, Title                          (i.e., foreign key) between them:
   FROM Courses                                               ... FROM table1 INNER JOIN table2 ON
   WHERE DeptCode = “COMM” AND Credits                         table1.field1 = table2.field2 ...
     3                                                    Note that since both tables contain the fields Dept-
                                                           Code and CrsNum, the table name.field
      Note that since DeptCode is a text field, its
                                                           name notation must be used to remove any ambi-
      criterion must be a string (in this case, the lit-
                                                           guity.
      eral string “COMM”). However, Credits is a
                                                            • Create a new SQL query containing the text:
      numeric field and its criterion must be a num-
                                                              SELECT Courses.DeptCode,
      ber (thus, there cannot be quotation marks
                                                               Courses.CrsNum, Courses.Title,
      around the 3).
                                                               Sections.CatalogNum
                                                              FROM Courses INNER JOIN Sections ON
                                                               Courses.CrsNum = Sections.CrsNum




                                                                    Home      Previous     4 of 5     Next
5. Basic Queries using SQL                                                         Discussion

    AND Courses.DeptCode =
    Sections.DeptCode
   WHERE Courses.DeptCode=”COMM”;

5.4 Discussion
Although the syntax of SQL is not particularly diffi-
cult, writing long SQL queries is tedious and error-
prone. For this reason, you are advised to use QBE
for the assignment.
In the real world, however, when you say you know
something about databases, it usually implies you
know the “data definition” and “data manipulation”
aspects of SQL in your sleep. If you plan to pursue a
career in information systems, a comprehensive
SQL reference book can be a worthwhile investment.




                                                        Home   Previous   5 of 5   Next
Access Tutorial 6: Form Fundamentals
6.1 Introduction: Using forms as                            FIGURE 6.1: The relationship between forms,
    the core of an application                                          queries, and tables.
Forms provide a user-oriented interface to the data
in a database application. They allow you, as a                                                           forms
developer, to specify in detail the appearance and
behavior of the data on screen and to exert a certain
amount of control over the user’s additions and mod-                                                     queries
ifications to the data.
Like queries, forms do not contain any data. Instead,
they provide a “window” through which tables and                                                          tables
queries can be viewed. The relationship between               Courses   Departments      Employees
tables, queries, and forms is shown in Figure 6.1.
In this tutorial, we are going to explore the basic ele-
ments of form creation using Access’ form design           6.2 Learning objectives
tools. In subsequent tutorials, we will extend the               Do forms contain data?
functionality and ease-of-use of our basic forms with
subforms (Tutorial 7), “combo box” controls
                                                                 How do I create a form?

(Tutorial 8), and triggers (Tutorial 13).

© Michael Brydon (brydon@unixg.ubc.ca)
Last update: 24-Aug-1997                                            Home      Previous      1 o f 15     Next


6. Form Fundamentals                                                                               Tutorial exercises

      How do I make the contents of a field on a           • Create a new blank form based on the Courses
       form read-only?                                        table, as shown in Figure 6.2.
      What is an unbound text box? How do I create         • The basic elements of the design screen are
       one?                                                   shown in Figure 6.3. Use the View menu to dis-

      How do I create a form using the form wizard?
                                                              play the toolbox and field list if they are not
                                                              already visible.
      What is the difference between a columnar
                                                           6.3.1.1 Adding bound text boxes
       (single-column) and tabular form?
                                                             • Add a “bound” text box for the DeptCode field by
                                                               dragging DeptCode from the field list to the form
6.3 Tutorial exercises                                         background, as shown in Figure 6.4.
                                                             • Reposition the DeptCode text box in the upper
6.3.1 Creating a form from scratch                             left of the form.
Although Access provides an excellent wizard for
creating simple forms, you will start by building a               Remember that you can always use the
form from scratch. This will give you a better appreci-           “undo” feature to reverse mistakes. Select
ation of what it is the wizard does and provide you               Edit  Undo from the menu or simply press
with the basic knowledge needed to customize and                  Control-Z (this works the same in virtually all
refine the wizard’s output.                                       Windows applications).




                                                                    Home      Previous      2 o f 15     Next
6. Form Fundamentals                                                                              Tutorial exercises


                FIGURE 6.2: Create a new form to display data from the Courses table.




   the database window. from
    Select the Forms tab




      use theDesign at this (do not
       Select
              wizard
                     View
                             point)
                                                                                           Bind the form to the
                                                                                            Courses table.




       Since you can build a form on top of a table or a
       query, both are shown in this list (here is where a
       meaningful naming convention starts to pay off)


                                                                       Home    Previous    3 o f 15     Next


6. Form Fundamentals                                                                              Tutorial exercises


                       FIGURE 6.3: The basic elements of the form design screen.




                 To change the size of
                 the form, drag the edges
                 of the detail section.




  The field list — shows the fields     The toolbox — the icons in the               If the field list and toolbox
  in the table or query to which the    toolbox are used to create graphical         are not displayed, use the
  form is bound.                        items and controls on the form.              View menu or toolbar icons.


                                                                       Home    Previous    4 o f 15     Next
6. Form Fundamentals                                                                                       Tutorial exercises


                          FIGURE 6.4: Create a bound text box for the DeptCode field.

          Access uses the field’s caption property as the default label for the text box.
          If no caption is specified, the field name (e.g., DeptCode) is used. To save
          time editing labels, choose your captions with this feature in mind.


                                                                                        to thethe highlightedsection.on
                                                                                         Drag
                                                                                                form’s detail
                                                                                                                field


          To move an object and its
          label, drag the center of the
          object (the cursor becomes
          a white arrow). To move
          just the object or just the
          label, drag the upper left
          handle (the cursor becomes
          a pointing finger).
                                           field inthe DeptCode
                                            Select
                                                     the field list.




                                                                            Home       Previous     5 o f 15     Next


6. Form Fundamentals                                                                                       Tutorial exercises

 • Drag the remaining fields on to the form, as                    • Scroll down the property sheet to the Locked
   shown in Figure 6.5 (do not worry about whether                   property and set it to Yes, as shown in
   the fields are lined up perfectly).                               Figure 6.7.
 • Select View  Form to see the resulting form.                   • Switch to the form view and attempt to change
   Alternatively, press the form view icon ( ).                      the contents of the DeptCode field.
 • Select View  Form Design or press the design                 A stronger form of protection than locking a field is
   view icon ( ) to return to design mode.                       “disabling” it.
6.3.1.2     Using a field’s properties to protect its              • Return to design mode and make the following
            contents                                                 changes: reset the Locked property to No; set the
Every object on an Access form (e.g., text box, label,               Enabled property to No.
                                                                   • Attempt to change the contents of the DeptCode
detail section, etc.) has a set of properties that can
be modified. In this section, you are going to use the               field in form view, as shown in Figure 6.8.
                                                                   • Save the form as frmCourses.
Locked and Enabled properties to control the user’s
ability to change the information in a field.                    6.3.1.3     Adding an unbound text box
 • Select the DeptCode text box and right-click to               All the text boxes created in the previous section
    bring up its property sheet, as shown in                     were “bound” text boxes—that is, they were bound to
    Figure 6.6.                                                  a field in the underlying table or query. When you
                                                                 change the value in a bound text box, you are mak-



                                                                            Home       Previous     6 o f 15     Next
6. Form Fundamentals                                                                                 Tutorial exercises


         FIGURE 6.5: Add the text boxes and switch to form view to see the resulting form.


                                                                                     Text boxes are simply
                                                                                     “windows” on to the fields
                                                                                     in the underlying table.




   fieldsthe the form.
    Add
           to
              remaining                                  main menu toview the form.
                                                          Select View Form from the




       You can add more than one field to the form with one
       drag-and-drop operation by holding down the Control
       button when selecting the fields from the field list.


                                                                   Home       Previous        7 o f 15     Next


6. Form Fundamentals                                                                                 Tutorial exercises


                 FIGURE 6.6: Bring up the property sheet for the DeptCode text box.


                                                       object to getoncepop-up selected
                                                        Right-click
                                                                      the
                                                                          on the
                                                                                 menu.


                                                              Select Properties to get the
                                                               property sheet.




   DeptCode text box) for
    Select the object (e.g., the                                                 The properties are broken down
                                                                                 into four groups. To see all the
       which you wish to see the                                                 properties, select the All tab.
       properties. When an object
       has been selected, it is
       bordered by six dark
       “handles”.                                              Some properties of the text box (such as
                                                               input mask) are inherited from the field
                                                               to which the text box is bound.


                                                                   Home       Previous        8 o f 15     Next
6. Form Fundamentals                                                                      Tutorial exercises

                                                  ing the change directly to the data in the underlying
  FIGURE 6.7: Change the Locked property of
                                                  table.
              DeptCode to Yes.
                                                  It is possible, however, to create objects on forms
                                                  that are not bound to anything. Although you will not
                                                  use many “unbound” text boxes in the assignment, it
                                                  is instructive to see how they work.
                                                     • Create a new empty form bound to the Courses
                                                       table and save it using the name
                                                       frmCoursesUB.
                                                     • Select the text box tool ( ) from the toolbox and
                                                       create and unbound text box, as shown in
                                                       Figure 6.9.
                                                  6.3.1.4   Binding an unbound text box to a field
                                                  The only difference between a bound and an
                                                  unbound text box is that the Control Source property
                                                  of a bound text box is set to the name of a field. In
                                                  this section, you are going to change the unbound
      the Locked property.find
       Use the scroll bar to
                                                  text box shown in Figure 6.9 to a bound text box.



                                                            Home     Previous      9 o f 15     Next


6. Form Fundamentals                                                                      Tutorial exercises


  FIGURE 6.8: Set the Enabled property of DeptCode to No and attempt to change the value in the
                                              field.

                                               Enabled to No. and
                                                Set Locked to No




                                               to see the result.view
                                                Switch to form


                                                                     When a form object is disabled, it
                                                                     cannot receive the “focus” (that is,
                                                                     you cannot put the cursor on it).


                                                                     By default, disabled form objects are
                                                                     greyed out. To override this feature,
                                                                     set the Locked property to Yes and
                                                                     the Enabled property to No.




                                                            Home     Previous      10 o f 15    Next
6. Form Fundamentals                                                                    Tutorial exercises

                                                  • Bring up the property sheet for the unbound text
  FIGURE 6.9: Create an unbound text box.
                                                    box. Change its Control Source property from null
                                                    to DeptCode, as shown in Figure 6.10.
    The cursortext box toolsmall texttoolbox.
     Select the
                becomes a
                             from the
                                       box.
                                                 6.3.2 Creating a single-column form
                                                       using the wizard
                                                 Now that you understand the basics of creating and
                                                 modifying bound text boxes, you can rely on the form
                                                 wizard to create the basic layout of all your forms.
                                                  • Create a new form bound to the Courses table
                                                    using the form wizard, as shown in Figure 6.11.
                                                  • Use the form wizard to specify the fields you want
                                                    on your form and the order in which they appear,
         detail section to create a
          Click anywhere on the
                                                    as shown in Figure 6.12. Select “columnar” when
             new unbound text box.                  prompted for the form type.


                                                      “Columnar” forms are called “single column”
                                                       forms in version 2.0.




                                                          Home      Previous     11 o f 15    Next


6. Form Fundamentals                                                                    Tutorial exercises


FIGURE 6.10: Set the Control Source property     FIGURE 6.11: Create a new form using the form
          of an unbound text box.                                   wizard.




                                                    wizard.the form
                                                     Select




                                                                                Courses table. the
                                                                                 Bind the form to



      the Control Source property
       Use the pull-down list to set

          to DeptCode.



                                                          Home      Previous     12 o f 15    Next
6. Form Fundamentals                                                                            Tutorial exercises


            FIGURE 6.12: Use the form wizard to determine the order of fields on your form.




                                                                                          The order in which
                                                                                          the fields appear in
                                                                                          this pane is the order
                                                                                          in which they will
                                                                                          appear on the form.
                                                                                          Use the  and 
                                                                                          buttons to move
                                                                                          fields back to the
                                                                                          pane on the left.
        to show a field, either double-
        click it or press the  button.

        To show all the fields, press the
         button.




                                                                   Home      Previous    13 o f 15    Next


6. Form Fundamentals                                                                                   Discussion

The primary advantage of the wizard is that it auto-      look and behavior of the data. The three different
matically creates, formats, and aligns the bound text     types of forms are shown in Figure 6.13.
boxes. Of course, once the wizard has created a
form, you are free to modify it in any way.               6.5 Application to the assignment
                                                           • Use the wizard to create columnar forms for all
       If you make a mistake when creating a form            your master tables. Note that in some cases
       (e.g., you put the fields in the wrong order) it      (e.g., BackOrders) you will want to base the
       is often easier to use the wizard and start over      form on a join query rather than table in order to
       than to fix the problem manually.                     show important information such as CustName
                                                             and ProductName.
6.4 Discussion
6.4.1 Columnar versus tabular versus
      datasheet forms
Columnar forms show one record per page. Tabular
forms, in contrast, show many records per page and
are used primarily as subforms. There is also a a
datasheet form type, but it is seldom used since it
gives the developer relatively little control over the


                                                                   Home      Previous    14 o f 15    Next
6. Form Fundamentals                                                      Application to the assignment


      FIGURE 6.13: The same information displayed as a columnar, tabular, and datasheet form.

                                                                   A columnar form displays
                                                                   one record per page.




 A tabular form
 displays more than
 one record per page.



 A datasheet form is identical to the datasheet
 view of a table or query. Since it gives the
 designer very little control over the format of the
 data, it is generally inappropriate for use in an
 end-user application.

                                                           Home    Previous    15 o f 15      Next
Access Tutorial 7: Subforms
7.1 Introduction: The advantages of                          fact, there is no need to show DeptCode and
    forms within forms                                       CrsNum in the subform).
                                                         Although you will quickly learn to take a feature such
A columnar/single-column main form with a tabular
                                                         as form/subform synchronization for granted, it is
subform is a natural way of representing information
from tables with a one-to-many relationship. For         worthwhile to consider what this feature does and
                                                         what it would take if you had to implement the same
example, the form shown in Figure 7.1 is really two
forms: the main form contains information about a        feature using a programming language.
specific course; the subform shows all the sections
associated with the course.                              7.2 Learning objectives
In the Courses and Sections example, the foreign                What is form/subform synchronization?
key (DeptCode and CrsNum) provides a link                       How do I create a form/subform combination?
between the two forms. This connection allows
Access to synchronize the forms, meaning:
                                                                How do I link a form with a subform?

  • when you move to another course record, only
                                                         7.3 Tutorial exercises
    the relevant sections are shown in the subform;
  • when you add a new section, the foreign key in       Although there are a number of different ways to cre-
    the Sections table is automatically filled in (in    ate a subform within a main form, the recommended
                                                         procedure is the following:


© Michael Brydon (brydon@unixg.ubc.ca)
Last update: 25-Aug-1997                                           Home      Previous      1 o f 19       Next


7. Subforms                                                                                       Tutorial exercises


                                FIGURE 7.1: A typical form/subform combination.


                                                    Because a link is established between the main form
                                                    and the subform, only the sections that belong with
                                                    “COMM 351” are displayed in the subform.

   The main part of the form is
   columnar (one record per page)
   and displays information from
   the Courses table.




   The subform is a separate
   tabular form that displays
   information from the
   Sections table.




                                                                   Home      Previous      2 o f 19       Next
7. Subforms                                                                                      Tutorial exercises

1. create and save both forms (one columnar, one            space they occupy. A number of editing issues
   tabular) separately;                                     are highlighted in Figure 7.5.
2. drag the subform on to the main form; and,             • Save the form as sfrmSections and close it.
3. verify the linkage between the two forms.
                                                        7.3.3 Linking the main form and subform
7.3.1 Creating the main form                            In this section, you are going to return to the main
 • Use the wizard to create a columnar form based       form and drag the saved subform from the database
   on the Courses table.                                window to an appropriate position on the main form.
 • Rearrange the fields so that they make efficient       • Open the main form (frmCoursesMain) in
   use of the top part of the form, as shown in             design mode.
   Figure 7.2.                                            • Select Window  univ0_vx: Database to open the
 • Save the form as frmCoursesMain.                         database window in the foreground. Alternatively,
                                                            you can press the database window icon ( ) on
7.3.2 Creating the subform                                  the tool bar.
 • Use the wizard to create the subform, as shown         • Perform the steps shown in Figure 7.6 to drag the
   in Figure 7.3 and Figure 7.4.                            subform on to the main form.
 • Subforms created by the wizard typically require       • The result of the drag-and-drop operation are
   some fine tuning in order to reduce the amount of        shown in Figure 7.7. The advantage of the drag-
                                                            and-drop method of creating a sub form is that


                                                                  Home      Previous      3 o f 19     Next


7. Subforms                                                                                      Tutorial exercises


       FIGURE 7.2: Rearrange the text boxes on the main form to make room for the subform.



   columnar form based on a
    Use the wizard to create
       Courses.


   rearrange the text boxes to
    Enter form design mode and
       make room for the subform.


      Save the form under the name
       frmCoursesMain.



                                             To move more than one form object at a time, either
                                             hold down the Shift key when selecting or drag a box
                                             through the objects (click and drag to create a box).




                                                                  Home      Previous      4 o f 19     Next
7. Subforms                                                                                   Tutorial exercises


                FIGURE 7.3: Use the wizard to create the Sections subform (part 1).


                                                             DeptCodeneedCrsNum since they
                                                              There is no
                                                                          and
                                                                              to include

                                                                are shown in the main form.




                                                                The order in which the fields are added to
                                                                the right-hand pane determines their order
                                                                (from left to right) on the form. Use the 
                                                                and  buttons to get the desired ordering.




   new form to thewizard and bind the
    Select the form
                    Sections table.




                                                              Home      Previous       5 o f 19     Next


7. Subforms                                                                                   Tutorial exercises


               FIGURE 7.4: Use the wizard to create the Sections subform (continued)


                                                                  In version 7.0, the title appears in the bar
                                                                  across the top of the form’s window. In
                                                                  version 2.0, however, the wizard creates a
                                                                  title in a form header. As such, you
                                                                  should ensure this is blank if you are
                                                                  using version 2.0.
                Select Tabular
                 layout.




                                                              form, you do not is embedded in aamain
                                                               Since a subform
                                                                                 have to provide title.




                       Select Modify the form’s design to
                       enter form design mode directly.

                                                              Home      Previous       6 o f 19     Next
7. Subforms                                                                                  Tutorial exercises


               FIGURE 7.5: Edit the subform to reduce the amount of space it uses.



                                           “detail band” and bringingby moving footer” band to the
                                            Reduce the vertical space
                                                                       the “form
                                                                                 the fields up
                                                                                               up
    by the headings and fields. used
     Reduce the horizontal space               against the fields (to move a band, drag it using the mouse).


                                                                           To split the headings into two
                                                                           or more lines, place the cursor
                                                                           at the desired split location and
                                                                           press Shift-Enter.




                                                                           To move all the fields at once,
                                                                           drag a “selection box” so that it
                                                                           touches each field. Note that the
                                                                           box does not have to enclose
                                                                           objects for them to be selected.




                                                             Home       Previous      7 o f 19     Next


7. Subforms                                                                                  Tutorial exercises


                        FIGURE 7.6: Drag the subform on to the main form.



                                    in design mode.form
                                     Open the main




                                                                               window so that the
                                                                                Position the database

                                                                                     subform’s target
                                                                                     destination is visible.




                                              Drag the subform on
                                               to the main form.



                                                             Home       Previous      8 o f 19     Next
7. Subforms                                                                                          Tutorial exercises

   the width of the subform control (the white win-        Since both the forms created in Section 7.3.3 were
   dow) is automatically set to equal the width of the     built on tables, Access could automatically deter-
   subform.                                                mine the relationship.
                                                            • Verify the link between the form and the subform
      If you make changes to the size of your sub-             by examining the property sheet of the subform
      form once the subform control is created, you            control, as shown in Figure 7.8.
      may have to resize the subform control by
      clicking and dragging a corner handle.                       The terminology “link child field” and “link
                                                                   master field” is identical to “foreign key” and
7.3.4 Linking forms and subforms                                   “primary key”. The main form is the parent
      manually                                                     (“one” side) and the subform is the child
If both the form and the subform are based on                      (“many” side).
tables, and if relationships have been defined
                                                             • View the resulting form. Notice that as you move
between the tables, Access normally has no problem
                                                               from course to course, the number of sections
determining which fields “link” the information on the
                                                               shown in the subform changes (see Figure 7.9).
main form with the information in the subform. How-
ever, when the forms are built on queries, Access
has no relationship information to rely on. As such,
you have to specify the form/subform links manually.



                                                                     Home       Previous      9 o f 19     Next


7. Subforms                                                                                          Tutorial exercises


                 FIGURE 7.7: The drag-and-drop operation creates a subform control.


                                                                                       The white area is a
                                                                                       “subform control”. It is
                                                                                       essentially a window
                                                                                       through which the subform
                                                                                       shows.




                                                                                             You may want to
                                                                                             delete the label
                                                                                             created with the
                                                                                             subform window. To
               This is the name of the form to which                                         delete the label only,
                                                                                             select it and press
               the subform control is bound.                                                 Delete.



                                         The form footer is pushed down when the subform control is created. You
                                         may move the footer to create more or less area at the bottom of the form.


                                                                     Home       Previous     10 o f 19     Next
7. Subforms                                                                                           Tutorial exercises


                           FIGURE 7.8: Verify the link fields for the form/subform.




                                                                  controlthe Sections subform bring
                                                                   Select
                                                                           (the white window) and
                                                                      up its property sheet.



                                                                  determined Access has correctly
                                                                   Verify that
                                                                               the link fields.




                                                                      When there are more than one link
                                                                      fields (i.e., the foreign key is
                                                                      concatenated), separate the field
                                                                      names with a semicolon. In Access
                                                                      version 7.0, a builder is available to
                                                                      select the field names from a list.



                                                                   Home       Previous         11 o f 19    Next


7. Subforms                                                                                           Tutorial exercises


                              FIGURE 7.9: A synchronized main form/subform.


 290, eightfor COMM
  Note that
             courses are               For COMM 291, four
                                        sections are listed in
     listed in the subform.             the subform.




 record” navigation
  Click the “next
     button on the main
     form to move to the
     next course.



     There are two sets of
     navigation buttons:
     one for the main form
     (bottom) and one for
     the subform (at the
     bottom of the
     subform window).


                                                                   Home       Previous         12 o f 19    Next
7. Subforms                                                                                       Tutorial exercises

7.3.5 Non-synchronized forms                                itself) to make your form more attractive and easier
In this section, you will delete the link fields shown in   to use.
Figure 7.8 in order to explore some of the problems         In Figure 7.11, the basic form created in the previous
associated with non-synchronized forms.                     sections is shown and a number of shortcomings are
  • Return to form design mode and delete the link          identified.
    fields (highlight the text and press the Delete         7.3.6.1 Changing the form’s caption
    key).                                                     • Select the form as shown in Figure 7.12.
  • View the form. Note that all records in the Sec-          • Change its Caption property to “Courses and
    tions table (not just those associated with a               Sections”.
    particular course) are shown.
  • Attempt to add a new section to COMM 290 as             7.3.6.2   Eliminating unwanted scroll bars and
    shown in Figure 7.10.                                             navigation buttons
  • Re-establish the correct link fields and save the       Scroll bars and navigation buttons are also form-
    form.                                                   level properties. However, in this case, you need to
                                                            modify the properties of the subform.
7.3.6 Aesthetic refinements                                   • To quickly open the subform in design mode,
In this section, you will modify the properties of sev-         double-click the subform control when viewing
eral form objects (including the properties of the form         the main form in design mode (this takes some
                                                                practice)


                                                                      Home     Previous    13 o f 19    Next


7. Subforms                                                                                       Tutorial exercises


                            FIGURE 7.10: A non-synchronized main form/subform.


  fields for the
   Delete the link

       subform control
       and view the
       resulting form.


  sections show37
   Note that all
                 in
       the subform
       (moving to a
       different course
       has no effect).


      Add a new
       catalog number
       and click the
       record selector           Since the forms are not synchronized, the
       to try to save the        DeptCode and CrsNum fields of the Sections
       new record.               table are not automatically filled in by Access.



                                                                      Home     Previous    14 o f 19    Next
7. Subforms                                                                                          Tutorial exercises


              FIGURE 7.11: A form/subform in need of some basic aesthetic refinements.

                      The caption of the form shows the form’s name.
                      A more attractive/descriptive caption is required.


                                                                                          Since the subform control
                                                                                          was automatically sized to
                                                                                          fit the underlying form, a
                                                                                          horizontal scroll bar is not
                                                                                          necessary.




                                                                                          The navigation buttons for
                                                                                          the subform are too easily
                                                                                          confused with the
                                                                                          navigation buttons for the
                                                                                          main form



                                                                      Home     Previous       15 o f 19    Next


7. Subforms                                                                            Application to the assignment

                                                              • Bring up the property sheet for the form and scroll
      FIGURE 7.12: Select the entire form.
                                                                down to change its Scroll Bars and Navigation
                                                                Button properties, as shown in Figure 7.13.
   and horizontal rulerswhere in order to
    Click on the square
                          meet
                               the vertical
                                                            The net result, as shown in Figure 7.14, is a more
       get the property sheet for the form.                 attractive, less cluttered form.

                                                            7.4 Application to the assignment
                                                              • Create a form and subform for your Shipment
                                                                and ShipmentDetails information. You will
                                                                use this form to record the details of shipments
                                                                from your suppliers.
                                                            Note that both forms should be based on queries:
                                                             • the Shipment form should be based on a “sort”
                                                               query so that the most recent shipment always
                                                               shows first;
                                                             • the ShipmentDetails form should be based
                                                               on a join query so that validation information
                                                               (such as the name of the product) is shown when
                                                               a product number is entered.


                                                                      Home     Previous       16 o f 19    Next
7. Subforms                                                                  Application to the assignment

                                                    • Create a form/subform to show customer orders
   FIGURE 7.13: Change the scroll bars and
                                                      that have already been placed (such as the one
      navigation buttons of the subform.
                                                      you entered manually in Section 4.5). The top
                                                      part of the form should contain information about
                    propertyScroll Bar
                     Set the
                              to “Vertical
                                                      the order plus some information about the cus-
                        Only” and the Navigation      tomer; the subform should contain information
                        Buttons property to “No”.     about what was ordered and what was actually
                                                      shipped.

                                                         The form you created in the preceding step is
                                                         used for viewing existing orders, not for add-
                                                         ing new orders. To add new orders, the form
                                                         must be more complex. For example, it has to
                                                         show the quantity on hand and the back
                                                         ordered quantity for each item so the user can
                                                         decide how many to ship. You will create a
                                                         form for order entry in the latter tutorials.

                                                    • Set the Allow Additions and Allow Edits proper-
                                                      ties of the “order viewing” form to No. This pre-


                                                           Home      Previous     17 o f 19    Next


7. Subforms                                                                  Application to the assignment


              FIGURE 7.14: A form without subform scroll bars or navigation buttons.




                                                           Home      Previous     18 o f 19    Next
7. Subforms                                                       Application to the assignment

  vents the user from changing the details of an
  order that has already been invoiced or attempt-
  ing to use the form for order entry.




                                                     Home   Previous   19 o f 19   Next
Access Tutorial 8: Combo Box Controls
8.1 Introduction: What is a combo
    box?                                                    FIGURE 8.1: A combo box for filling in the
                                                                        Activity field.
So far, the only kind of “control” you have used on
your forms has been the text box. However, Access
provides other controls (such as combo boxes, list
boxes, check boxes, radio buttons, etc.) that can be
used to improve the attractiveness and functionality
of your forms.
A combo box is list of values from which the user can
select a single value. Not only does this save typing,
it adds another means of enforcing referential integ-
rity since the user can only pick values in the combo
box. For example, a combo box for selecting course       same. For example, in Figure 8.1, the combo box is
activities from a predefined list is shown in            bound to the Activity field. When an item in the
Figure 8.1.                                              combo box is selected, the string (e.g., “LEC”) is
Although advanced controls such as combo boxes           copied into the underlying field exactly as if you had
and list boxes look and behave very differently than     typed the letters L-E-C into a text box.
simple text boxes, their function is ultimately the

© Michael Brydon (brydon@unixg.ubc.ca)
Last update: 25-Aug-1997                                          Home      Previous      1 o f 23    Next


8. Combo Box Controls                                                                         Learning objectives

       It is important to realize that combo boxes             What is tab order? How do I change it so that
       have no intrinsic search capability. Combo               the cursor moves in the correct order?
       boxes change values—they do not automati-               Should I put a combo box on a key field?
       cally move to the record with the value you
       select. If you want to use a combo box for        8.3 Tutorial exercises
       search, you have to program the procedure
                                                          • Open your frmCourses form in design mode.
       yourself (see Tutorial 15 for more details).       • Ensure the toolbox and field list are visible (recall
                                                            Figure 6.3).
8.2 Learning objectives
      How do I create a bound combo box?                8.3.1 Creating a bound combo box
      Can I create a combo box that displays values     Although Access has a wizard that simplifies the pro-
       from a different table?                           cess of creating combo boxes, you will start by build-
      How do I show additional information in a
                                                         ing a simple combo box (similar to that shown in
                                                         Figure 8.1) with the wizard turned off. This will give
       combo box?
                                                         you a better appreciation for what the wizard does
      How do I prevent certain information from         and provide you with the skills to make refinements
       showing in the combo box?                         to wizard-created controls.
      Can I change the order in which the items           • Delete the existing Activity text box by select-
       appear in a combo box?                                ing it and pressing the Delete key.


                                                                  Home      Previous      2 o f 23    Next
8. Combo Box Controls                                                                         Tutorial exercises

 • The wizard toggle button ( ) in the toolbox                  an unbound combo box, the easiest thing to
   allows you to turn wizard support on and off.                do is to delete it and try again.
   Ensure the button is out (wizards are turned off).       FIGURE 8.3: An unbound combo box (not what
 • Click on the combo box tool ( ). The cursor                               you want).
   turns into a small combo box.
 • With the combo box tool selected, drag the
   Activity field from the field list to the desired
   location on the form’s detail section, as shown in
   Figure 8.2.
The process of selecting a tool from the toolbox, and
then using the tool to drag a field from the field list
ensures that the control you create (text box, combo
box, etc.) is bound to a field in the underlying table or
query.
                                                                                             Since the control
                                                                                             is unbound, no
       If you forget to drag the field in from the field                                     field name
       list, you will create an unbound combo box, as                                        shows and the
       shown in Figure 8.3. If you accidently create                                         label is generic.




                                                                  Home     Previous    3 o f 23     Next


8. Combo Box Controls                                                                         Tutorial exercises


                                   FIGURE 8.2: Create a bound combo box.




                                                                      depressed. wizard button is not
                                                                       Ensure the




                                                                      activate the combo box tool. to
                                                                       Click on the combo box button




                                                                          Select the Activity field from
                                                                           the field list.




   have doneActivity field onname ofdetailunderlying
    Drag the
              this correctly, the
                                  to the
                                         the
                                             area. If you

         field should show in the combo box and the label
         should take the value of the field’s caption


                                                                  Home     Previous    4 o f 23     Next
8. Combo Box Controls                                                                            Tutorial exercises

8.3.2 Filling in the combo box properties                  • Change the Row Source Type property to Value
In this section, you will tell Access what you want to       List as shown in Figure 8.4. This tells Access to
appear in the rows of new combo box.                         expect a list of values in its Row Source property.
  • Switch to form view and test the combo box.
                                                          FIGURE 8.4: Set the Row Source Type property.
At this point, the combo box does not show any list
items because we have not specified what the list
items should be. There are three methods of specify-
ing what shows up in the combo box list:
1. enter a list of values into the combo box’s Row
   Source property;
2. tell Access to get the value from an existing table
   or query;
3. tell Access to use the names of fields in an exist-
   ing table (you will not use this approach).
Although the second method is the most powerful
and flexible, you will start with the first.
 • Bring up the property sheet for the Activity
    combo box.


                                                                   Home      Previous     5 o f 23     Next


8. Combo Box Controls                                                                            Tutorial exercises

 • Enter the following into the Row Source property:      8.3.3 A combo box based on another
   LAB;LEC;TUT                                                  table or query
 • Set the Limit To List property to Yes.
                                                          An obvious limitation of the value-list method of cre-
                                                          ating combo boxes is that it is impossible to change
       If the Limit To List property is set to No, the
                                                          or update the items that appear in the list without
       user can ignore the choices in the combo box
       and simply type in a value (e.g., “SEM”). In       knowing about the Row Source property.
       this particular situation, you want to limit the   A more elegant and flexible method of populating the
       user to the three choices given.                   rows of a combo box is to have Access look up the
                                                          values from an existing table or query. Although the
 • Switch to form view and experiment with the            basic process of setting the combo box properties
   combo box.                                             remains the same, it is more efficient to rely on the
                                                          wizard when building this type of combo box.
       Notice that the combo box has some useful
                                                          Before you can continue, you need a table that con-
       built-in features. For example, if you choose
                                                          tains appropriate values for course activities.
       to type values rather than select them with a
       mouse, the combo box anticipates your                • Switch to the database window and create a new
                                                              table called Activities.
       choice based on the letters you type. Thus, to
       select “TUT”, you need only type “T”.                • The table should consist of two fields: one called
                                                              Activity and the other called Descript, as
                                                              shown in Figure 8.5.

                                                                   Home      Previous     6 o f 23     Next
8. Combo Box Controls                                                                  Tutorial exercises

                                                 • Populate the table with the same values used in
 FIGURE 8.5: Create a table containing course
                                                   Section 8.3.2.
                  activities.
                                                The result is a table containing all the possible
                                                course activities and a short description to explain
                                                the meaning of the three-letter codes. You can now
                                                return to creating a combo box based on these val-
                                                ues.
                                                  • Delete the existing Activity combo box.
                                                  • Ensure the wizard button ( ) in the toolbox is
                                                    depressed (wizards are activated).
                                                  • Repeat the steps for creating a bound combo box
                                                    (i.e., select the combo box tool and drag the
                                                    Activity field from the field list on to the detail
                                                    section). As shown in Figure 8.6, this activates
                                                    the combo box wizard.
                                                The wizard asks you to specify a number of things
                                                about the combo box:
                                                1. the table (or query) from which the combo box
                                                   values are going to be taken;


                                                         Home      Previous     7 o f 23     Next


8. Combo Box Controls                                                                  Tutorial exercises


                  FIGURE 8.6: Create a combo box using the combo box wizard.

                                                     combo abox.
                                                      Create bound




                                                                   valuesAccessa look up the
                                                                    Have
                                                                           from table or query.




                                                         Home      Previous     8 o f 23     Next
8. Combo Box Controls                                                                             Tutorial exercises

2. the field (or fields) that you would like to show up          source table or query change while the form is
   as columns in the in the combo box;                           open these changes are not automatically
3. the width of the field(s) in the combo box (see               reflected in the combo box rows. As a conse-
   Figure 8.7);                                                  quence, you have to either (a) close and re-
4. the column from the combo box (if more than one               open the form, or (b) requery the form.
   field is showing) that is inserted into the underly-          Although you can automate the requery pro-
   ing field; and,                                               cess, we will rely on the F9 key for the time
5. the label attached to the field (see Figure 8.8).             being.
When you are done, the combo box should look sim-
                                                          8.3.3.1   Showing more than one field in the
ilar to that shown in Figure 8.1. However, updating or
                                                                    combo box
changing the values in the combo box is much easier
when the combo box is based on a table.                   One problem the combo boxes created so far is that
   • Add “SEM” (Seminar) to the Activities table.         they are not of much use to a user who is not familiar
   • Return to the form, click on the Activity combo      with the abbreviations “TUT”, “SEM”, and so on. In
     box, and press F9 to requery the combo box.          this section, you will use the Descript field of the
   • Verify that “SEM” shows up in combo box.             Activities table to make the combo box more
                                                          readable, as shown in Figure 8.9.
       Access creates the rows in a combo box               • Delete the existing combo box and start again.
       when the form is opened. If the values in the



                                                                    Home     Previous      9 o f 23     Next


8. Combo Box Controls                                                                             Tutorial exercises


                                                                        FIGURE 8.7: Fill in the combo box
                                                                             wizard dialog sheets.




                                                                               morecomboone field. show
                                                                                The
                                                                                     than
                                                                                          box can
                                                                                                    Select
   Activities
    The new
                                                                                    only Activity for now.
        tables contains
        the values for
        the combo box.




                                                                          Use the column selector (the grey bar
                                                                           at the top of the column) to resize the
                                                                           column to the desired width.


                                                                    Home     Previous      10 o f 23    Next
8. Combo Box Controls                                                                             Tutorial exercises


                     FIGURE 8.8: Fill in the combo box wizard dialog sheets (continued).




   to thecombo box is already bound
    The
           Activity field, this step
          is automatically filled in for you.




          Because the combo box is bound,
           the Activity field’s caption is
           provided as a default label.




                                                                   Home       Previous     11 o f 23    Next


8. Combo Box Controls                                                                             Tutorial exercises

                                                          tions and want them to select a course activity value
FIGURE 8.9: A combo box that shows two fields
                                                          based solely on the Descript field.
       from the source table or query.
                                                          In such a case, you could include only the
                                                          Descript column in the combo box. However, this
                                                          would not work because the Activity field of the
                                                          Courses table expects a three-letter abbreviation.
                                                          As such, the combo box would generate an error
                                                          when it tried to stuff a long description into the rela-
                                                          tively short field to which it is bound.
                                                          In this section, you will create a combo box identical
                                                          to that shown in Figure 8.9 except that the key col-
                                                          umn (Activity) will be hidden from view. Despite
                                                          its invisibility, however, the Activity column will
 • Fill in the wizard dialog sheets as in Section 8.3.3
                                                          still be bound to the Activity field of the underly-
   but make the changes shown in Figure 8.10.
                                                          ing table and thus the combo box will work as it
 • Verify that your combo box resembles Figure 8.9.
                                                          should.
8.3.3.2     Hiding the key field                             • Delete the existing combo box and start again
Assume for a moment that you, as a developer, do               using the combo box wizard.
not want users to even see the three-letter abbrevia-


                                                                   Home       Previous     12 o f 23    Next
8. Combo Box Controls                                                                              Tutorial exercises


                                                                           FIGURE 8.10: Use the wizard to
                                                                           add more than one field to the
                                                                                   combo box.


                                                            Activities table into the combo box.
                                                             Bring both fields from the


                                                                    resize the the “hide appropriately.
                                                                     Uncheck
                                                                                 columns
                                                                                          key” box and

                                                                        Note that Access version 2.0 does
                                                                        not have the “hide key” feature


                                                                               Select the column that provides
                                                                                the value of interest (in this case,
                                                                                Activity).




                                                                    Home       Previous     13 o f 23     Next


8. Combo Box Controls                                                                              Tutorial exercises

 • Include both the Activity and Descript fields
   in the combo box.                                      FIGURE 8.12: A combo box with a hidden key.
 • Resize the Activity column as shown in
   Figure 8.11. Note that users of version 7.0 can
   simply leave the “hide key” box checked—the
   result is the same.
 • Ensure that the Input Mask property for the
   combo box (which is inherited from the field’s
   Input Mask property) is blank.
 • Verify that the resulting combo box resembles
   that shown in Figure 8.12.

     Combo boxes with hidden keys can be con-
                                                         8.3.3.3     Changing the order of items in the
     fusing. The important thing to remember is
                                                                     combo box
     that even though the description (e.g., “Lec-
     ture”) now shows in the combo box, what is          A combo box based on a table shows the records in
     really stored in the underlying field is the hid-   one of two ways:
     den key (e.g., “LEC”).                              1. If the table does not have a primary key, the
                                                            records are shown in their natural order (that is,
                                                            in the order they were added to the database).

                                                                    Home       Previous     14 o f 23     Next
8. Combo Box Controls                                                                           Tutorial exercises


                               FIGURE 8.11: Resize the columns to hide the key.



   the column selector andof
    Click on the right side

        drag the edge of the
        Activity column to the
        far left (i.e., make its width
        zero)


        Hiding the key is such a
        common operation that
        Access version 7.0 includes
        the “hide key” check box.




                                                                   Home      Previous    15 o f 23    Next


8. Combo Box Controls                                                                           Tutorial exercises

2. If the table does have a primary key, then the         If the changes are quite minor (for instance, sorting
   records are sorted in ascending order according        the records in a different order), you may prefer to
   to the key.                                            modify the Row Source property.
It may be, however, that you want a different order       In Section 8.3.2, you set the Row Source property to
within the rows of the combo box. To achieve this,        equal a list of values. When the combo box is based
you can do one of two thing:                              on values from a table or a query, however, the Row
1. Create a stand-alone query (in which the sort          Source is an SQL statement (recall Tutorial 5) rather
   order is specified) and use this query as the          than a list of values. You can either edit the SQL
   source for the combo box.                              statement directly or invoke the QBE editor.
2. Modify the “ad hoc” query within the Row Source        In this section, you will order the items in you combo
   property of the combo box.                             box according to the length of the Descript field
If you intend to make several major changes to the        (this is done merely for illustrative purposes).
basic information in the underlying table (e.g., joins,     • Bring up the property sheet for the Activity
calculated fields), it is usually better to create a          combo box.
stand-alone query. In this way, the same query can          • Put the cursor in the Row Source property. As
be used by many combo boxes.                                  shown in Figure 8.13, a builder button ( )
                                                              appears.
                                                            • Press the builder button to enter the “SQL
                                                              builder” (i.e., the QBE editor).


                                                                   Home      Previous    16 o f 23    Next
8. Combo Box Controls                                                                        Tutorial exercises

                                                           (Len() is a built-in function that returns the
  FIGURE 8.13: Invoke the builder for the Row
                                                           length of a string of characters).
               Source property.
                                                       •   Sort on DescLength in descending order.
                                                       •   Switch to datasheet view to ensure the query is
                                                           working as it should.
                                                       •   Ensure the Show box for the field is unchecked,
                                                           as shown in Figure 8.14.
                                                       •   Instead of saving the query in the normal way,
                                                           simply close the QBE box using the close button
                                                           ( ).

                                                              If you save the query, it will be added to your
                                                              collection of saved queries (the ones that are
  bring up the QBEbutton to
   Click the builder
                     editor.
                                                              displayed in the database window). However,
                                                              if you simply close the QBE window, the Row
      Alternatively, you can edit
      the SQL statement directly.                             Source property will be updated and no new
                                                              database object will be created.
 • Create a calculated field called DescLength
   using the following expression:
   DescLength: Len([Descript])


                                                                Home      Previous    17 o f 23    Next


8. Combo Box Controls                                                                        Tutorial exercises

                                                      8.3.4 Changing a form’s tab order
FIGURE 8.14: Use the QBE editor to modify the         A form’s tab order determines the order in which the
           Row Source property.                       objects on a form are visited when the Tab or Enter
                                                      (or Return) keys are pressed. Access sets the tab
                                                      order based on the order in which objects are added
                                                      to the form. As a result, when you delete a text box
                                                      and replace it with a combo box or some other con-

                      calleda DescLength.
                       Add calculated field           trol, the new control becomes the last item in the tab
                                                      order regardless of its position on the form.
                                                      To illustrate the problem, you are going to create a
                                                      combo box for the DeptCode field.
                                                       • Delete the DeptCode text box and replace it with
                                                          a combo box based on the Departments table.
                                                       • Switch to form view. Notice that the focus starts
                                                          off in the CrsNum field instead of the DeptCode
                                                          field.
    calculated field.
     Sort on the
                                       Uncheck the
                                        Show box       • Press tab to move from field to field. Notice that
                                                          after DeptCode is left, the focus returns to the
                                                          CrsNum field of the next record.


                                                                Home      Previous    18 o f 23    Next
8. Combo Box Controls                                                                                   Discussion

 • To fix the problem, return to form design mode           For example, it never makes sense to put a combo
   and select View  Tab Order from the main                box on a non-concatenated primary key. To illustrate
   menu.                                                    this, consider the Departments form shown in
                                                            Figure 8.16. On this form, the DeptCode text box

      In Access version 2.0, the menu structure is
       slightly different. As such, you must select
                                                            has been replaced with a combo box that draws its
                                                            values from the Departments table.
       Edit  Tab Order.
                                                            FIGURE 8.16: A combo box bound to a key field.
 • Perform the steps in Figure 8.15 to move Dept-
   Code to the top of the tab order.

8.4 Discussion
8.4.1 Why you should never use a
      combo box for a non-concatenated
      key.
A mistake often made once new users learn how to            This combo box appears to work. However, if you
make combo boxes is to put a combo box on every-            think about it, it makes no sense: The form in
thing. There are certain situations, however, in which      Figure 8.16 is a window on the Departments table.
the use of a combo box is simply incorrect.                 As such, when the DeptCode combo box is used,

                                                                     Home     Previous      19 o f 23   Next


8. Combo Box Controls                                                                                   Discussion


                              FIGURE 8.15: Adjust the tab order of fields on a form.



   selector torecord
    Drag the
                 the                                                              selector of the field
                                                                                   Click on the record

        desired position in                                                              you wish to move.
        the list.




                   For forms in which the fields are arranged
                   in a single column from top to bottom
                   (such as this one), you can press Auto
                   Order to order them automatically.



                                                                     Home     Previous      20 o f 23   Next
8. Combo Box Controls                                                                               Discussion

one of two things can occur depending on whether a          combo box is identical to typing “CPSC” over
new record is being created or an existing record is        whatever is currently in the DeptCode field. This
being edited:                                               causes all sorts of problems; the most obvious of
1. A new record is being created — If a new                 these is that by overwriting an existing value of
   record is being created (i.e., a new department is       DeptCode, a “duplicate value in index, primary
   being added to the information system), a unique         key, or relationship” error is generated (there is
   value of DeptCode must be created to distin-             already a department with “CPSC” as its Dept-
   guish the new department from the existing               Code).
   departments. However, the combo box only              Note that a combo box may make sense when the
   shows DeptCode values of existing depart-             key is concatenated. An example of this is the
   ments. If the Limit To List property is set to Yes,   DeptCode combo box you created in Section 8.3.4.
   then the combo box prevents the user from enter-
   ing a valid DeptCode value.                           8.4.2 Controls and widgets
2. An existing record is being edited — It is            Predefined controls are becoming increasingly popu-
   important to remember that a combo box has no         lar in software development. Although Microsoft
   intrinsic search capability. As such, selecting       includes several predefined controls with Access
   “CPSC” in the DeptCode combo box does not             (such as combo boxes, check boxes, radio buttons,
   result in a jump to the record with “CPSC” as its     etc.), a large number of more compex or specialized
   key value. Rather, selecting “CPSC” from the          controls are available from Microsoft and other ven-


                                                                  Home     Previous     21 o f 23   Next


8. Combo Box Controls                                                             Application to the assignment

dors. In addition, you can write your own custom         8.5 Application to the assignment
controls using a language like Visual C++ or Visual
                                                         There are a number of forms in your assignment that
Basic and use them in many different forms and
                                                         can be greatly enhanced by combo boxes.
applications.
                                                          • Create a combo box on your order form to allow
An example of a more complex control is the calen-          the user to select customers by name rather than
dar control shown in Figure 8.17. A calendar control        CustID. Since your CustID value is a counter, it
can be added to a form to make the entry of dates           has no significance beyond its use as a primary
easier for the user. Microsoft calls such components        key. Generally, such keys should be hidden from
“ActiveX controls” (formerly known as “OLE con-             view.
trols”). Non-microsoft vendors provide similar com-       • Create a combo box in your order details subform
ponents but use different names, such as “widgets”.         to allow the user to select products. Since the
There are two main advantages of using controls.            ProductID values are used by both you and
First, they cut down on the time it takes to develop        your customers, they have some significance
an application since the controls are predefined and        beyond the information system. As such, Pro-
pre-tested. Second, they are standardized so that           ductID should be visible in all combo boxes. In
users encounter the same basic behavior in all appli-       addition, the items in the product list should be
cations.                                                    sorted by ProductID. This makes it easier to
                                                            select a product by typing the first few numbers.
                                                          • Create combo boxes on other forms as required.


                                                                  Home     Previous     22 o f 23   Next
8. Combo Box Controls                                                    Application to the assignment


                        FIGURE 8.17: A calendar control on a form.



                                                   The calendar control can be bound
                                                   to date/time fields, thereby making
                                                   it easier for users to enter dates.




                                                          Like other objects in Access, controls have
                                                          properties and events that determine the
                                                          appearance and behavior of the control.



                                                       Home       Previous     23 o f 23    Next
Access Tutorial 9: Advanced Forms
9.1 Introduction: Using calculated                       best course of action. However, as you will see in the
    controls on forms                                    context of subtotals, this is not always possible.

It is often useful to show summary information from
                                                         9.2 Learning objectives
the subform on the main form. The classic example
of this is showing the subtotal from a list of order           How do I create a calculated text box?
details on the main order form.                                What is the expression builder? When is it
In this tutorial, you are going to explore one means            used?
of implementing this feature using calculated con-             Where can put an intermediate result of a
trols. A calculated control is an unbound control for           calculation on a form so that it does not
which the Control Source property is set to an                  show?
expression that Access can evaluate.
Clearly, calculated controls have a great deal in com-   9.3 Tutorial exercises
mon with the calculated query fields you created in
Section 4.3.3. Although there are no hard-and-fast       9.3.1 Creating calculated controls on
rules that dictate when to use a one over the other,           forms
pushing your calculations to the lowest level (i.e.,     In this section, you are going to create a simple cal-
performing calculations in the query) is usually the     culated text box to translate the Credits field into a
                                                         dichotomous text variable [full year,

© Michael Brydon (brydon@unixg.ubc.ca)
Last update: 24-Aug-1997                                           Home      Previous      1 o f 11     Next


9. Advanced Forms                                                                                 Tutorial exercises

half year]. Recall that you have already imple-           • Test your form. Note that you are prevented from
mented this feature in Section 4.3.3.2 using a calcu-       editing the calculated field. If, however, you
lated query field.                                          change the value of Credits, the value of txt-
  • Perform the steps shown in Figure 9.1 to create         CourseLength changes accordingly when you
    an unbound text box on your fmrCoursesMain              leave the Credits field.
    form.
  • Set the Control Source property of the text box      9.3.2 Showing a total on the main form
    using the syntax:                                    In this section, you will create a calculated text box
    = expression                                       that displays the number of sections associated
    In this case, the expression should be an “imme-     with each course. The primary motivation for this
    diate if” function (see Section 4.3.3.2).            exercise is to illustrate some of the limitations of cal-
                                                         culated controls (as they are implemented in Access)
       By default, Access interprets text in the Con-
                                                         and to provide an opportunity to explore an interest-
       trol Source property field as the name of a
                                                         ing work-around.
       variable (i.e., the name of a field or another
                                                           • Create a text box call txtNumSections on the
       control). As such, you must remember to
                                                             main form as shown in Figure 9.2.
       include the equals sign when setting this
       property.                                         The logical next step is to set the Control Source of
                                                         the field to an expression that includes the Count()
                                                         function. However, Access has a limitation in this


                                                                   Home      Previous      2 o f 11     Next
9. Advanced Forms                                                                           Tutorial exercises


                     FIGURE 9.1: Create an unbound text box on your main form.

                                   Credits text boxbytodragging the
                                    Make some room
                                                         the left.                 tool from the box
                                                                                    Select the text

                                                                                       toolbox and click on
                                                                                       an appropriate space
                                                                                       in the detail area.

                                                                                       Adjust the tab order
                                                                                        of the fields as
                                                                                        necessary.




   (e.g.,the label and give the textThe txt prefix is name
    Edit
           txtCourseLength).
                                     box a meaningful
                                                       used
       here to indicate an unbound text box.


                                                               Home    Previous      3 o f 11     Next


9. Advanced Forms                                                                           Tutorial exercises


               FIGURE 9.2: Create an unbound text box to show the number of sections
                                    associated with each course.

   Sincean unbound textboundcalled txtNumSections.
    Add
          it is currently
                          box
                              to nothing, it is blank.




                                                                                           What you want
                                                                                           is a means of
                                                                                           counting the
                                                                                           records in the
                                                                                           subform and



                                                                       }
                                                                                           displaying the
                                                                                           count in the
                                                                                           new text box.




                                                               Home    Previous      4 o f 11     Next
9. Advanced Forms                                                                                       Tutorial exercises

regard: you cannot use an aggregate function                 9.3.2.1   Calculating the aggregate function on
(Sum(), Avg(), Count(), etc.) on a main form that                      the subform
refers to a field in a subform. As a consequence, you          • Create an unbound text box on the subform as
have to break the calculation into two steps:                    shown in Figure 9.3.
1. use the aggregate function to create a calculated           • Save the subform but do not close it.
   text box on the subform (i.e., a “dummy” field to           • Return to the main form and set the Control
   hold an intermediate result);                                 Source of txtNumSections to equal the value
2. create a calculated control on the main form that             of txtNumSectionsOnSub. Since the naming
   references the dummy text box created in the first            conventions for objects on forms and subforms
   step.                                                         can be tricky, use the expression builder (as
                                                                 shown in Figure 9.4) to build the name for you.
      It is important that you realize that this proce-      The expression builder organizes all the elements of
      dure does not involve any immutable, funda-            the database environment into a hierarchical struc-
      mental information systems knowledge.                  ture. You build an expression by “drilling down” to the
      Rather, it is merely an example of the type of         element you need and double-clicking to copy its
      work-around (hack, kludge, etc.) that is rou-          name into the text area.
      tinely used when using a tool like Access to
      create a custom application.                                      The expression builder takes some practice.
                                                                        One problem is that it is easy to double-click



                                                                          Home      Previous     5 o f 11     Next


9. Advanced Forms                                                                                       Tutorial exercises


                              FIGURE 9.3: Perform the count on the subform.



       txtNumSectionsOnSub and place it in the form header
        Create a calculate control called
           (do not worry about its location, you will move it later).


                                                                                      propertyControl Source
                                                                                       Set the
                                                                                                to
                                                                                           =Count([Section]).
                                                                                           Note that any field can be
                                                                                           used as the argument for the
                                                                                           Count() function.




                                                                          Home      Previous     6 o f 11     Next
9. Advanced Forms                                                                              Tutorial exercises


         FIGURE 9.4: Use the builder to drill down to the calculated control on the subform.


                                                                      Controlthe builder from the drill
                                                                       Invoke
                                                                               Source property and
                                                                          down to the calculated control you
                                                                          just created on the subform.
       Note that when the main
       form and the subform are
       both open, the subform
       appears twice in the builder:
       once as a “stand-alone”
       form (under “Loaded
       Forms”) and once as a
       component of the main form
       (press the + sign on the
       frmCoursesMain
       folder). You want to use the
       latter (you will never
       access the subform in stand-
       alone mode).




                                                                  Home    Previous      7 o f 11     Next


9. Advanced Forms                                                                              Tutorial exercises

      on the wrong thing. Another problem is that          • Test the form. The value of txtNumSections
      Access attempts to guide you by inserting              and txtNumSectionsOnSub should be identi-
      «Expr» place-holders all over the place. The           cal, as shown in Figure 9.5.
      solution to both problems is to click on the text   FIGURE 9.5: The number of sections on the main
      window and make liberal use of the Delete                              form.
      key.

      The point made about “stand-alone” and
      “component” subforms in Figure 9.4 is
      extremely important. The reason you use the
      sfrm prefix is so you know that the form is
      designed to be a component of another form.
      If you select the stand-alone version the form
      in the builder, the name created by the builder
                                                                          The “dummy” text box is visible in
      will be incorrect and an error will result.                         the subform. Although you will
                                                                          eventually hide it, it is useful to
 • Close the subform (in version 7.0 and 8.0, the                         display it until you know both steps
   main form and subform cannot be open at the                            of the calculation are working
                                                                          properly.
   same time).



                                                                  Home    Previous      8 o f 11     Next
9. Advanced Forms                                                                                        Discussion

9.3.2.2     Hiding the text box on the subform             • Drag (or cut and paste) txtNumSectionsOn-
The obvious problem in Figure 9.5 is that the dummy          Sub from the form header to the page header, as
text box shows on the subform. There are at least            shown in Figure 9.6.
two ways to get around this: one is to set the Visible     • Test the result.
property of the text box to No; a slightly more elegant
approach is to use the page header or page footer         9.4 Discussion
to hide the text box.                                     In Section 4.3.3.2 and Section 9.3.1, you accom-
The page header and footer are areas on the form          plished the same thing (showing half year or
that only show when the form is printed. Since you        full year) using different techniques. The advan-
will never print a form (reports are used for printed     tage of implementing this as a calculated query field
material), these areas can be used to hide intermedi-     is that you can use this field repeatedly in other
ate results, etc.                                         forms. On the other hand, if you do the transforma-
  • In design mode, select View  Page Header/            tion on the form, you have to repeat the calculation
    Footer from the menu.                                 on every form that requires the calculated field.
                                                          In the case of the aggregate function, the situation is

      In version 2.0, the menu structure is slightly
       different. As such, you must select Format 
                                                          slightly different. Although you can use the totals
                                                          feature of QBE (see on-line help) to count the num-
       Page Header/Footer.                                ber of sections for a particular course within a query,
                                                          the resulting recordset is non-updatable (and hence


                                                                   Home      Previous      9 o f 11      Next


9. Advanced Forms                                                                                        Discussion


                       FIGURE 9.6: Hide the intermediate result in the page header.


           menu (Format Page Header/Footer fromversion
            Select View 
                           Page Header/Footer in
                                                  the
                                                                            the field you and paste)
                                                                             Drag (or cut
                                                                                           want to hide
              2.0) to show the page header and footer.                           into the page header.




                                                                   Home      Previous      10 o f 11     Next
9. Advanced Forms                                                    Application to the assignment

not much use for editing course names, etc.). As a
result, you are forced to do the calculation on the
form rather than in the query.

9.5 Application to the assignment
To show the subtotal, tax, and grand total on your
order form, you use the same techniques illustrated
here. The only difference is that you use the Sum()
function instead of the Count() function to get the
subtotal for the order.
  • Create a dummy field on your OrderDetails
    subform to calculate the subtotal for the order.
  • Calculate the tax (G.S.T. only for wholesale) and
    grand total on the main form (traditionally, this
    information is located near the bottom of the
    form—but not in the form footer).




                                                        Home   Previous   11 o f 11   Next
Access Tutorial 10: Parameter Queries
The last few tutorials have been primarily concerned       result is that parameters can be used to create
with interface issues. In the remaining tutorials, the     extremely flexible queries.
focus shifts to transaction processing.                    When the concepts from this tutorial are combined
                                                           with action queries (Tutorial 11) and triggers
10.1 Introduction: Dynamic queries                         (Tutorial 13), you will have a the skills required to
     using parameters                                      create a simple transaction processing system with-
A parameter query is a query in which the criteria         out writing a line of programming code.
for selecting records are determined when the query
is executed rather than when the query is designed.        10.2 Learning objectives
For example, recall the select query shown in                    What is a parameter query? How do I create
Figure 4.6. In this query, the results set is limited to          one?
records that satisfy the criterion DeptCode =                    How do I prompt the user to enter parameter
“COMM”. If you wanted a different set of results, you             values?
would have to edit the query (e.g., change the crite-
rion to “CPSC”) and rerun the query.
                                                                 How do I create a query whose results
                                                                  depend on a value on a form?
However, if a variable (parameter) is used for the cri-
terion, Access will prompt the user for the value of
the variable before executing the query. The net

© Michael Brydon (brydon@unixg.ubc.ca)
Last update: 24-Aug-1997                                            Home       Previous     1 o f 11     Next


10. Parameter Queries                                                                              Tutorial exercises

10.3 Tutorial exercises                                    attempts to bind the variable to some value. To do
                                                           this, it performs the following tests:
10.3.1 Simple parameter queries                            1. First, Access checks whether the variable is the
 • If you do not already have a qryCourses query              name of a field or a calculated field in the query. If
   like the one shown in Figure 4.6, create one now           it is, the variable is bound to the current value of
   and save it under the name pqryCourses.                    the field. For example, if the parameter is named
 • Replace the literal string in the criteria row             [DeptCode], Access replaces it with the current
   (“COMM”) with a variable ([X]).                            value of the DeptCode field. Since X is not the
                                                              name of a field or a calculated field in this particu-
       By default, Access expects criteria to be literal      lar query, this test fails.
       strings of text. As a result, it automatically      2. Second, Access attempts to resolve the parame-
       adds quotation marks to text entered in the            ter as a reference to something within the current
       criteria row. To get around this, place your           environment (e.g., the value on an open form).
       parameter names inside of square brackets.             Since there is nothing called X in the current envi-
                                                              ronment, this test fails.
 • Execute the query as shown in Figure 10.1.              3. As a last resort, Access asks the user for the
When Access encounters a variable (i.e., something            value of the parameter via the “Enter Parameter
that is not a literal string) during execution, it            Value” dialog box.




                                                                    Home       Previous     2 o f 11     Next
10. Parameter Queries                                                                           Tutorial exercises


                      FIGURE 10.1: Convert a select query into a parameter query.


                                                              (herethe queryisand supply the value of value
                                                               Run
                                                                     Access asking for
                                                                                          a parameter
                                                                                                       X).




         (“COMM”) with a parameter (X)
          Replace the literal criterion



                                                                  Home      Previous     3 o f 11     Next


10. Parameter Queries                                                                           Tutorial exercises

       Note that the spelling mistakes discussed in      may be useful to be able to generate a list of courses
       Section 4.3.4 are processed by Access as          offered by the department currently being viewed.
       parameters.                                       Although you could use a creatively-named parame-
                                                         ter to invoke the “Enter Parameter Value” dialog, this
10.3.2 Using parameters to generate                      requires the user to type in the value of DeptCode.
       prompts                                           A more elegant approach is to have Access pull the
Since the name of the parameter can be anything          value of a parameter directly from the open form.
(as long as it is enclosed in square brackets), you      This exploits the second step in the operation of a
can exploit this feature to create quick and easy dia-   parameter query (Access will attempt to resolve a
log boxes.                                               parameter with the value of an object within the cur-
  • Change the name of your DeptCode parameter           rent environment). The basic idea is shown in
    from [X] to [Courses for which depart-               Figure 10.3.
    ment?].                                              The key to making this work is to provide a parame-
  • Run the query, as shown in Figure 10.2.              ter name that correctly references the form object in
                                                         which you are interested. In order to avoid having to
10.3.3 Values on forms as parameters                     remember the complex naming syntax for objects on
A common requirement is to use the value on a form       forms, you can invoke the expression builder to
to influence the outcome of a query. For instance, if    select the correct name from the hierarchy of data-
the user is viewing information about departments, it    base objects.


                                                                  Home      Previous     4 o f 11     Next
10. Parameter Queries                                                                    Tutorial exercises


              FIGURE 10.2: Select a parameter name that generates a useful prompt.



                                                                          the value of the for
                                                                           When Access asks

                                                                               parameter, it uses the
                                                                               parameter’s name.


                                                                              Only records that satisfy
                                                                               the criteria are included
                                                                               in the results set.




   for which department?].
    Name the parameter [Courses



                                                          Home      Previous      5 o f 11     Next


10. Parameter Queries                                                                    Tutorial exercises


             FIGURE 10.3: Using the value on an open form as a parameter in a query.




                                                        The current value in the DeptCode field on
                                                        the form is used as a parameter in the query.




                                                          Home      Previous      6 o f 11     Next
10. Parameter Queries                                                             Application to the assignment

 • Create a very simple form based on the                    Although the naming syntax of objects in
   Departments table and save it as frmDepart-               Access is tricky, it is not impossible to com-
   ments.                                                    prehend. For example, the name
 • Leave the form open (in form view or design               Forms![frmDepartments]![DeptCode]
   mode, it does not matter).                                consists of the following elements: Forms
 • Open pqryCourses in design mode, place the                refers to a collection of Form objects; [frm-
   cursor in the criteria row of the DeptCode field,         Departments] is a specific instance of a
   and invoke the expression builder as shown in             Form object in the Forms collection; [Dept-
   Figure 10.4.                                              Code] is a Control belonging to the form. See
 • Perform the steps shown in Figure 10.5 to create          Tutorial 14 for more information on the hierar-
   a parameter that references the DeptCode field            chy of objects used by Access.
   on the frmDepartments form.
 • Run the query. The results set should correspond    10.4 Application to the assignment
   to the department showing in the frmDepart-         You will use parameter queries as the basis for sev-
   ments form.                                         eral action queries (see Tutorial 11) that process
 • Move to a new record on the form. Notice that       transactions against master tables. For now, simply
   you have to requery the form (Shift-F9) in order    create the parameter queries that take their criteria
   for the new parameter value to be used (see         values from forms you have already created.
   Figure 10.6).



                                                                Home       Previous      7 o f 11   Next


10. Parameter Queries                                                             Application to the assignment


                         FIGURE 10.4: Invoke the builder to build a parameter.




                       Criteria row of the the
                        Place the cursor in
                            DeptCode field and
                            right-click to bring up
                            the pop-up menu.


                                                                 Departmentsform basedleavetheopen
                                                                  Create a simple
                                                                                  table and
                                                                                            on
                                                                                               it
                                                                       in the background.




                                                                      Select Build to
                                                                       invoke the builder.



                                                                Home       Previous      8 o f 11   Next
10. Parameter Queries                                                                      Application to the assignment


   FIGURE 10.5: Use the builder to select the name of the object you want to use as a parameter.


                                                 aDouble-click DeptCode toarea, delete the text,area.tryyou make
                                                    mistake, move to the text
                                                                              move it to the text
                                                                                                  and
                                                                                                       If
                                                                                                          again.



   the forms in yourget a list of all
    Select Forms to
                      database.




   form isthe frmDepartments
    Since
             open, click on Loaded
       Forms and select the form.


                                                                                                            Press OK
                                                                                                             when done.
      Move to the middle pane and
       select Field List to get a list of the
                                                                                                             The text will
                                                                                                             be copied
       fields on the form in the pane on                                                                     into the
       the far right.                                                                                        criteria row.



                                                                         Home       Previous     9 o f 11       Next


10. Parameter Queries                                                                      Application to the assignment


                  FIGURE 10.6: Requery the results set to reflect changes on the form.




                                                                          form. Notice that the query is not
                                                                           Move to a new record on the

                                                                                automatically updated.




    parameter valueto(MATH in this case)
     Press Shift-F9 requery. The new

         is used to select records.




                                                                         Home       Previous     10 o f 11      Next
10. Parameter Queries                                                            Application to the assignment

 • Create a parameter query to show all the order       • It shows the change (positive or negative but not
   details for a particular order.                        zero) in backorders for each item in a particular
 • Create a second parameter query to show all the        order.
   shipment details for a particular shipment.          • The query consist of three fields: OrderID, Pro-
Each order may result in a number of changes being        ductID and a calculated field Qty (i.e., the
made to the BackOrders table. For some items in           change in the back order for a particular product).
the order, more product is ordered than is actually     • The name of the parameter is in this query is sim-
shipped (i.e., a backorder is created). For other         ply[pOrderID]. Since the value of this parame-
items, more product is shipped than is ordered (i.e.,     ter will be set by the Visual Basic shortcut before
a backorder is filled).                                   the query is run, there is no need to set it to a
                                                          value on a form.
In Tutorial 15, you are supplied with a “shortcut”
Visual Basic procedure that makes the changes to             Since the query is accessed by a program,
the BackOrders table for you. However, the short-            the name of the query and all the fields must
cut procedure requires a query that lists the changes        be exactly as described above. In other
that must be made to the BackOrders table for a              words, you are given a precise specification
particular order. The requirements for this query are        for a database object that fills a role in a pro-
the following:                                               cess designed and implemented by someone
  • The name of the query is                                 else. You will not understand how the query
    pqryItemsToBackOrder                                     fits in until Tutorial 15.


                                                               Home      Previous      11 o f 11   Next
Access Tutorial 11: Action Queries
11.1 Introduction: Queries that                           2. Append — similar to a make-table query, except
     change data                                             that the results set of the query is appended to an
                                                             existing table;
11.1.1 What is an action query?                           3. Update — allows the values of one or more fields
                                                             in the result set to be modified; and,
All of the queries that you have created to this point
                                                          4. Delete — deletes all the records in the results set
have been variations of “select” queries. Select que-
                                                             from the underlying table.
ries are used to display data but do not actually
change the data in any way.                               Since the operation of all four types of action queries
                                                          is similar, we will focus on update queries in this tuto-
Action queries, in contrast, are used to change the
                                                          rial.
data in existing tables or make new tables based on
the query's results set. The primary advantage of
                                                          11.1.2 Why use action queries?
action queries is that they allow you to modify a large
                                                          To motivate the examples in the first part of this tuto-
number of records without having to write Visual
                                                          rial, we are going to assume that the number of cred-
Basic programs.
                                                          its allocated to courses in certain departments need
Access provides four different types of action que-
                                                          to be changed. For example, assume that you need
ries:                                                     to increase the number of credits for courses in the
1. Make table — creates a new table based on the          Commerce department by 1.5 times their current val-
   results set of the query;

© Michael Brydon (brydon@unixg.ubc.ca)
Last update: 25-Aug-1997                                           Home       Previous     1 o f 16    Next


11. Action Queries                                                                             Learning objectives

ues. There are at least four different ways of accom-     3. Write a Visual Basic program to automate Step 2.
plishing this task:                                          This is a good approach; however, it clearly
1. Create a calculated field called NewCredits that          requires the ability to write Visual Basic pro-
   multiplies the value of Credits by 1.5 — The              grams.
   query containing the calculated field can be used      4. Create an update query that (a) selects only
   in place of the Courses table whenever credit             those courses that require modification and (b)
   information is required. Of course, the values            replaces the value of Credits with Credits *
   stored in the Courses table are still the old val-        1.5. — This approach is computationally efficient
   ues. Although there might be some advantages              and allows you to work with the QBE editor rather
   to keeping the old values, it may cause confusion         than a programming language.
   about which values to use. In addition, the use of
   a calculated field creates a computational load        11.2 Learning objectives
   that becomes larger as the number of courses                 What is an action query? Why would I want to
   increases.                                                    use one?
2. Go through the Courses table record by record
   and manually change all the values — This
                                                                How do I make a backup copy of one of my
                                                                 tables?
   approach is tedious and error prone. Further-
   more, it is simply impractical if the number of              How to I undo (rollback) an action query once
   courses is large.                                             I have executed it?



                                                                   Home       Previous     2 o f 16    Next
11. Action Queries                                                                                 Tutorial exercises

      How do I update only certain records in a             • While still in query design mode, select Query 
       table?                                                  Make Table from the main menu and provide a
      How do I create a button on a form? How do I            name for the target table (e.g., CoursesBackup)
       make an action query execute when the                   as shown in Figure 11.1.
       button is pressed?                                    • Select Query  Run from the main menu to exe-
                                                               cute the action query, as shown in Figure 11.2.
11.3 Tutorial exercises                                            Action queries do not execute until you explic-
                                                                   itly run them. Switching to datasheet mode
11.3.1 Using a make-table query to create                          only provides a preview of the results set.
       a backup
Since action queries permanently modify the data in          • Save the query. If you switch to the database win-
tables, it is a good idea to create a backup of the            dow, you will notice that the new make-table
table in question before running the query. An easy            query has a different icon than the select queries.
way to do this is to use a make-table query.
  • Create a select query based on the Courses              11.3.2 Using an update query to rollback
    table and save it as qryCoursesBackup.                         changes
  • Project the asterisk (*) into the query definition so   Having a backup table is not much use without a
    that all the fields are included in the results set.    means of using it to restore the data in your original
                                                            table. In this section, you will use an update query to


                                                                     Home      Previous     3 o f 16     Next


11. Action Queries                                                                                 Tutorial exercises


                    FIGURE 11.1: Use a make-table query to back up and existing table


                                                             aTransform the Select query into
                                                                Make Table query



                                                                 Provide a name for the new
                                                                  (target) table.




            the query definition.into
             Project all fields (*)



                                                                     Home      Previous     4 o f 16     Next
11. Action Queries                                                                                       Tutorial exercises


                                  FIGURE 11.2: Run the make-table query.

                      You can switch to datasheet mode to view the results
                      set. Note that this does not actually execute the query.




                                                         Query  Run. query, you must select
                                                          To execute the
                                                                         Alternatively, you can
                                                              press the “run” (!) icon on the toolbar.




                                                                The warning box reminds you that you
                                                                are about to make permanent changes
                                                                to the data in the database.


                                                                       Home       Previous      5 o f 16       Next


11. Action Queries                                                                                       Tutorial exercises

replace some of the values in your Courses table
                                                                FIGURE 11.3: Create an ad hoc relationship
with values from your CoursesBackup table.
                                                                    between the table and its backup.
  • Create a new query based on the Courses and
    CoursesBackup tables.
  • Since no relationship exists between these
    tables, create an ad hoc relationship within the
    query as shown in Figure 11.3.
  • Select Query  Update from the main menu. Note
    that this results in the addition of an Update To
    row in the query definition grid.
  • Project Credits into the query definition and fill
    in the Update To row as shown in Figure 11.4.
  • Save the query as qryRollbackCredits.
Now is a good point to stop and interpret what you                 counterparts in thethe key on to their
                                                                    Drag the fields in
                                                                                        backup table.
have done so far:
1. By creating a relationship between the Courses                       You cannot drag two fields at once or
   table and its backup, you are joining together the                   enforce referential integrity in a QBE
                                                                        relationship like you can in the main
   records from both tables that satisfy the condi-                     relationship editor.



                                                                       Home       Previous      6 o f 16       Next
11. Action Queries                                                                              Tutorial exercises

                                                           tion:
     FIGURE 11.4: Fill in the Update To field.
                                                           Courses.DeptCode =
                                                             CoursesBackup.DeptCode AND
   the query an update query. make
    Select Query  Update to
                                                             Courses.CrsNum =
                                                             CoursesBackup.CrsNum.
                                                        2. By projecting Courses.Credits into the query,
                                                           you are making it the target for the update. In
                                                           other words, the values in Courses.Credits
                                                           are going to be modified by the update action.
                                                        3. By setting the Update To field to Courses-
                                                           Backup.Credits, you are telling Access to
                                                           replace the contents of Courses.Credits with
                                                           the contents of CoursesBackup.Credits.
                                                        Whenever this query is run, it will replace whatever is
                                                        in the Credits field of all the records in the
                                                        Courses table with values from the backup. You will
                                                        use this query to “rollback” updates made later on.

   syntax totable name.field name
    Use the
              disambiguate the field name.


                                                                   Home    Previous      7 o f 16     Next


11. Action Queries                                                                              Tutorial exercises

11.3.3 Using an update query to make
                                                            FIGURE 11.5: Create an update query that
       selective changes                                        updates a subset of the records.
Now that you have an infrastructure for undoing any
errors, you can continue with the task of updating
credits for the Commerce department.
  • Create an update query based on the Courses
    table and save it as qryUpdateCredits.
                                                                                        To fieldUpdate
                                                                                         Set the
                                                                                                  to replace
                                                                                              Credits with
  • Set the Update To field to [Courses]*1.5.                                                 Credits × 1.5
    Note that if you do not include the square brack-
    ets, Access will interpret Courses as a literal
    string rather than a field name.

      Since this particular query only contains one
      table, the table name.field name
      syntax is not required for specifying the
      Update To expression.

 • Since you only want to apply the change to Com-             the update. Note limitDeptCodeofis
                                                                Add a criteria to
                                                                                  that
                                                                                       the scope
   merce courses, enter a criterion for the Dept-                   not changed in any way by this query.
   Code field, as shown in Figure 11.5.

                                                                   Home    Previous      8 o f 16     Next
11. Action Queries                                                                               Tutorial exercises

 • Run the query and verify that update has been          11.3.5 Attaching action queries to
   performed successfully.                                       buttons
                                                          As a designer, you should not expect your users to
11.3.4 Rolling back the changes                           understand your query naming convention, rum-
While testing the qryUpdateCredits query, your            mage through the queries listed in the database win-
exuberance may have led you to execute it more            dow, and execute the queries that need to be
than once. To return the Courses table to its state       executed. As such, it is often useful to create buttons
before any updates, all you need to do it run your        on forms and “attach” the action queries to the but-
rollback query.                                           tons. When the button is pressed, the query is exe-
  • Run qryRollback credits by double-clicking its        cuted.
    icon in the database window.
                                                          Although we have not yet discussed buttons (or
      Once an action query is created, it has more        events in general), the button wizard makes the cre-
      in common with subroutines written in Visual        ation of this type of form object straightforward.
      Basic than standard select queries. As such, it       • Modify qryUpdateCredits so that it updates
      is best to think of action queries in terms of          only those departments matching the DeptCode
      procedures to be executed rather than virtual           value in the frmDepartments table (see
      tables or views. Double-clicking an action              Figure 11.6).
      query executes it.                                    • Save the resulting action parameter query as
                                                              pqryUpdateCredits and close it.


                                                                   Home      Previous     9 o f 16     Next


11. Action Queries                                                                               Tutorial exercises


   FIGURE 11.6: Create an action parameter query to update Credits for a particular department.




      specifies theoperation
       The update
                     action to                         update to those records scope of the
                                                        The criterion limits the
                                                                                 matching
           perform on the records.                         the current parameter value



                                                                   Home      Previous     10 o f 16    Next
11. Action Queries                                                                        Application to the assignment

 • Switch to the design view of frmDepartments                 • Create backup copies of your Products and
   and add a button as shown in Figure 11.7.                     BackOrders tables using make-tables queries.
 • Attach the pqryUpdateCredits query to the                     Save these queries but note that they only need
   button as shown in Figure 11.8.                               to be run once.
 • Provide a caption and a name for the button as              • Create a rollback query that allows you to return
   shown in Figure 11.9.                                         your Products table to its original state.
 • Switch to form view. Press the button to run the          Rolling back the BackOrders table is more complex
   query (alternatively, use the shortcut key by             than rolling back the Products table. This is
   pressing Alt-U) as shown in Figure 11.10.                 because we are making the assumption that no
                                                             products are ever added or deleted to the system. As
11.4 Application to the assignment                           such, all the information needed for the rollback is in
                                                             the backup copy of Products.
11.4.1 Rolling back your master tables
                                                             In contrast, records are added to the BackOrders
As you begin to implement the transaction process-           table on a regular basis. As a result, the Back-
ing component of your system, it is worthwhile to            Orders table and its backup may contain a different
have a means of returning your master tables to their        number of records. If so, the match-and-replace pro-
original state (i.e., their state when you started devel-    cess used for rolling back Products is inappropri-
oping the system).                                           ate.



                                                                         Home     Previous     11 o f 16   Next


11. Action Queries                                                                        Application to the assignment


                      FIGURE 11.7: Add a button to the form using the button wizard.



                  thethere is insufficient space fortoa the rightdrag
                   If
                       border of the detail section
                                                         button,




                                                                                           wizard button in the
                                                                                            Ensure that the

                                                                                                toolbox is
                                                                                                depressed (wizards
                                                                                                are activated).




                                         Select the “command button” tool and click
                                          on an appropriate location on the form detail
                                          section. The button wizard should appear


                                                                         Home     Previous     12 o f 16   Next
11. Action Queries                                                           Application to the assignment


                 FIGURE 11.8: Use the wizard to attach an action query to the button.


                                                                     perform can bedifferentto
                                                                      Buttons
                                                                              many
                                                                                     created
                                                                                              actions
                                                                         in Access. The button wizard
                                                                         organizes these actions into
                                                                         categories. Select
                                                                         Miscellaneous  Run Query.




   queries (including non-action queries).
    The wizard lists all the available
       Select pqryUpdateCredits.



                                                             Home     Previous    13 o f 16    Next


11. Action Queries                                                           Application to the assignment


                FIGURE 11.9: Use the wizard to attach a query to a button (continued)


      You can show either a picture (icon) or a caption
       on the button. Enter a suitable caption.
                                                                         Including an ampersand () in
                                                                         the caption creates a shortcut
                                                                         key from the letter immediately
                                                                         following the ampersand.
                                                                         Shortcut keys can be invoked
                                                                         using the Alt-letter
                                                                         combination (the letter is
                                                                         underlined). In this case, Alt-U
                                                                         moves the focus directly to the
                                                                         button.




                                                                 button. The cmd prefixname for the
                                                                  Provide a meaningful
                                                                                         indicates a
                                                                      command button.



                                                             Home     Previous    14 o f 16    Next
11. Action Queries                                                                  Application to the assignment


                     FIGURE 11.10: Execute the action query by pressing the button.



           (or press Alt-U to use the shortcut). query
            Press the button to execute the action




                                                                    Home     Previous     15 o f 16   Next


11. Action Queries                                                                  Application to the assignment

The easiest way to rollback the BackOrders table is        ries. These queries will allow you to perform
to delete all the records it contains and use an           reasonably complex transaction processing opera-
append query to replace the records from the               tions on your master tables.
backup.                                                      • Create an update query to add all products in a
  • Open your BackOrders table in datasheet mode               shipment to inventory.
    and select Edit  Select All Records from the
    menu (alternatively, press Control-A)                        Note that this query should only process ship-
  • Press the Delete key.                                        ment details for the current shipment (i.e., it
  • Create an append query that adds the records                 should be based on a parameter query similar
    in the backup table to the BackOrders table.                 to the one you created in Section 10.4).
Once you learn the Access macro language or                 • Create a button on the shipments form to perform
Visual Basic for Applications, you will be able to write      this update.
a small procedure to execute these steps for you.           • Create an update query to subtract items from
For the assignment, however, this “manual rollback”           inventory when you process an order from your
is sufficient.                                                customers. Do not attach this query to a button at
                                                              this point.
11.4.2 Processing transactions
You are now in a position to combine parameter que-              This query should only process order details
ries and action queries into parameter-action que-               from the current order.


                                                                    Home     Previous     16 o f 16   Next
Access Tutorial 12: An Introduction to Visual Basic
12.1 Introduction: Learning the                                     simple programs we are writing here, these
     basics of programming                                          terms are interchangeable.

Programming can be an enormously complex and                 12.1.1 Interacting with the interpreter
difficult activity. Or it can be quite straightforward. In
                                                             Access provides two ways of interacting with the
either case, the basic programming concepts remain
                                                             VBA language. The most useful of these is through
the same. This tutorial is an introduction to a handful
                                                             saved modules that contain VBA procedures. These
of programming constructs that apply to any “third
                                                             procedures (subroutines and functions) can be run to
generation” language, not only Visual Basic for
                                                             do interesting things like process transactions
Applications (VBA).
                                                             against master tables, provide sophisticated error
       Strictly speaking, the language that is               checking, and so on.
       included with Access is not Visual Basic—it is        The second way to interact with VBA is directly
       a subset of the full, stand-alone Visual Basic        through the interpreter. Interpreted languages are
       language (which Microsoft sells separately).          easier to experiment with since you can invoke the
       In Access version 2.0, the subset is called           interpreter at any time, type in a command, and
       “Access Basic”. In version 7.0, it is slightly        watch it execute. In the first part of this tutorial, you
       enlarged subset called “Visual Basic for Appli-       are going to invoke Access’ VBA interpreter and exe-
       cations” (VBA). However, in the context of the        cute some very simple statements.


© Michael Brydon (brydon@unixg.ubc.ca)
Last update: 25-Aug-1997                                              Home       Previous     1 o f 16    Next


12. An Introduction to Visual Basic                                                               Learning objectives

In the second part of the tutorial, you are going to         12.3 Tutorial exercises
create a couple of VBA modules to explore looping,
conditional branching, and parameter passing.                12.3.1 Invoking the interpreter
                                                              • Click on the module tab in the database window
12.2 Learning objectives                                        and press New.
      What is the debug/immediate window? How               This opens the module window which we will use in
       do I invoke it?                                       Section 12.3.3. You have to have a module window
      What are statements, variables, the                   open in order for the debug window to be available
       assignment operator, and predefined                   from the menu.
       functions?                                              • Select View  Debug Window from the main
      How do I create a module containing VBA                   menu. Note that Control-G can be used in ver-
                                                                 sion 7.0 and above as a shortcut to bring up the
       code?
   
                                                                 debug window.
       What are looping and conditional branching?

                                                              
       What language constructs can I use to                        In version 2.0, the “debug” window is called
       implement them?                                              the “immediate” window. As such, you have to
      How do I use the debugger in Access?                         use View  Immediate Window. The term

      What is the difference between an interpreted
                                                                    debug window will be used throughout this
                                                                    tutorial.
       and compiled programming language?

                                                                      Home       Previous     2 o f 16    Next
12. An Introduction to Visual Basic                                                                 Tutorial exercises

12.3.2 Basic programming constructs                         12.3.2.2 Variables and assignment
In this section, we are going to use the debug win-         A variable is space in memory to which you assign a
dow to explore some basic programming constructs.           name. When you use the variable name in expres-
                                                            sions, the programming language replaces the vari-
12.3.2.1 Statements
                                                            able name with the contents of the space in memory
Statements are special keywords in a programming            at that particular instant.
language that do something when executed. For                 • Type the following:
example, the Print statement in VBA prints an                   s = “Hello”↵
expression on the screen.                                       ? s  “ world”↵
  • In the debug window, type the following:                    ? “s”  “ world”↵
    Print “Hello world!”↵
                                                            In the first statement, a variable s is created and the
(the ↵ symbol at the end of a line means “press the         string Hello is assigned to it. Recall the function of
Return or Enter key”).                                      the concatenation operator () from Section 4.4.2.
       In VBA (as in all dialects of BASIC), the ques-             Contrary to the practice in languages like C
       tion mark (?) is typically used as shorthand for            and Pascal, the equals sign (=) is used to
       the Print statement. As such, the statement:                assign values to variables. It is also used as
       ? “Hello world!”↵ is identical to the                       the equivalence operator (e.g., does x = y?).
       statement above.



                                                                     Home      Previous      3 o f 16     Next


12. An Introduction to Visual Basic                                                                 Tutorial exercises

When the second statement is executed, VBA recog-           is a function that is provided as part of the program-
nizes that s is a variable, not a string (since it is not   ming environment.
in quotations marks). The interpreter replaces s with       For example, cos(x) is a predefined function in
its value (Hello) before executing the Print com-           many computer languages—it takes some number x
mand. In the final statement, s is in quotation marks       as an argument, does some processing to find its
so it is interpreted as a literal string.                   cosine, and returns the answer. Note that since this
                                                            function is predefined, you do not have to know any-
       Within the debug window, any string of char-
                                                            thing about the algorithm used to find the cosine, you
       acters in quotations marks (e.g., “COMM”) is
                                                            just have to know the following:
       interpreted as a literal string. Any string with-
       out quotation marks (e.g., COMM) is interpreted      1. what to supply as inputs (e.g., a valid numeric
       as a variable (or a field name, if appropriate).        expression representing an angle in radians),
       Note, however, that this convention is not uni-      2. what to expect as output (e.g., a real number
       versally true within different parts of Access.         between -1.0 and 1.0).

12.3.2.3 Predefined functions                                      The on-line help system provides these two
                                                                   pieces of information (plus a usage example
In computer programming, a function is a small pro-
                                                                   and some additional remarks) for all VBA pre-
gram that takes one or more arguments (or param-
                                                                   defined functions.
eters) as input, does some processing, and returns
a value as output. A predefined (or built-in) function


                                                                     Home      Previous      4 o f 16     Next
12. An Introduction to Visual Basic                                                          Tutorial exercises

In this section, we are going to explore some basic
                                                       FIGURE 12.1: Interacting with the Visual Basic
predefined functions for working with numbers and
                                                                        interpreter.
text. The results of these exercises are shown in
Figure 12.1.
  • Print the cosine of 2π radians:
    pi = 3.14159↵
    ? cos(2*pi)↵                                                                     The argument contains
  • Convert a string of characters to uppercase:                                     an expression.
    s = “basic or cobol”↵
    ? UCase(s)↵                                                                      UCase() converts a
                                                                                     string to uppercase.
  • Extract the middle six characters from a string
    starting at the fifth character:
    ? mid (s,5,6)↵                                                                   Mid() extracts
                                                                                     characters from the
12.3.2.4 Remark statements                                                           string defined earlier.
When creating large programs, it is considered good
programming practice to include adequate internal
documentation—that is, to include comments to
explain what the program is doing.



                                                               Home      Previous     5 o f 16     Next


12. An Introduction to Visual Basic                                                          Tutorial exercises

Comment lines are ignored by the interpreter when
                                                      FIGURE 12.2: The declarations page of a Visual
the program is run. To designate a comment in VBA,
                                                                     Basic module.
use an apostrophe to start the comment, e.g.:
   ‘ This is a comment line!
   Print “Hello” ‘the comment starts
    here
The original REM (remark) statement from BASIC
can also be used, but is less common.
   REM This is also a comment (remark)

12.3.3 Creating a module
                                                      strings are compared (e.g., does uppercase/ lower-
 • Close the debug window so that the declaration
                                                      case matter?). The Option Explicit statement
   page of the new module created in
                                                      forces you to declare all your variables before using
   Section 12.3.3 is visible (see Figure 12.2).       them.
The two lines:
Option Compare Database
Option Explicit                                            In version 2.0, Access does not add the
                                                            Option Explicit statement by default. As
are included in the module by default. The Option           such you should add it yourself.
Compare statement specifies the way in which


                                                               Home      Previous     6 o f 16     Next
12. An Introduction to Visual Basic                                                             Tutorial exercises

A module contains a declaration page and one or         12.3.4 Creating subroutines with looping
more pages containing subroutines or user-defined              and branching
functions. The primary difference between subrou-       In this section, you will explore two of the most pow-
tines and functions is that subroutines simply exe-
                                                        erful constructs in computer programming: looping
cute whereas functions are expected to return a         and conditional branching.
value (e.g., cos()). Since only one subroutine or
                                                          • Create a new subroutine by typing the following
function shows in the window at a time, you must            anywhere on the declarations page:
use the Page Up and Page Down keys to navigate
                                                            Sub LoopingTest()↵
the module.
                                                        Notice that Access creates a new page in the mod-

     The VBA editor in version 8.0 has a number of     ule for the subroutine, as shown in Figure 12.3.
      enhancements over earlier version, including      12.3.4.1 Declaring variables
      the capability of showing multiple functions
                                                        When you declare a variable, you tell the program-
      and subroutines on the same page.
                                                        ming environment to reserve some space in memory
                                                        for the variable. Since the amount of space that is
                                                        required is completely dependent on the type of data
                                                        the variable is going to contain (e.g., string, integer,
                                                        Boolean, double-precision floating-point, etc.), you




                                                                 Home       Previous     7 o f 16     Next


12. An Introduction to Visual Basic                                                             Tutorial exercises

                                                         • Save the module as basTesting.
     FIGURE 12.3: Create a new subroutine.              One of the most useful looping constructs is For
                                                        condition... Next. All statements between
                                                        the For and Next parts are repeated as long as the
                                                        condition part is true. The index i is automati-
                                                        cally incremented after each iteration.
                                                          • Enter the remainder of the LoopingTest pro-
                  You can use the procedure                 gram:
                  combo box to switch between
                  procedures in a module.                   s = “Loop number: ”
                                                            For i = 1 To 10
have to include data type information in the declara-           Debug.Print s  i
tion statement.                                             Next i
                                                          • Save the module.
In VBA, you use the Dim statement to declare vari-
ables.                                                         It is customary in most programming lan-
  • Type the following into the space between the              guages to use the Tab key to indent the ele-
    Sub... End Sub pair:                                       ments within a loop slightly. This makes the
    Dim i as integer                                           program more readable.
    Dim s as string


                                                                 Home       Previous     8 o f 16     Next
12. An Introduction to Visual Basic                                                               Tutorial exercises

Note that the Print statement within the subroutine
                                                                 FIGURE 12.4: Run the LoopingTest
is prefaced by Debug. This is due to the object-ori-
                                                                   subroutine in the debug window.
ented nature of VBA which will be explored in greater
detail in Tutorial 14.
12.3.4.2 Running the subroutine
Now that you have created a subroutine, you need to
run it to see that it works. To invoke a subroutine, you
simply use its name like you would any statement.
  • Select View  Debug Window from the menu (or
    press Control-G in version 7.0).
  • Type: LoopingTest↵ in the debug window, as
    shown in Figure 12.4.
12.3.4.3 Conditional branching
We can use a different looping construct, Do Until
condition... Loop, and the conditional
branching construct, If condition Then...
Else, to achieve the same result.
                                                              by typing its name in the debug window.
                                                               Invoke the LoopingTest subroutine




                                                                    Home      Previous     9 o f 16     Next


12. An Introduction to Visual Basic                                                               Tutorial exercises

 • Type the following anywhere under the End Sub              Loop
   statement in order to create a new page in the           • Run the program
   module:
   Sub BranchingTest↵                                      12.3.5 Using the debugger
 • Enter the following program:                            Access provides a rudimentary debugger to help you
   Dim i As Integer                                        step through your programs and understand how
   Dim s As String                                         they are executing. The two basic elements of the
   Dim intDone As Integer                                  debugger used here are breakpoints and stepping
   s = “Loop number: “                                     (line-by-line execution).
   i = 1                                                      • Move to the s = “Loop number: ” line in your
   intDone = False                                              BranchingTest subroutine and select Run 
   Do Until intDone = True                                      Toggle Breakpoint from the menu (you can also
      If i  10 Then                                            press F9 to toggle the breakpoint on a particular
          Debug.Print “All done”                                line of code).
          intDone = True                                   Note that the line becomes highlighted, indicating the
      Else                                                 presence of an active breakpoint. When the program
          Debug.Print s  i                                runs, it will suspend execution at this breakpoint and
          i = i + 1                                        pass control of the program back to you.
      End If


                                                                    Home      Previous    10 o f 16     Next
12. An Introduction to Visual Basic                                                       Tutorial exercises

 • Run the subroutine from the debug window, as
                                                        FIGURE 12.5: Execution of the subroutine is
   shown in Figure 12.5.
                                                              suspended at the breakpoint.
 • Step through a couple of lines in the program
   line-by-line by pressing F8.
By stepping through a program line by line, you can
usually find any program bugs. In addition, you can
use the debug window to examine the value of vari-
ables while the program’s execution is suspended.
 • click on the debug window and type
   ? i↵
   to see the current value of the variable i.

12.3.6 Passing parameters
In the BranchingTest subroutine, the loop starts                           The outlined box indicates the
                                                                           current location of the
at 1 and repeats until the counter i reaches 10. It                        interpreter in the program. Press
may be preferable, however, to set the start and fin-                      F8 to execute the line of code.
ish quantities when the subroutine is called from the
debug window. To achieve this, we have to pass
parameters (or arguments) to the subroutine.


                                                              Home     Previous    11 o f 16    Next


12. An Introduction to Visual Basic                                                       Tutorial exercises

The main difference between passed parameters
                                                        FIGURE 12.6: Highlight the code to copy it.
and other variables in a procedure is that passed
parameters are declared in the first line of the sub-
routine definition. For example, following subroutine
declaration
    Sub BranchingTest(intStart as
      Integer, intStop as Integer)
not only declares the variables intStart and
intStop as integers, it also tells the subroutine to
expect these two numbers to be passed as parame-
ters.
To see how this works, create a new subroutine
called ParameterTest based on Branch-
ingTest.
 • Type the declaration statement above to create
    the ParameterTest subroutine.
 • Switch back to BranchingTest and highlight all
    the code except the Sub and End Sub state-
    ments, as shown in Figure 12.6.


                                                              Home     Previous    12 o f 16    Next
12. An Introduction to Visual Basic                                                         Tutorial exercises

 • Copy the highlighted code to the clipboard (Con-   12.3.7 Creating the Min() function
   trol-Insert), switch to ParameterTest, and         In this section, you are going to create a user-
   paste the code (Shift-Insert) into the Parame-     defined function that returns the minimum of two
   terTest procedure.                                 numbers. Although most languages supply such a
To incorporate the parameters into ParameterT-        function, Access does not (the Min() and Max()
est, you will have to make the following modifica-    function in Access are for use within SQL statements
tions to the pasted code:                             only).
  • Replace i = 1 with i = intStart.                    • Create a new module called basUtilities.
  • Replace i  10 with i  intStop.                    • Type the following to create a new function:
  • Call the subroutine from the debug window by          Function MinValue(n1 as Single, n2
    typing:                                               as Single) as Single↵
    ParameterTest 4, 12↵                              This defines a function called MinValue that returns
                                                      a single-precision number. The function requires two
      If you prefer enclosing parameters in brack-
                                                      single-precision numbers as parameters.
      ets, you have to use the Call sub
      name(parameter1, ..., parametern)                    Since a function returns a value, the data type
      syntax. For example:                                  of the return value should be specified in the
      Call ParameterTest(4,12)↵                             function declaration. As such, the basic syn-
                                                            tax of a function declaration is:


                                                               Home     Previous     13 o f 16    Next


12. An Introduction to Visual Basic                                                                Discussion

      Function function                              12.4 Discussion
      name(parameter1 As data type,
      …, parametern As data type) As                12.4.1 Interpreted and compiled
      data type                                            languages
      The function returns a variable named
                                                      VBA is an interpreted language. In interpreted lan-
      function name.
                                                      guages, each line of the program is interpreted (con-
 • Type the following as the body of the function:    verted into machine language) and executed when
                                                      the program is run. Other languages (such as C,
   If n1 = n2 Then
                                                      Pascal, FORTRAN, etc.) are compiled, meaning
      MinValue = n1
                                                      that the original (source) program is translated and
   Else
                                                      saved into a file of machine language commands.
      MinValue = n2
                                                      This executable file is run instead of the source
   End If
                                                      code.
 • Test the function, as shown in Figure 12.7.
                                                      Predictably, compiled languages run much faster
                                                      then interpreted languages (e.g., compiled C++ is
                                                      generally ten times faster than interpreted Java).
                                                      However, interpreted languages are typically easier
                                                      to learn and experiment with.



                                                               Home     Previous     14 o f 16    Next
12. An Introduction to Visual Basic                                                                 Discussion


                              FIGURE 12.7: Testing the MinValue() function.


                             function using conditional branching.
                              Implement the MinValue()


                                                                          various parameterby passing it
                                                                           Test the function
                                                                                             values.



                                                                              According to the function
                                                                              declaration, MinValue()
                                                                              expects two single-precision
                                                                              numbers as parameters.
                                                                              Anything else generates an error.




      These five lines could be replaced with one line:
      MinValue = iif(n1 = n2, n1, n2)


                                                                  Home     Previous    15 o f 16    Next


12. An Introduction to Visual Basic                                               Application to the assignment

12.5 Application to the assignment
You will need a MinValue() function later in the
assignment when you have to determine the quantity
to ship.
  • Create a basUtilities module in your assign-
    ment database and implement a MinValue()
    function.

      To ensure that no confusion arises between
      your user-defined function and the built-in
      SQL Min() function, do not call you function
      Min().




                                                                  Home     Previous    16 o f 16    Next
Access Tutorial 13: Event-Driven Programming
                              Using Macros
13.1 Introduction: What is event-                             the order entry is complete, the inventory update
     driven programming?                                      module is executed, and so on.
                                                              Event-driven programming, graphical user interfaces
In conventional programming, the sequence of oper-
ations for an application is determined by a central          (GUIs), and object-orientation are all related since
                                                              forms (like those created in Tutorial 6) and the
controlling program (e.g., a main procedure). In
                                                              graphical interface objects on the forms serve as the
event-driven programming, the sequence of opera-
                                                              skeleton for the entire application. To create an
tions for an application is determined by the user’s
                                                              event-driven application, the programmer creates
interaction with the application’s interface (forms,
menus, buttons, etc.).                                        small programs and attaches them to events associ-
                                                              ated with objects, as shown in Figure 13.1. In this
For example, rather than having a main procedure
                                                              way, the behavior of the application is determined by
that executes an order entry module followed by a             the interaction of a number of small manageable pro-
data verification module followed by an inventory
                                                              grams rather than one large program.
update module, an event-driven application remains
in the background until certain events happen: when
a value in a field is modified, a small data verification
program is executed; when the user indicates that


© Michael Brydon (brydon@unixg.ubc.ca)
Last update: 25-Aug-1997                                               Home      Previous      1 o f 26   Next


13. Event-Driven Programming Using Macros                            Introduction: What is event-driven programming?

                                                              13.1.1 Triggers
     FIGURE 13.1: In a trigger, a procedure is
             attached to an event.                            Since events on forms “trigger” actions, event/proce-
                                                              dure combinations are sometimes called triggers.
                                  An object, such as the
    interface object              button created in           For example, the action query you attached to a but-
  cmdUpdateCredits                Section 11.3.5, has         ton in Section 11.3.5 is an example of a simple, one-
                                  predefined properties and   action trigger. However, since an action query can
   properties                     events. For a button, the
     Caption                      most important event is     only perform one type of action, and since you typi-
     Enabled                      On Click.                   cally have a number of actions that need to be per-
     ...                                                      formed, macros or Visual Basic procedures are
   events                                procedure            typically used to implement a triggers in Access.
    On Click
    On Got Focus
    ...                                                       13.1.2 The Access macro language
                                                              As you discovered in Tutorial 12, writing simple VBA
 A procedure (such as an                                      programs is not difficult, but it is tedious and error-
 action query, macro, or VBA                                  prone. Furthermore, as you will see in Tutorial 14,
 function or subroutine) can be                               VBA programming becomes much more difficult
 attached to an event. When
 the event occurs, the                                        when you have to refer to objects using the naming
 procedure is executed.                                       conventions of the database object hierarchy. As a
                                                              consequence, even experienced Access program-


                                                                       Home      Previous      2 o f 26   Next
13. Event-Driven Programming Using Macros                                                      Learning objectives

mers often turn to the Access macro language to            attach the procedure to the correct event of the cor-
implement basic triggers.                                  rect object.
The macro language itself consists of 40 or so com-
                                                                  Selecting the correct object and the correct
mands. Although it is essentially a procedural lan-
                                                                  event for a trigger is often the most difficult
guage (like VBA), the commands are relatively high
                                                                  part of creating an event-driven application. It
level and easy to understand. In addition, the macro
                                                                  is best to think about this carefully before you
editor simplifies the specification of the action argu-
                                                                  get too caught up in implementing the proce-
ments (parameters).
                                                                  dure.
13.1.3 The trigger design cycle
                                                           13.2 Learning objectives
                                                              
To create a trigger, you need to answer two ques-
tions:                                                            What is event-driven programming? What is a
                                                                  trigger?
1. What has to happen?
2. When should it happen?                                        How do I design a trigger?
Once you have answered the first question (“what”),              How does the macro editor in Access work?
you can create a macro (or VBA procedure) to exe-                How do I attach a macro to an event?
cute the necessary steps. Once you know the
answer to the second question (“when”), you can
                                                                 What is the SetValue action? How is it used?



                                                                    Home      Previous     3 o f 26     Next


13. Event-Driven Programming Using Macros                                                         Tutorial exercises

      How do I make the execution of particular           13.3.1 The basics of the macro editor
       macro actions conditional?                          In this section, you are going to eliminate the warn-
      What is a switchboard and how do I create           ing messages that precede the trigger you created
       one for my application?                             Section 11.3.5.
      How to I make things happen when the                As such, the answer to the “what” question is the fol-
       application is opened?                              lowing:
      What are the advantages and disadvantages           1. Turn off the warnings so the dialog boxes do not
       of event-driven programming?                           pop up when the action query is executed;
                                                           2. Run the action query; and,
13.3 Tutorial exercises                                    3. Turn the warnings back on (it is generally good
                                                              programming practice to return the environment
In this tutorial, you will build a number of very simple
                                                              to its original state).
triggers using Access macros. These triggers, by
themselves, are not particularly useful and are            Since a number of things have to happen, you can-
intended for illustrative purposes only.                   not rely on an action query by itself. You can, how-
                                                           ever, execute a macro that executes several actions
                                                           including one or more action queries.




                                                                    Home      Previous     4 o f 26     Next
13. Event-Driven Programming Using Macros                                                         Tutorial exercises

 • Select the Macros tab from the database window
                                                             FIGURE 13.4: Bring up the On Click property for
   and press New. This brings up the macro editor
                                                                              the button.
   shown in Figure 13.2.
 • Add the three commands as shown in
   Figure 13.3. Note that the OpenQuery command
   is used to run the action query.
 • Save the macro as mcrUpdateCredits and
   close it.

13.3.2 Attaching the macro to the event
The answer to the “when” question is: When the
cmdUpdateCredits button is pressed. Since you
already created the button in Section 11.3.5, all you
need to do is modify its On Click property to point the
mcrUpdateCredits macro.
  • Open frmDepartments in design mode.
  • Bring up the property sheet for the button and
    scroll down until you find the On Click property,
                                                                            The button wizard attached a
    as shown in Figure 13.4.                                                VBA procedure to the button.


                                                                    Home      Previous     5 o f 26     Next


13. Event-Driven Programming Using Macros                                                         Tutorial exercises


                                        FIGURE 13.2: The macro editor.

   Macro actions can be selected from a list. The
   SetWarnings command is used to turn the warning                         In the comment column, you can
   messages (e.g., before you run an action query) on and off.             document your macros as required


   Multiple commands are
   executed from top to
   bottom.

   Most actions have one or
   more arguments that
   determine the specific
   behavior of the action. In
   this case, the
   SetWarnings action is
   set to turn warnings off.

   The area on the right
   displays information about
   the action.



                                                                    Home      Previous     6 o f 26     Next
13. Event-Driven Programming Using Macros                                                    Tutorial exercises


                     FIGURE 13.3: Create a macro that answers the “what” question.



 the macro. commands to
  Add the three




 SetWarningsfor the two
  The arguments
                actions
      are straightforward. For the
      OpenQuery command,
      you can select the query to
      open (or run) from a list.
      Since this is an action
      query, the second and third
      arguments are not
      applicable.




                                                                Home     Previous     7 o f 26     Next


13. Event-Driven Programming Using Macros                                                    Tutorial exercises

 • Press the builder button ( ) beside the existing
                                                         FIGURE 13.5: Select the macro to attach to the
   procedure and look at the VBA subroutine cre-
                                                                      On Click property.
   ated by the button wizard. Most of this code is for
   error handling.

      Unlike the stand-along VBA modules you cre-
      ated in Tutorial 12, this module (collection of

                                                                 of available macrosget a list
      functions and subroutines) is embedded in                   Press the arrow to
      the frmDepartments form.

 • Since you are going to replace this code with a
   macro, you do not want it taking up space in your
   database file. Highlight the text in the subroutine
   and delete it. When you close the module win-
   dow, you will see the reference to the “event pro-
   cedure” is gone.
 • Bring up the list of choice for the On Click prop-
   erty as shown in Figure 13.5. Select mcrUp-
   dateCredits.



                                                                Home     Previous     8 o f 26     Next
13. Event-Driven Programming Using Macros                                                       Tutorial exercises

 • Switch to form view and press the button. Since             to modify the structure of the table until the
   no warnings appear, you may want to press the               query or form is closed.
   button a few times (you can always use your roll-
   back query to reset the credits to their original      • Set the Caption property to Credits updated?
   values).                                                 and the Default property to No as shown in
                                                            Figure 13.6.
13.3.3 Creating a check box to display                   Changes made to a table do not automatically carry
       update status information                         over to forms already based on that table. As such,
Since the warning boxes have been disabled for the       you must manually add the new field to the depart-
update credits trigger, it may be useful to keep track   ments form.
of whether courses in a particular department have        • Open frmDepartments in design mode.
already been updated.                                     • Make sure the toolbox and field list are visible.
                                                            Notice that the new field (CrUpdated) shows up
To do this, you can add a field to the Departments
                                                            in the field list.
table to store this “update status” information.
                                                          • Use the same technique for creating combo
  • Edit the Departments table and add a Yes/No
                                                            boxes to create a bound check box control for the
    field called CrUpdated.
                                                            yes/no field. This is shown in Figure 13.7.
       If you have an open query or form based on
       the Departments table, you will not be able


                                                                  Home     Previous      9 o f 26     Next


13. Event-Driven Programming Using Macros                                                       Tutorial exercises

                                                         this section, you are going to use one of the most
 FIGURE 13.6: Add a field to the Departments
                                                         useful commands—SetValue—to automatically
    table to record the status of updates.
                                                         change the value of the CrUpdated check box.
                                                           • Open your mcrUpdateCredits macro in design
                                                             mode and add a SetValue command to change
                                                             the CrUpdated check box to Yes (or True, if
                                                             you prefer). This is shown in Figure 13.8.
                                                           • Save the macro and press the button on the form.
                                                             Notice that the value of the check box changes,
                                                             reminding you not to update the courses for a
                                                             particular department more than once.

                                                         13.3.5 Creating conditional macros
                                                         Rather than relying on the user not to run the update
                                                         when the check box is checked, you may use a con-
                                                         ditional macro to prevent an update when the
                                                         check box is checked.
13.3.4 The SetValue command
So far, you have used two commands in the Access
macro language: SetWarnings and OpenQuery. In

                                                                  Home     Previous     10 o f 26     Next
13. Event-Driven Programming Using Macros                                                         Tutorial exercises


             FIGURE 13.7: Add a check box control to keep track of the update status.



                                                                           from the toolbox.box tool
                                                                            Select the check




                                                                                       A check box is a control
                                                                                       that can be bound to fields
                                                                                       of the yes/no data type.
                                                                                       When the box is checked,
                                                                                       True is stored in the
                                                                                       table; when the box is
                            field list to the detail section.from the
                             Drag the CrUpdated field                                  unchecked, False is
                                                                                       stored.




                                                                   Home     Previous       11 o f 26    Next


13. Event-Driven Programming Using Macros                                                         Tutorial exercises


    FIGURE 13.8: Add a SetValue command to set the value of the update status field when the
                                    update is compete.

                      from the SetValue command
                       Pick
                            the list or simply type it in.




       The Item argument is the thing you                                    The Expression argument is the
                                                                               value you want the SetValue
        want the SetValue action to set the                                    action to set the value of the Item
        value of. You can use the builder or                                   to. Type in Yes (no quotation
        simply type in CrUpdate.                                               marks are required since Yes is
                                                                               recognized as a constant in this
                                                                               context).


                                                                   Home     Previous       12 o f 26    Next
13. Event-Driven Programming Using Macros                                                    Tutorial exercises

 • Select View  Conditions to display the condi-   13.3.5.1 The simplest conditional macro
   tions column in the macro editor as shown in     If there is an expression in the condition column of a
   Figure 13.9.                                     macro, the action in that row will execute if the condi-
    FIGURE 13.9: Display the macro editors          tion is true. If the condition is not true, the action will
             condition column                       be skipped.
                                                       • Fill in the condition column as shown in
                                                         Figure 13.10. Precede the actions you want to
                                                         execute if the check box is checked with [CrUp-
                                                         dated]. Precede the actions you do not want to
                                                         execute with Not [CrUpdated].

                                                           Since CrUpdated is a Boolean (yes/no) vari-
                                                           able, you do not need to write [CrUpdated]
                                                           = True or [CrUpdated] = False. The

      “conditions”  Conditions toolpress the
       Select View                or                       true and false parts are implied. However, if a
                    button on the     bar.                 non-Boolean data type is used in the expres-
                                                           sion, a comparison operator must be included
                                                           (e.g., [DeptCode] = “COMM”, [Cred-
                                                           its]  3, etc.)



                                                              Home       Previous     13 o f 26    Next


13. Event-Driven Programming Using Macros                                                    Tutorial exercises


            FIGURE 13.10: Create a conditional macro to control which actions execute.



   is true if the CrUpdated check box is
    The expression Not [CrUpdated]

       not checked. Use this expression in
       front of the actions you want to execute
       in this situation.


   true if the CrUpdated check box is
    The expression [CrUpdated] is

       checked. In this situation, you should
       indicate to the user that the update is
       not being performed.

      The MsgBox action displays a
       standard Windows message box. You
       can set the message and other message
       box features in the arguments section.




                                                              Home       Previous     14 o f 26    Next
13. Event-Driven Programming Using Macros                                                      Tutorial exercises

 • Switch to the form and test the macro by pressing   13.3.5.2 Refining the conditions
   the button. If the CrUpdated check box is           The macro shown in Figure 13.10 can be improved
   checked, you should get a message similar to        by using an ellipsis (…) instead of repeating the
   that shown in Figure 13.11.                         same condition in line after line. In this section, you
FIGURE 13.11: The action query is not executed         will simplify your conditional macro slightly.
    and the message box appears instead.               Move the message box action and condition to the
                                                       top of the list of actions by dragging its record selec-
                                                       tor (grey box on the left).
                                                         • Insert a new row immediately following the mes-
                                                           sage and add a StopMacro action, as shown in
                                                           Figure 13.12.
                                                       The macro in Figure 13.12 executes as follows: If
                                                       CrUpdate is true (i.e., the box is checked), the
                                                       MsgBox action executes. Since the next line has an
                                                       ellipsis in the condition column, the condition contin-
                                                       ues to apply. However, that action on the ellipsis line
                                                       is StopMacro, and thus the macro ends without
                                                       executing the next four lines.



                                                                Home       Previous     15 o f 26    Next


13. Event-Driven Programming Using Macros                                                      Tutorial exercises

                                                       If the CrUpdate box is not checked, the first two
FIGURE 13.12: Rearrange the macro actions and
                                                       lines are ignored (i.e., the lines with the false condi-
              insert a new row.
                                                       tion and the ellipsis) and the update proceeds.

         message box action to theand drag thelist.
          Click the record selector
                                    top of the
                                                       13.3.5.3 Creating a group of named macros
                                                       It is possible to store a number of related macros

                                   Add an ellipsis    together in one macro “module”. These group mac-
                                    (…) and a          ros have two advantages:
                                    StopMacro
                                    action.            1. Modular macros can be created — instead of
                                                          having a large macro with many conditions and
                                                          branches, you can create a small macro that call
                                                          other small macros.
                                                       2. Similar macros can be grouped together — for
                                                          example, you could keep all you Departments-
                                                          related macros or search-related macros in a
                                                          macro group.

   to insert a new rowyou would like
    Right-click where
                        and select
                                                       In this section, we will focus on the first advantage.
                                                         • Select View  Macro Names to display the macro
       Insert Row from the popup menu.
                                                           name column.


                                                                Home       Previous     16 o f 26    Next
13. Event-Driven Programming Using Macros                                                       Tutorial exercises

 • Perform the steps in Figure 13.13 to modularize      • Remove the scroll bars, navigation buttons, and
   your macro.                                            record selectors from the form using the form’s
 • Change the macro referred to in the On Click           property sheet.
   property of the cmdUpdateCredits button from         • Save the form as swbMain.
   mcrUpdateCredits to                                 There are two ways to add button-based triggers to a
   mcrUpdateCredits.CheckStatus.                       form:
 • Test the operation of the button.
                                                       1. Turn the button wizard off, create the button, and
                                                          attach an macro containing the appropriate
13.3.6 Creating switchboards
                                                          action (or actions).
One of the simplest (but most useful) triggers is an   2. Turn the button wizard on and use the wizard to
OpenForm command attached to a button on a form           select from a list of common actions (the wizard
consisting exclusively of buttons.                        writes a VBA procedure for you).
This type of “switchboard” (as shown in
Figure 13.14) can provide the user with a means of           Since the wizard can only attach one action to
navigating the application.                                  a button (such as opening a form or running
  • Create an unbound form as shown in                       an action query) it is less flexible than a
    Figure 13.15.                                            macro. However, once you are more comfort-
                                                             able with VBA, there is nothing to stop you




                                                                Home       Previous      17 o f 26    Next


13. Event-Driven Programming Using Macros                                                       Tutorial exercises


                       FIGURE 13.13: Use named macros to modularize the macro.


     the macro names column. to display
      Select View  Macro Names                                A macro executes until it encounters a
                                                               blank line. Use blank lines to separate the
                                                               named macros within a group.


     CheckStatusmacro called the
      Create a named
                     that contains
          conditional logic for the procedure.



         Create two other macros, Updated and
          NotUpdated that correspond to the
          logic in the CheckStatus macro.



     particular macro. action executes a to
      The RunMacro
                        Select the macro
          execute from a list in the arguments pane.
          Note the naming convention for macros
          within a macro group.



                                                                Home       Previous      18 o f 26    Next
13. Event-Driven Programming Using Macros                                                         Tutorial exercises


                      FIGURE 13.14: A switchboard interface to the application.


        The command buttons are placed on an             Although it is not shown here, switchboards can
        unbound form. Note the absence of scroll bars,   call other switchboards, allowing you to add a
        record selectors, or navigation buttons.         hierarchical structure to your application.




               Gratuitous clip art can be used to          Shortcut keys are include on each
               clutter your forms and reduce the           button to allow the user to navigate
               application’s overall performance.          the application with keystrokes.




                                                                Home       Previous      19 o f 26      Next


13. Event-Driven Programming Using Macros                                                         Tutorial exercises


                                                         FIGURE 13.15: Create an unbound form as the
                                                                 switchboard background.



                                                                 leave the “record source”wizard) and
                                                                  Select Design View (no
                                                                                           box empty.


                                                                 you can buildayour switchboard.
                                                                  The result is blank form on which




                                                                Home       Previous      20 o f 26      Next
13. Event-Driven Programming Using Macros                                                             Tutorial exercises

      from editing the VBA modules created by the           • Follow the directions provided by the wizard to
      wizard to add additional functionality.                 set the action for the button (i.e., open the frm-
                                                              Courses form) as shown in Figure 13.17.
13.3.6.1 Using a macro and manually-created                 • Change the button’s font and resize it as
          buttons                                             required.
 • Ensure the wizard is turned off and use the but-
   ton tool to create a button.                                   You can standardize the size of your form
 • Modify the properties of the button as shown in                objects by selecting more than one and using
   Figure 13.16.                                                  Format  Size  to Tallest and to Widest com-
 • Create a macro called                                          mands. Similarly, you can select more than
   mcrSwitchboard.OpenDept and use the                            one object and use the “multiple selection”
   OpenForm command to open the form frmDe-                       property sheet to set the properties all at
   partments.                                                     once.
 • Attach the macro to the On Click event of the
   cmdDepartments button.                                  13.3.7 Using an autoexec macro
 • Test the button.                                        If you use the name autoexec to save a macro (in
13.3.6.2 Using the button wizard                           lieu of the normal mcrname convention), Access
 • Turn the button wizard back on and create a new         will execute the macro actions when the database is
   button.                                                 opened. Consequently, auto-execute macros are



                                                                       Home       Previous     21 o f 26     Next


13. Event-Driven Programming Using Macros                                                             Tutorial exercises


                       FIGURE 13.16: Create a button and modify its appearance.


   (ensure the wizard activated).a button
    Use the button tool to create
                                                                        (e.g., cmdDepartments) and caption
                                                                         Give the button a meaningful name
                                                                              (including a shortcut key.).




                      Scroll down the property sheet and change
                       the value of the button’s Font Size property.
                       Resize the button by dragging its handles.



                                                                       Home       Previous     22 o f 26     Next
13. Event-Driven Programming Using Macros                                                      Tutorial exercises


        FIGURE 13.17: Use the command button wizard to create a button for the switchboard.


                          the action type associated with the button.as
                           Select Form Operations  Open Form



                                                                                        Provide a caption
                                                                                         for the button.




                                               from the list. form
                                                Select the correct




                                                                   Home     Previous    23 o f 26    Next


13. Event-Driven Programming Using Macros                                                      Tutorial exercises

often used to display a switchboard when the user        from the menu system. Consequently, you need to
starts the application.                                  know something about the menu structure of Access
Another typical auto-execute operation is to hide the    before you create your macro.
database window. By doing this, you unclutter the
screen and reduce the risk of a user accidentally
making a change to the application (by deleting a
                                                               In version 8.0, the DoMenuItem action has
                                                                been replaced by the slightly more intuitive
                                                                RunCommand action. See on-line help for
database object, etc.).
                                                                more information on RunCommand.
      To unhide the database window, select Win-
                                                           • Create an auto-execute macro
      dow  Unhide from the main menu or press
                                                           • Add the DoMenuItem and OpenForm actions to
      the database window icon ( ) on the toolbar.
                                                             hide the database window and open the main
The problem with hiding the database window using            switchboard, as shown in Figure 13.18.
a macro is that there is no HideDatabaseWindow             • Close the database and reopen it after a short
command in the Access macro language. As such,               delay to test the macro.
you have to rely on the rather convoluted DoMenu-
                                                                In version 7.0 and above, you do not need to
Item action.
                                                                use an autoexec macro to hide the database
As its name suggests, the DoMenuItem action per-                window and open a form. Instead, you can
forms an operation just as if it had been selected              right-click on the database window, select


                                                                   Home     Previous    24 o f 26    Next
13. Event-Driven Programming Using Macros                                                                Discussion

                                                             13.4 Discussion
 FIGURE 13.18: Create an auto-execute macro.
                                                             13.4.1 Event-driven programming versus
                                                                    conventional programming
                                                             The primary advantages of event-driven program-
                                                             ming are the following:
                                                             1. Flexibility — since the flow of the application is
                                                                controlled by events rather than a sequential pro-
                                                                gram, the user does not have to conform to the
                                                                programmer’s understanding of how tasks should
                                                                be executed.
   WindowDoMenuItem action, select the
    For the
             Hide commands from the
                                                             2. Robustness — Event-driven applications tend to
                                                                be more robust since they are less sensitive to
         Database menu (i.e., the menu that is active
         when the database window is being used).               the order in which users perform activities. In
                                                                conventional programming, the programmer has
                                                                to anticipate virtually every sequence of activities
       Startup, and fill in the properties for the appli-       the user might perform and define responses to
       cation.                                                  these sequences.



                                                                      Home      Previous     25 o f 26   Next


13. Event-Driven Programming Using Macros                                              Application to the assignment

The primary disadvantage of event-driven programs             • Create a main switchboard for you application. It
is that it is often difficult to find the source of errors      should provide links to all the database objects
when they do occur. This problem arises from the                your user is expected to have access to (i.e., your
object-oriented nature of event-driven applications—            forms).
since events are associated with a particular object
you may have to examine a large number of objects
before you discover the misbehaving procedure.
This is especially true when events cascade (i.e., an
event for one object triggers an event for a different
object, and so on).

13.5 Application to the assignment
 • Add “update status” check boxes to you transac-
   tion processing forms (i.e., Orders and Ship-
   ments)
 • Create a conditional macro for your Shipments
   form to prevent a particular shipment from being
   added to inventory more than once.




                                                                      Home      Previous     26 o f 26   Next
Access Tutorial 14: Data Access Objects
14.1 Introduction: What is the DAO                         that its modularity supports easier development and
     hierarchy?                                            maintenance of applications.
                                                           The disadvantage is that is you have to understand a
The core of Microsoft Access and an important part
                                                           large part of the hierarchy before you can write your
of Visual Basic (the stand-alone application develop-
ment environment) is the Microsoft Jet database            first line of useful code. This makes using VBA diffi-
                                                           cult for beginners (even for those with considerable
engine. The relational DBMS functionality of Access
comes from the Jet engine; Access itself merely pro-       experience writing programs in BASIC or other
                                                           3GLs*).
vides a convenient interface to the database engine.
Because the application environment and the data-          14.1.1 DAO basics
base engine are implemented as separate compo-
                                                           Although you probably do not know it, you already
nents, it is possible to upgrade or improve Jet
                                                           have some familiarity with the DAO hierarchy. For
without altering the interface aspects of Access, and
                                                           example, you know that a Database object (such as
vice-versa.
                                                           univ0_vx.mdb) contains other objects such as
Microsoft takes this component-based approach fur-         tables (TableDef objects) and queries (QueryDef
ther in that the interface to the Jet engine consists of   objects). Moving down the hierarchy, you know that
a hierarchy of components (or “objects”) called Data       TableDef objects contain Field objects.
Access Objects (DAO). The advantage of DAO is
                                                              * Third-generation programming languages.

© Michael Brydon (brydon@unixg.ubc.ca)
Last update: 25-Aug-1997                                            Home       Previous     1 o f 22      Next


14. Data Access Objects                                                  Introduction: What is the DAO hierarchy?

Unfortunately, the DAO hierarchy is somewhat more          every object has a number of properties that can be
complex than this. However, at this level, it is suffi-    either observed (read-only properties) or set (read/
cient to recognize three things about DAO:                 write properties). For example, each TableDef (table
1. Each object that you create is an instance of a         definition) object has a read-only property called
   class of similar objects (e.g., univ0_vx is a par-      DateCreated and a read/write property called Name.
   ticular instance of the class of Database objects).     To access an object’s properties in VBA, you nor-
2. Each object may contain one or more Collec-             mally use the object name.property
   tions of objects. Collections simply keep all           name syntax, e.g.,
   objects of a similar type or function under one         Employees.DateCreated.
   umbrella. For example, Field objects such as
                                                                  To avoid confusion between a property called
   DeptCode and CrsNum are accessible through a
                                                                  DateCreated and a field (defined by you)
   Collection called Fields).
                                                                  called DateCreated, Access version 7.0
3. Objects have properties and methods (see
                                                                  and above require that you use a bang (!)
   below).
                                                                  instead of a period to indicate a field name or
                                                                  some other object created by you as a devel-
14.1.2 Properties and methods
                                                                  oper. For example:
You should already be familiar with the concept of                Employees!DateCreated.Value
object properties from the tutorial on form design                identifies the Value property of the DateCre-
(Tutorial 6). The idea is much the same in DAO:


                                                                    Home       Previous     2 o f 22      Next
14. Data Access Objects                                                  Introduction: What is the DAO hierarchy?

      ated field (assuming one exists) in the                     object summaries in the on-line help if you are
      Employees table.                                            unsure.

Methods are actions or behaviors that can be               A more obvious example of a method is the Cre-
applied to objects of a particular class. In a sense,      ateField method of TableDef objects, e.g.:
they are like predefined functions that only work in       Employees.CreateField(“Phone”,
the context of one type of object. For example, all        dbText, 25)
Field objects have a method called FieldSize that          This creates a field called Phone, of type dbText (a
returns the size of the field. To invoke a object’s        constant used to represent text), with a length of 25
methods, you use the                                       characters.
object name.method [parameter1,
..., parametern] syntax, e.g.,:                            14.1.3 Engines, workspaces, etc.
DeptCode.FieldSize.                                        A confusing aspect of the DAO hierarchy is that you
                                                           cannot simply refer to objects and their properties as
      A reasonable question at this point might be:
                                                           done in the examples above. As Figure 14.1 illus-
      Isn’t FieldSize a property of a field, not a
                                                           trates, you must include the entire path through the
      method? The answer to this is that the imple-
                                                           hierarchy in order to avoid any ambiguity between,
      mentation of DAO is somewhat inconsistent in
                                                           say, the DeptCode field in the Courses TableDef
      this respect. The best policy is to look at the
                                                           object and the DeptCode field in the qryCourses
                                                           QueryDef object.

                                                                     Home       Previous     3 o f 22    Next


14. Data Access Objects                                                  Introduction: What is the DAO hierarchy?


                                 FIGURE 14.1: Navigating the DAO hierarchy.

        To access a particular field, you                 DBEngine                 By creating a database object at
        have to understand the structure                                           the start of your VBA
        of the DAO hierarchy.                                                      programs, you bypass the top
                                                        Workspaces                 part of the hierarchy.


                                                   Databases                                     other classes...

                TableDefs                          QueryDefs                    Recordsets       other classes...


     Courses           other tables...      qryCourses       other queries...

          Fields                                 Fields
                                                                                           Legend
           DeptCode                               DeptCode
                                                                            TableDefs        object or collection
         Indexes                                Indexes
                                                                            Courses          instance



                                                                     Home       Previous     4 o f 22    Next
14. Data Access Objects                                                                        Learning objectives

Working down through the hierarchy is especially           14.3 Tutorial exercises
confusing since the first two levels (DBEngine and
Workspaces) are essentially abstractions that have         14.3.1 Setting up a database object
no physical manifestations in the Access environ-
                                                           In this section you will write VBA code that creates a
ment. The easiest way around this is to create a           pointer to the currently open database.
Database object that refers to the currently open
                                                             • Create a new module called basDAOTest (see
database (e.g., univ0_vx.mdb) and start from the               Section 12.3.3 for information on creating a new
database level when working down the hierarchy.
                                                               module).
Section 14.3.1 illustrates this process for version 2.0.
                                                             • Create a new subroutine called PrintRecords.
                                                             • Define the subroutine as follows:
14.2 Learning objectives                                      Dim dbCurr As DATABASE
      What is the DAO hierarchy?                             Set dbCurr =
      What are objects? What are properties and               DBEngine.Workspaces(0).Databases(0)
       methods?                                               Debug.Print dbCurr.Name

      How do I create a reference to the current
                                                            • Run the procedure, as shown in Figure 14.2.
                                                           Let us examine these three statements one by one.
       database object? Why is this important?
      What is a recordset object?
                                                           1. Dim dbCurr As DATABASE
                                                              This statement declares the variable dbCurr as
      How do I search a recordset?                           an object of type Database. For complex objects

                                                                    Home      Previous     5 o f 22     Next


14. Data Access Objects                                                                           Tutorial exercises


                          FIGURE 14.2: Create a pointer to the current database.




        (dbCurr) toset the pointer
         Declare and
                     the current
            database.


        of thea database. the name
         Add line to print


            Although you can use the
            Print statement by itself
                                                                                         Run the procedure to
                                                                                          ensure it works.
            in the debug window, you
            must invoke the Print
            method of the Debug object                                  Version 7.0 and above support a less
            from a module—hence the                                     cumbersome way referring to the current
            Debug.Print syntax.                                         database—the CurrentDb function:
                                                                        Set dbCurr = CurrentDb


                                                                    Home      Previous     6 o f 22     Next
14. Data Access Objects                                                                           Tutorial exercises

   (in contrast to simple data types like integer,                Do not worry if you are not completely sure
   string, etc.) Access does not allocate memory                  what is going on at this point. As long as you
   space for a whole database object. Instead, it                 understand that you can type the above two
   allocates space for a pointer to a database                    lines to create a pointer to your database,
   object. Once the pointer is created, you must set              then you are in good shape.
   it to point to an object of the declared type (the
   object may exist already or you may have to cre-        3. Debug.Print dbCurr.Name
   ate it).                                                   This statement prints the name of the object to
2. Set dbCurr = DBEngine.Work-                                which dbCurr refers.
   spaces(0).Databases(0)
   (Note: this should be typed on one line). In this       14.3.2 Creating a Recordset object
   statement, the variable dbCurr (a pointer to a          As its name implies, a TableDef object does not con-
   Database object) is set to point to the first Data-     tain any data; instead, it merely defines the structure
   base in the first Workspace of the only Database        of a table. When you view a table in design mode,
   Engine. Since the numbering of objects within a         you are seeing the elements of the TableDef object.
   collection starts at zero, Databases(0) indi-           When you view a table in datasheet mode, in con-
   cates the first Database object. Note that the first    trast, you are seeing the contents of Recordset
   Database object in the Databases collection is          object associated with the table.
   always the currently open one.



                                                                    Home      Previous     7 o f 22     Next


14. Data Access Objects                                                                           Tutorial exercises

To access the data in a table using VBA, you have to       2. Sets rsCourses to point to the newly created
invoke the OpenRecordset method of the Data-                  recordset.
base object. Since most of the processing you do in        Note that this Set statement is different than the pre-
VBA involves data access, familiarity with Recordset       vious one since the OpenRecordset method
objects is essential. In this section, you will create a   results in a new object being created (dbCurr points
Recordset object based on the Courses table.               to an existing database—the one you opened when
  • Delete the Debug.Print dbCurr.Name line                you started Access).
    from your program.
  • Add the following:                                     14.3.3 Using a Recordset object
   Dim rsCourses As Recordset                              In this section, you will use some of the properties
   Set rsCourses =                                         and methods of a Recordset object to print its con-
    dbCurr.OpenRecordset(“Courses”)
                                                           tents.
The first line declares a pointer (rsCourses) to a           • Add the following to PrintRecords:
Recordset object. The second line does two things:
                                                              Do Until rsCourses.EOF
1. Invokes the OpenRecordset method of dbCurr                 Debug.Print rsCourses!DeptCode  “ ”
   to create a Recordset object based on the table              rsCourses!CrsNum
   named “Courses”. (i.e., the name of the table is           rsCourses.MoveNext
   a parameter for the OpenRecordset method).                 Loop
                                                            • This code is explained in Figure 14.3.


                                                                    Home      Previous     8 o f 22     Next
14. Data Access Objects                                                                           Tutorial exercises


          FIGURE 14.3: Create a program to loop through the records in a Recordset object.

                                                                             EOF is a property of the recordset.
                                                                             It is true if the record counter has
                                                                             reached the “end of file” (EOF)
                                                                             marker and false otherwise.

                                                                             The exclamation mark (!) indicates
                                                                             that DeptCode is a user-defined
                                                                             field (rather than a method or
                                                                             property) of the recordset object.


                                                                Since the Value property is the default property
                                                                of a field, you do not have to use the
                                                                recordset!field.Value syntax.



                                                                             The MoveNext method moves the
                                                                             record counter to the next record in
                                                                             the recordset.


                                                                   Home      Previous      9 o f 22     Next


14. Data Access Objects                                                                           Tutorial exercises

14.3.4 Using the FindFirst method                         WHERE condition (a string) that ensures that only one
In this section, you will use the FindFirst method        record is found.
of Recordset objects to lookup a specific value in a      For example, to get the Title of COMM 351 from
table.                                                    the Courses table, you would provide MyLookUp()
  • Create a new function called MyLookUp() using         with the following parameters:
    the following declaration:                            1. “Title” — a string containing the name of the
    Function MyLookUp(strField As                            field from which we want to return a value;
     String, strTable As String,                          2. “Course” — a string containing the name of the
     strWhere As String) As String                           source table; and,
An example of how you would use this function is to       3. “DeptCode = ‘COMM’ AND CrsNum =
return the Title of a course from the Courses                ‘335’” — a string that contains the entire
table with a particular DeptCode and CrsNum. In              WHERE clause for the search.
other words, MyLookUp() is essentially an SQL
statement without the SELECT, FROM and WHERE                    Note that both single and double quotation
clauses.                                                        marks must be used to signify a string within a
The parameters of the function are used to specify              string. The use of quotation marks in this
the name of the table (a string), the name of the field         manner is consistent with standard practice in
(a string) from which you want the value, and a                 English. For example, the sentence:
                                                                “He shouted, ‘Wait for me.’” illus-


                                                                   Home      Previous     10 o f 22     Next
14. Data Access Objects                                                                         Tutorial exercises

       trates the use of single quotes within double            Recordset object to be opened (the Find-
       quotes.                                                  First method only works with “dynaset” type
                                                                recordsets, hence the need to include the
 • Define the MyLookUp() function as follows:                   additional parameter in this segment of code).
   Dim dbCurr As DATABASE
   Set dbCurr = CurrentDb                                   rsRecords.FindFirst strWhere


      If you are using version 2.0, you cannot use             VBA uses a rather unique convention to
       the CurrentDb method to return a pointer to              determine whether to enclose the arguments
       the current database. You must use long form             of a function, subroutine, or method in paren-
       (i.e., Set dbCurr = DBEngine…)                           theses: if the procedure returns a value,
                                                                enclose the parameters in parentheses; oth-
   Dim rsRecords As Recordset                                   erwise, use no parentheses. For example, in
   Set rsRecords =                                              the line above, strWhere is a parameter of
    dbCurr.OpenRecordset(strTable,                              the FindFirst method (which does not
    dbOpenDynaset)
                                                                return a value).

      In version 2.0, the name of some of the pre-
       defined constants are different. As such, you
                                                            If Not rsRecords.NoMatch() Then
                                                            MyLookUp =
       must use DB_OPEN_DYNASET rather than
                                                             rsRecords.Fields(strField).Value
       dbOpenDynaset to specify the type of


                                                                  Home      Previous     11 o f 22    Next


14. Data Access Objects                                                                         Tutorial exercises

   Else                                                  need in your application, it is occasionally necessary
   MyLookUp = “”                                         to perform a stand-alone query—that is, to use the
   End If                                                DLookUp() function to retrieve a value from a table
 • Execute the function with the following statement     or query.
   (see Figure 14.4):                                    When using DLookUp() for the first few times, the
   ? MyLookUp(“Title”, “Courses”,                        syntax of the function calls may seem intimidating.
    “DeptCode = 'COMM' AND CrsNum =                      But all you have to remember is the meaning of a
    '351'”)
                                                         handful of constructs that you have already used.
As it turns out, what you have implemented exists        These constructs are summarized below:
already in Access in the form of a predefined func-        • Functions — DLookUp() is a function that
tion called DLookUp().                                       returns a value. It can be used in the exact same
  • Execute the DLookUp() function by calling it in          manner as other functions, e.g.,
    the same manner in which you called                      x = DLookUp(…) is similar to
    MyLookUp().                                              x = cos(2*pi).
                                                           • Round brackets ( ) — In Access, round brackets
14.3.5 The DLookUp() function                                have their usual meaning when grouping
The DLookUp() function is the “tool of last resort” in       together operations, e.g., 3*(5+1). Round
Access. Although you normally use queries and                brackets are also used to enclose the arguments
recordsets to provide you with the information you           of function calls, e.g., x = cos(2*pi).


                                                                  Home      Previous    12 o f 22     Next
14. Data Access Objects                                                                         Tutorial exercises


                     FIGURE 14.4: MyLookUp(): A function to find a value in a table.




                                                                The NoMatch() method returns True if the
                                                                FindFirst method finds no matching records,
                                                                and False otherwise.



                                                                Since strField contains the name of a valid
                                                                Field object (Title) in the Fields collection,
                                                                this notation returns the value of Title.




                                                                  Home      Previous     13 o f 22    Next


14. Data Access Objects                                                                         Tutorial exercises

 • Square brackets [ ] — Square brackets are not             x = COMM means that the variable x is equal to
   a universally defined programming construct like          the value of the variable COMM.
   round brackets. As such, square brackets have a         • Single quotation marks ‘ ’ — Single quotation
   particular meaning in Access/VBA and this                 marks have only one purpose: to replace normal
   meaning is specific to Microsoft products. Simply         quotation marks when two sets of quotation
   put, square brackets are used to signify the name         marks are nested. For example, the expression
   of a field, table, or other object in the DAO hierar-     x = “[ProductID] = ‘123’” means that the
   chy—they have no other meaning. Square brack-             variable x is equal to the string ProductID =
   ets are mandatory when the object names                   “123”. In other words, when the expression is
   contain spaces, but optional otherwise. For               evaluated, the single quotes are replaced with
   example, [Forms]![frmCourses]![Dept-                      double quotes. If you attempt to nest two sets of
   Code] is identical to Forms!frm-                          double quotation marks (e.g., x = “[Produc-
   Courses!DeptCode.                                         tID] = “123””) the meaning is ambiguous
 • Quotation marks “ ” — Double quotation marks              and Access returns an error.
   are used to distinguish literal strings from names      • The Ampersand  — The ampersand is the con-
   of variables, fields, etc. For example,                   catenation operator in Access/VBA and is unique
   x = “COMM” means that the variable x is equal             to Microsoft products. The concatenation opera-
   to the string of characters COMM. In contrast,            tor joins two strings of text together into one
                                                             string of text. For example,



                                                                  Home      Previous     14 o f 22    Next
14. Data Access Objects                                                                            Tutorial exercises

   x = “one”  “_two” means that the variable                • Create a calculated field called Title using the
   x is equal to the string one_two.                           following expression (see Figure 14.5):
If you understand these constructs at this point, then         Title: DLookUp(“Title”, “Courses”,
understanding the DLookUp() function is just a mat-             “DeptCode = ‘” [DeptCode]  “’ AND
ter of putting the pieces together one by one.                  CrsNum = ‘”  [CrsNum]  “’”)
                                                            14.3.5.2 Understanding the WHERE clause
14.3.5.1 Using DLookUp() in queries
                                                            The first two parameters of the DLookUp() are
The DLookUp() function is extremely useful for per-
                                                            straightforward: they give the name of the field and
forming lookups when no relationship exists between
                                                            the table containing the information of interest. How-
the tables of interest. In this section, you are going to
                                                            ever, the third argument (i.e., the WHERE clause) is
use the DLookUp() function to lookup the course
                                                            more complex and requires closer examination.
name associated with each section in the Sections
table. Although this can be done much easier using a        At its core, this WHERE clause is similar to the one
join query, this exercise illustrates the use of vari-      you created in Section 5.3.2 in that it contains two
ables in function calls.                                    criteria. However, there are two important differ-
  • Create a new query called qryLookUpTest                 ences:
    based on the Sections table.                            1. Since it is a DLookUp() parameter, the entire
  • Project the DeptCode, CrsNum, and Section                  clause must be enclosed within quotation marks.
    fields.                                                    This means single and double quotes-within-
                                                               quotes must be used.

                                                                     Home      Previous     15 o f 22    Next


14. Data Access Objects                                                                            Tutorial exercises


                             FIGURE 14.5: Create a query that uses DLookUp().


   table onlyquerynot includethe Sections
    Create a
               (do
                    based on
                                Courses).                        correct course title for function to get the
                                                                  Use the DLookUp()
                                                                                           each section.




                                                                     Home      Previous     16 o f 22    Next
14. Data Access Objects                                                                                      Discussion

2. It contains variable (as opposed to literal) criteria.       • Use strWhere in a DLookUp() call.
   For example, [DeptCode] is used instead of
   “COMM”. This makes the value returned by the                14.4 Discussion
   function call dependent on the current value of
   the DeptCode field.                                         14.4.1 VBA versus SQL
In order to get a better feel for syntax of the function       The PrintRecords procedure you created in
call, do the following exercises (see Figure 14.6):            Section 14.3.3 is interesting since it does essentially
Switch to the debug window and define two string               the same thing as a select query: it displays a set of
variables (see Section 12.3.1 for more information             records.
on using the debug window):                                    You could extend the functionality of the Print-
   strDeptCode = “COMM”                                        Records subroutine by adding an argument and an
   strCrsNum = “351”                                           IF-THEN condition. For example:
These two variables will take the place the field val-            Sub PrintRecords(strDeptCode as
ues while you are in the debug window.                              String)
 • Write the WHERE clause you require without the                 Do Until rsCourses.EOF
   variables first. This provides you with a template             If rsCourses!DeptCode = strDeptCode
                                                                    Then
   for inserting the variables.
 • Assign the WHERE clause to a string variable                   Debug.Print rsCourses!DeptCode  “ ”
                                                                     rsCourses!CrsNum
   called strWhere (this makes it easier to test).


                                                                        Home       Previous     17 o f 22    Next


14. Data Access Objects                                                                                      Discussion


                          FIGURE 14.6: Examine the syntax of the WHERE clause.


           values of DeptCode and CrsNum.valid
            Create string variables that refer to
                                                                          criteriathe WHERE clause using literal
                                                                           Write
                                                                                    first to get a sense of what is
                                                                               required.


                                                                              Use the variables in the WHERE
                                                                               clause and assign the expression to a
                                                                               string variable called strWhere.




                                                                          third parameter of the DLookUp()the
                                                                           To save typing, use strWhere as

                                                                               call.

         When replacing a literal string with a variable, you
         have to stop the quotation marks, insert the variable
         (with ampersands on either side) and restart the
         quotation marks. This procedure is evident when the
         literal and variable version are compared to each other.


                                                                        Home       Previous     18 o f 22    Next
14. Data Access Objects                                                                                   Discussion

   End If                                                SQL and QBE are declarative languages because
   rsCourses.MoveNext                                    you (as a programmer) need only tell the computer
   Loop                                                  what you want done, not how to do it. In contrast,
   rsCourses.Close                                       VBA is a procedural language since you must tell the
   End Sub                                               computer exactly how to extract the records of inter-
This subroutine takes a value for DeptCode as an         est.
argument and only prints the courses in that particu-    Although procedural languages are, in general, more
lar department. It is equivalent to the following SQL    flexible than their declarative counterparts, they rely
command:                                                 a great deal on knowledge of the underlying struc-
   SELECT DeptCode, CourseNum FROM                       ture of the data. As a result, procedural languages
    Courses WHERE DeptCode =                             tend to be inappropriate for end-user development
    strDeptCode                                          (hence the ubiquity of declarative languages such as
                                                         SQL in business environments).
14.4.2 Procedural versus Declarative
The difference between extracting records with a
query language and extracting records with a pro-
gramming language is that the former approach is
declarative while the latter is procedural.




                                                                   Home       Previous     19 o f 22      Next


14. Data Access Objects                                                              Application to the assignment

14.5 Application to the assignment                       As a result, it is possible to cheat a little bit and cre-
                                                         ate a stand-alone table (e.g., SystemVariables)
14.5.1 Using a separate table to store                   that contains a single record:
       system parameters                                       VariableName                       Value
When you calculated the tax for the order in                         GST                           0.07
Section 9.5, you “hard-coded” the tax rate into the
form. If the tax rate changes, you have to go through
                                                         Of course, other system-wide variables could be
all the forms that contain a tax calculation, find the
                                                         contained in this table, but one is enough for our pur-
hard-coded value, and change it. Obviously, a better
                                                         poses. The important thing about the SystemVari-
approach is to store the tax rate information in a
                                                         ables table is that it has absolutely no relationship
table and use the value from the table in all form-
                                                         with any other table. As such, you must use a
based calculations.
                                                         DLookUp() to access this information.
Strictly speaking, the tax rate for each product is a     • Create a table that contains information about the
property of the product and should be stored in the         tax rate.
Products table. However, in the wholesaling envi-         • Replace the hard-coded tax rate information in
ronment used for the assignment, the assumption is          your application with references to the value in
made that all products are taxed at the same rate.          the table (i.e., use a DLookUp() in your tax cal-
                                                            culations). Although the SystemVariables
                                                            table only contains one record at this point, you

                                                                   Home       Previous     20 o f 22      Next
14. Data Access Objects                                                             Application to the assignment

   should use an appropriate WHERE clause to              The reason you must use a DLookUp() to get this
   ensure that the value for GST is returned (if no       information is that there is no relationship between
   WHERE clause is provided, DLookUp() returns            the OrderDetails and BackOrders tables.
   the first value in the table).
                                                                 Any relationship that you manage to create
       The use of a table such as SystemVari-                    between OrderDetails and BackOrders
       ables contradicts the principles of relational            will be nonsensical and result in a non-updat-
       database design (we are creating an attribute             able recordset.
       without an entity). However, trade-offs
       between theoretical elegance and practicality       • In the query underlying your OrderDetails
       are common in any development project.                subform, create a calculated field called QtyOn-
                                                             BackOrder to determine the number of items on
14.5.2 Determining outstanding                               backorder for each item added to the order. This
       backorders                                            calculated field will use the DLookUp() function.
An good example in your assignment of a situation         There are two differences between this DLookUp()
requiring use of the DLookUp() is determining the         and the one you did in Section 14.3.5.1
backordered quantity of a particular item for a partic-   1. Both of the variables used in the function (e.g.,
ular customer. You need this quantity in order to cal-       CustID and ProductID) are not in the query.
culate the number of each item to ship.                      As such, you will have to use a join to bring the



                                                                   Home      Previous    21 o f 22    Next


14. Data Access Objects                                                             Application to the assignment

   missing information into the query.                       zero. To do this, use the iif() and IsNull()
2. ProductID is a text field and the criteria of text        functions, e.g.:
   fields must be enclosed in quotation marks, e.g.:         QtyOnBackOrderNoNull:
   ProductID = “123”                                           iif(IsNull([QtyOnBackOrder]),0,[Qty
   However, CustID is a numeric field and the crite-           OnBackOrder])
   ria for numeric fields is not enclosed in quotations    • Use this “clean” version in your calculations and
   marks, e.g.:                                              on your form.
   CustID = 4.
                                                                 It is possible to combine these two calculated
       Not every combination of CustID and Pro-                  fields into a one-step calculation, e.g.:
       ductID will have an outstanding backorder.                iif(IsNull(DLookUp(…)),0,
       When a matching records is not found, the                 DLookUp(…)).
       DLookUp() function returns a special value:               The problem with this approach is that the
       Null. The important thing to remember is                  DLookUp() function is called twice: once to
       that Null plus or minus anything equals                   test the conditional part of the immediate if
       Null. This has implications for your “quantity            statement and a second time to provide the
       to ship” calculation.                                     “false” part of the statement. If the Back-
                                                                 Orders table is very large, this can result in
 • Create a second calculated field in your query to             an unacceptable delay when displaying data
   convert any Nulls in the first calculated field to            in the form.


                                                                   Home      Previous    22 o f 22    Next
Access Tutorial 15: Advanced Triggers
15.1 Introduction: Pulling it all                                How do I create an unbound combo box?
     together                                                    Can I implement the search capability using
In this tutorial, you will bring together several of the          Visual Basic?
skills you have learned in previous tutorials to imple-
ment some sophisticated triggers.                          15.3 Tutorial exercises

15.2 Learning objectives                                   15.3.1 Using a macro to run VBA code
      How do I run VBA code using a macro?
                                                           There a some things that cannot be done using the
                                                           Access macro language. If the feature you wish to
      How do I use the value in one field to              implement is critical to your application, then you
       automatically suggest a value for a different       must implement it using VBA. However, since it is
       field?                                              possible to call a VBA function from within a macro,
      How do I change the table or query a form is        you do not have to abandon the macro language
       bound to once the form is already created?          completely.
      What is the After Update event? How is it           In this section, you are going to execute the Param-
       used?                                               eterTest subroutine you created in Section 12.3.6
      How do I provide a search capability for my
                                                           from within a macro. Since the RunCode action of
                                                           the Access macro language can only be used to exe-
       forms?

© Michael Brydon (brydon@unixg.ubc.ca)
Last update: 25-Aug-1997                                            Home      Previous    1 o f 33     Next


15. Advanced Triggers                                                                            Tutorial exercises

cute functions (not subroutines) you must do one of           'this function calls the
two things before you create the macro:                        ParameterTest subroutine
                                                              ParameterTest intStart, intStop
1. Convert ParameterTest to a function — you do
   this simply by changing the Sub at the start of the        ParameterTestWrapper = True
                                                               'return a value
   procedure to Function.
                                                              End Function
2. Create a new function that executes Parame-
                                                            • Call the function, as shown in Figure 15.1.
   terTest and call the function from the macro.
15.3.1.1 Creating a wrapper                                       Note that the return value of the function is
Since the second alternative is slightly more interest-           declared as an integer, but the actual assign-
                                                                  ment statement is ParameterTestWrap-
ing, it is the one we will use.
  • Open your basTesting module from                              per = True. This is because in Access/
                                                                  VBA, the constants True and False are
    Tutorial 12.
  • Create a new function called ParameterTest-                   defined as integers (-1 and 0 respectively).
    Wrapper defined as follows:
                                                           15.3.1.2 Using the RunCode action
   Function                                                 • Leave the module open (you may have to resize
    ParameterTestWrapper(intStart As
                                                              and/or move the debug window) and create a
    Integer, intStop As Integer) As
                                                              new macro called mcrRunCodeTest.
    Integer



                                                                    Home      Previous    2 o f 33     Next
15. Advanced Triggers                                                                            Tutorial exercises


              FIGURE 15.1: Create a function that calls the ParameterTest subroutine.




   the ParameterTest
    Create a function to call

       subroutine.


       Since ParameterTest                                                invoke the function (do notto
                                                                           Use the Print statement
                                                                                                       forget
       does not return a value, its                                           the parameters).
       arguments are not in
       brackets.
                                                                              The return value of
                                                                              ParameterTestWrapper()
                                                                              is True, so this is printed when
                                                                              the function ends.


                                                                  Home       Previous     3 o f 33         Next


15. Advanced Triggers                                                                            Tutorial exercises

 • Add the RunCode action and use the expression         • Select Run  Start to execute the macro as
   builder to select the correct function to execute,      shown in Figure 15.3.
   as shown in Figure 15.2.
                                                        15.3.2 Using activity information to
      The expression builder includes two parame-              determine the number of credits
      ter place holders (intStart and
                                                        In this section, you will create triggers attached to the
      intStop) in the function name. These
                                                        After Update event of bound controls.
      are to remind you that you must pass two
      parameters to the ParameterTestWrap-              15.3.2.1 Scenario
      per() function. If you leave the place holders    Assume that each type of course activity is generally
      where they are, the macro will fail because       associated with a specific number of credits, as
      Access has not idea what intStart             shown below:
      and intStop refer to.
                                                                 Activity                        Credits
 • Replace the parameter place holders with two                   lecture                            3.0
   numeric parameters (e.g. 3 and 6). Note that in                  lab                              3.0
   general, the parameters could be field names or
                                                                  tutorial                           1.0
   any other references to Access objects contain-
                                                                 seminar                             6.0
   ing (in this case) integers.



                                                                  Home       Previous     4 o f 33         Next
15. Advanced Triggers                                                                       Tutorial exercises


               FIGURE 15.2: Use the expression builder to select the function to execute.


   action to the macro.
    Add a RunCode




                                                                         Note the intStart and
                                                                         intStop parameter place
                                                                         holders. These must be replaced
                                                                         with expressions that Access
                                                                         understands.


   downthe expression builder to drill in
    Use
          to the user-defined functions
        your database file.


                                                              Home      Previous     5 o f 33     Next


15. Advanced Triggers                                                                       Tutorial exercises

                                                     Assume as well that the number of credits for a par-
  FIGURE 15.3: Execute the RunCode macro.
                                                     ticular type of course is not cast in stone. As such,
                                                     the numbers given above are merely “default” val-
                                                     ues.
                                                     You want to use the default credit values when you
                                                     create a new course or modify an existing course.
                                                     However, the user may override this default if neces-
                                                     sary for a particular course. The basic requirement is
                                                     illustrated in Figure 15.4.
                                                     15.3.2.2 Designing the trigger
                                                     Based on the foregoing, the answer to the “what”

   parameter place
    Replace the                                      question is the following:
                                                     1. Look up the default number of credits associated
        holders.
                                                        with the course activity showing in the form’s
                                                        Activity field.
   the toolRun toStart (or press the ! icon in
    Select
             bar) execute the macro.
                                                     2. Copy this number into the Courses.Credits
                                                        field.




                                                              Home      Previous     6 o f 33     Next
15. Advanced Triggers                                                                           Tutorial exercises


                          FIGURE 15.4: Inserting a default value into a new record.



         Create a new record for a lecture-based              of creditsmacro to find the default number
                                                                Create a
                                                                          and copy the value it into the
          course: COMM 437: Database Technology                    Credits field.


                                                                  Select “Lecture” from the list of list of
                                                                   course activities created in Tutorial 8.




          Since this is a new record, the default
          value of Credits (like any numeric
          field) is zero. You want to use the
          information you just specified in the                macrothe Activityvalue in the the
                                                                Once
                                                                      executes. The
                                                                                    field is updated,
          Activity field to automatically                          Credits field can be changed by the
          look up the correct default number of                    user.
          credits for a lecture course and insert
          it in the Credits field.


                                                                 Home      Previous      7 o f 33     Next


15. Advanced Triggers                                                                           Tutorial exercises

There are several possible answers to the “when”         • Ensure that you have a courses form (e.g., frm-
question (although some are better than others). For       Courses) and that the form has a combo box for
example:                                                   the Activity field. You may wish to order the
1. When the user enters the Credits field (the On          fields such that Activity precedes Credits in
   Enter event for Credits) — The problem with             the tab order (as shown in Figure 15.4).
   this choice is that the user could modify the
                                                              If your move fields around, remember to
   course’s activity without moving the focus to the
                                                              adjust the tab order accordingly (recall
   Activity field. In such a case, the trigger would
                                                              Section 8.3.4).
   not execute.
2. When the user changes the Activity field (the        15.3.2.4 Looking up the default value
   After Update event for Activity) — This choice
                                                        As you discovered in Section 14.3.5, Access has a
   guarantees that whenever the value of Activ-
                                                        DLookUp() function that allows you to go to the
   ity is changed, the default value will be copied
                                                        Activities table and find the value of Credits
   into the Credits field. As such, it is a better
                                                        for a particular value of Activity. A different
   choice.
                                                        approach is to join the Activities table with the
15.3.2.3 Preliminary activities                         Courses table in a query so that the default value of
 • Modify the Activities table to include a single-     credits is always available in the form. This is the
   precision numeric field called Credits. Add the      approach we will use here.
   values shown in the table in Section 15.3.2.1.


                                                                 Home      Previous      8 o f 33     Next
15. Advanced Triggers                                                                        Tutorial exercises

 • Ensure you have a relationship (in the main rela-
                                                             FIGURE 15.5: Use a join to make the default
   tionship window) between Courses.Activity
                                                                          value available.
   and Activities.Activity.
 • Create a new query called qryCoursesAnd-
   Credits based on the Courses and Activi-
   ties tables (see Figure 15.5).

       Notice that you have two credits fields:
       Courses.Credits (the actual number of
       credits for the course) and Activi-
       ties.Credits (the “default” or “suggested”
       number of credits based on the value of
       Activity). Access uses the table
       name.field name notation whenever a
       query contains more than one field with the
       same name.

Since you already have forms based on the
Courses table that expect a field called Credits
(rather than one called Courses.Credits), it is a


                                                                  Home     Previous   9 o f 33     Next


15. Advanced Triggers                                                                        Tutorial exercises

good idea to rename the Activities.Credits
                                                           FIGURE 15.6: Rename one of the Credits fields.
field in the query. You do this by creating a calculated
field.
  • Rename Activities.Credits to Default-
    Credits as shown in Figure 15.6. Note that this
    eliminates the need for the table
    name.field name notation.
15.3.2.5 Changing the Record Source of the
         form
Rather than create a new form based on the qry-
CoursesAndCredits query, you can modify the
Record Source property of the existing frmCourses
form so it is bound to the query rather than the
Courses table.
  • Bring up the property sheet for the frmCourses
    form and change the Record Source property to
    qryCoursesAndCredits as shown in
    Figure 15.7.
                                                              table to DefaultCredits.Activities
                                                               Rename Credits form the



                                                                  Home     Previous   10 o f 33    Next
15. Advanced Triggers                                                                             Tutorial exercises

                                                           The advantage of using a join query in this manner is
    FIGURE 15.7: Change the Record Source
                                                           that DefaultCredits is now available for use
         property of an existing form.
                                                           within the form and within any macros or VBA mod-

     changeup the form’sSource property.
      Bring
             its Record
                          property list and                ules that run when the form is open.
                                                           15.3.2.6 Creating the SetValue macro
                                                           The SetValue macro you require here is extremely
                                                           simple once you have DefaultCredits available
                                                           within the scope of the form.
                                                             • Create the mcrCourses.SetCredits macro
                                                               as shown in Figure 15.8.
                                                           15.3.2.7 Attaching a procedure to the After
                                                                    Update event
                                                           The On Click event of a button is fairly simple to
                                                           understand: the event occurs when the button is
                                                           clicked. The events associated with non-button
                                                           objects operate in exactly the same way. For exam-
                                                           ple, the After Update event for controls (text box,
                         The field list now contains all
                         the fields in the new query.      combo box, check box, etc.) occurs when the value


                                                                    Home      Previous     11 o f 33    Next


15. Advanced Triggers                                                                             Tutorial exercises

                                                            • Attach the mcrCourses.SetCredits macro to
   FIGURE 15.8: Create the SetValue macro.
                                                              the After Update event of the Activity field.
                                                            • Verify that the trigger works properly.
   and a named macro called SetCredits.
    Create a macro group called mcrCourses
                                                           15.3.3 Use an unbound combo box to
                                                                  automate search
                                                           As mentioned in Tutorial 8, a combo box has no
                                                           intrinsic search capability. However, the idea of scan-
                                                           ning a short list of key values, selecting a value, and
                                                           having all the information associated with that record
                                                           pop on to the screen is so basic that in Access ver-
                                                           sion 7.0 and above, this capability is included in the
                                                           combo box wizard. In this tutorial, we will look at a
   or simplyuse the builder to set the arguments
    You can
              type in the names of the fields.
                                                           couple of different means of creating a combo boxes
                                                           for search from scratch.
of the control is changed by the user. As a result, the    15.3.3.1 Manual search in Access
After Update event is often used to trigger data verifi-   To see how Access searches for records, do the fol-
cation procedures and “auto-fill” procedures like the      lowing:
one you are creating here.                                   • Open your frmDepartments form.

                                                                    Home      Previous     12 o f 33    Next
15. Advanced Triggers                                                                         Tutorial exercises

 • Move to the field on which you want to search         • Set the Enabled property of DeptCode to No (the
   (e.g., DeptCode);                                       user should never be able to change the key val-
 • Select Edit  Find (or press Control-F);                ues of existing records).
 • Fill out the search dialog box as shown in
                                                        15.3.3.3 Creating the unbound combo box
   Figure 15.9.
                                                        The key thing to remember about the combo box
In the dialog box, you specify what to search for       used to specify the search criterion is that it has
(usually a key value) and specify how Access should
                                                        nothing to do with the other fields or the underlying
conduct its search. When you press Find First,          table. As such, it should be unbound.
Access finds the first record that matches your
                                                          • Create an unbound combo box in the form
search value and makes it the current record (note
                                                            header, as shown in Figure 15.10.
that if you are searching on a key field, the first       • Change the Name property of the combo box to
matching record is also the only matching record).
                                                            cboDeptCode.
15.3.3.2 Preliminaries                                    • The resulting combo box should resemble that
To make this more interesting, assume that the frm-         shown in Figure 15.11.
Departments form is for viewing editing existing
                                                               When you create an unbound combo box,
departmental information (rather than adding new
                                                               Access gives it a default name (e.g.,
departments). To enforce this limitation, do the fol-
                                                               Combo5). You should do is change this to
lowing:
                                                               something more descriptive (e.g., cboDept-
  • Set the form’s Allow Additions property to No.

                                                                 Home      Previous    13 o f 33    Next


15. Advanced Triggers                                                                         Tutorial exercises


                      FIGURE 15.9: Search for a record using the “find” dialog box.



   the field you wishtoto
    Move the cursor
        search and invoke
        the search box
        using Control-F.


   and setthe value you wish to find
    Enter
             the other search
        parameters as required.


       Limit the search to the current
        field (i.e., the field with the
        focus when the search box was
        opened).


   (or only) record that matches the
    Press Find First to move to the first

        search condition.


                                                                 Home      Previous    14 o f 33    Next
15. Advanced Triggers                                                                           Tutorial exercises


                                FIGURE 15.10: Create an unbound combo box.

   down themake roomfor the detail
    Drag
          to
             separator
                       in the form
        header


   selecting the combocombo boxand
    Create an unbound
                        box tool
                                 by

        clicking in the header area.


       Use the wizard in the usual way
        to get a list of valid DeptCode
        values and descriptions. The
        bound column for the combo box
        should be DeptCode.



   its value has to bebox is unbound,
    Since the combo
                        stored for later
        use rather than stored in a field.




                                                                   Home     Previous     15 o f 33    Next


15. Advanced Triggers                                                                           Tutorial exercises

                                                          15.3.3.4 Automating the search procedure
    FIGURE 15.11: An unbound combo box.
                                                                   using a macro
                                                          When we implement search functionality with a
                                                          combo box, only two things are different from the
                                                          manual search in Figure 15.9:
                                                          1. the search dialog box does not show up, and
                                                          2. the user selects the search value from the combo
                                                             box rather than typing it in.
                                                          The basic sequence of actions, however, remains
         Although the DeptCode column has been            the same. As a result, the answer to the “what” ques-
         hidden, it is the “bound” column. As a result,
         the value of the combo box as it appears here    tion is the following:
         is “COMM”, not “Commerce and ...”                1. Move the cursor to the DeptCode field (this
                                                             allows the “Search Only Current Field” option to
      Code). The advantage of the prefix cbo is              be used, thereby drastically cutting the search
      that it allows you to differentiate between the        time).
      bound field DeptCode and the unbound                2. Invoke the search feature using the current value
      combo box.                                             of cboDeptCode as the search value.




                                                                   Home     Previous     16 o f 33    Next
15. Advanced Triggers                                                                     Tutorial exercises

3. Move the cursor back to cboDeptCode or some
                                                        FIGURE 15.13: Fill in the arguments for the
   other field.
                                                                  FindRecord action.
The only problem with this procedure is that the
DeptCode text box is disabled. As a result, you must
include an extra step at the beginning of the macro
                                                               mcrSearch.FindDepartment.
                                                                Create a named macro called

to set its Enabled property to Yes and another at the
end of the macro to return it to its original state.
  • Create a new macro called mcrSearch.Find-
    Department.
  • Use the SetValue action to set the Dept-
    Code.Enabled property to Yes. This can be
    done using the expression builder, as shown in
    Figure 15.12.
  • Use the GotoControl action to move the cursor                                       Since Value is
                                                                                        the default
    to the DeptCode text box. Note that this action                                     property, its use
    will fail if the destination control is disabled.                                   is optional.
  • Use the FindRecord action to implement the
    search as shown in Figure 15.13.
                                                         equalsthe action arguments. Dothe combo box.
                                                          Enter
                                                                 sign before the name of
                                                                                         not forget the



                                                              Home     Previous    17 o f 33    Next


15. Advanced Triggers                                                                     Tutorial exercises


               FIGURE 15.12: Use the builder to specify the name of the property to set.



   expressionItem argument, down
    To set the
               builder to drill
                                use the
        to the correct form.


        The middle pane shows all the
        objects on the form including
        labels and buttons (hence the
        need for a good naming
        convention).


   (cboDeptCode) from thebox
    Select the unbound combo
                             middle
        pane. A list of properties for the
        selected object is displayed in the
        pane on the right.




                                                              Home     Previous    18 o f 33    Next
15. Advanced Triggers                                                                           Tutorial exercises

      Access interprets any text in the Find What        15.3.4 Using Visual Basic code instead of
      argument as a literal string (i.e., quotation             a macro
      marks would not be required to find COMM). To      Instead of attaching a macro to the After Update
      use an expression (including the contents of a
                                                         event, you can attach a VBA procedure. The VBA
      control) in the Find What argument, you must       procedure is much shorter than its macro counter-
      precede it with an equals sign (e.g.,
                                                         part:
      =[cboDeptCode].
                                                         1. a copy (clone) of the recordset underlying the
 • You cannot disable a control if it has the focus.        form is created,
   Therefore, include another GotoControl action         2. the FindFirst method of this recordset is used
   to move the cursor to cboDeptCode before set-            to find the record of interest.
   ting DeptCode.Enabled = No.                           3. the “bookmark” property of the clone is used to
 • Attach the macro mcrSearch.FindDepart-                   move to the corresponding bookmark for the
   ment to the After Update event of the cboDept-           form.
   Code combo box.                                       To create a VBA search procedure, do the following:
 • Test the search feature.                               • Change the After Update event of cboDeptCode
                                                            to “Event Procedure”.
                                                          • Press the builder ( ) to create a VBA subrou-
                                                            tine.



                                                                  Home      Previous     19 o f 33    Next


15. Advanced Triggers                                                              Application to the assignment

 • Enter the two lines of code below, as shown in           a non-human-readable data type and therefore is
   Figure 15.14.                                            not of much use unless it is used in the manner
   Me.RecordsetClone.FindFirst                              shown here. Setting the Bookmark property of a
     “DeptCode = ‘”  cboDeptCode  “'”                     record makes the record with that bookmark the
   Me.Bookmark =                                            current record. In the example above, the book-
     Me.RecordsetClone.Bookmark                             mark of the records underlying the form is set to
This program consists of a number of interesting ele-       equal the bookmark of the clone. Since the clone
ments:                                                      had its bookmark set by the search procedure,
 • The property Me refers to the current form. You          this is equivalent to searching the recordset
   can use the form's actual name, but Me is much           underlying the form.
   faster to type.
 • A form’s RecordsetClone property provides a           15.4 Application to the assignment
   means of referencing a copy of the form's under-
   lying recordset.                                      15.4.1 Triggers to help the user
 • The FindFirst method is straightforward. It            • Create a trigger on your order form that sets the
   acts, in this case, on the clone.                        actual selling price of a product to its default
 • Every recordset has a bookmark property that             price. This allows the user to accept the default
   uniquely identifies each record. A bookmark is           price or enter a new price for that particular trans-
   like a “record number”, except that it is stored as      action (e.g., the item could be damaged). You will


                                                                  Home      Previous     20 o f 33    Next
15. Advanced Triggers                                                              Application to the assignment


              FIGURE 15.14: Implement the search feature using a short VBA procedure.



                                                          referencethe After Update event to
                                                           Change
                                                                      an event procedure.


                                                          editor.the builder button to invoke the VBA
                                                           Press



                                                             Access automatically names the
                                                              subroutine. Enter the two lines of code.




                                                                 Home      Previous      21 o f 33       Next


15. Advanced Triggers                                                              Application to the assignment

   have to think carefully about which event to         Section 10.4). The problem is updating the Back-
   attach this macro to.                                Orders table itself because two different situations
 • Create a trigger on your order form that calcu-      have to be considered:
   lates a suggested quantity to ship and copies this   1. A record for the particular customer-product
   value into the quantity to ship field. The sug-         combination exists in the BackOrders table --
   gested value must take into account the amount          If a backorder record exists for a particular cus-
   ordered by the customer, any outstanding backo-         tomer and a particular product, the quantity field
   rders for that item by that customer, and the cur-      of the record can be added-to or subtracted-from
   rent quantity on hand (you cannot ship what you         as backorders are created and filled.
   do not have). The user should be able to override    2. A customer-product record does not exist in
   this suggested value. (Hint: use the MinValue()         the BackOrders table -- If the particular cus-
   function you created in Section 12.5.)                  tomer has never had a backorder for the product
 • Provide you customer and products forms with            in question, then there is no record in the Back-
   search capability.                                      Orders table to update. If you attempt to update
                                                           a nonexistent record, you will get an error.
15.4.2 Updating the BackOrders table
                                                        What is required, therefore, is a means of determin-
Once a sales order is entered into the order form, it   ing whether a record already exists for a particular
is a simple matter to calculate the amount of each      customer-product combination. If a record does
product that should be backordered (you did this in     exist, then it has to be updated; if a record does not


                                                                 Home      Previous      22 o f 33       Next
15. Advanced Triggers                                                                  Application to the assignment

exist, then one has to be created. This is simple                  (see Section 15.3.2.4 to review renaming
enough to talk about, but more difficult to implement              fields in queries).
in VBA. As a result, you are being provided with a
shortcut function called UpdateBackOrders()                  Note that if the backordered quantity is positive,
that implements this logic.                                  items are backordered. If the backordered quantity is
                                                             negative, backorders are being filled. If the backor-
The requirements for using the UpdateBackO-
                                                             dered quantity is zero, no change is required and
rders() function are outlined in the following sec-
                                                             these records should no be included in the results of
tions:
                                                             the query.
15.4.2.1 Create the pqryItemsToBackOrder
                                                             15.4.2.2 Import the shortcut function
         query
                                                             Import the Visual Basic for Applications (VBA) mod-
If you have not already done so, create the pqry-
                                                             ule containing the code for the
ItemsToBackOrder query described in
                                                             UpdateBackOrders() function. This module is
Section 10.4. The UpdateBackOrders() proce-
                                                             contained in an Access database called
dure sets the parameter for the query and then cre-
                                                             BOSC_Vx.mdb that you can download from the
ates a recordset based on the results.
                                                             course home page.
       If you did not use the field names OrderID,             • BOSC_V2.mdb is for those running Access ver-
       and ProductID in your tables, you must use                sion 2.0. To import the module, select File 
       the calculated field syntax to rename them


                                                                      Home      Previous    23 o f 33   Next


15. Advanced Triggers                                                                  Application to the assignment

   Import, choose BOSC_V2.mdb, and select Mod-               ers, and Products. If any of your tables or fields
   ule as the object type to import.                         are named differently, an error occurs. To eliminate
 • BOSC_V7.mdb is for those running Access ver-              these errors, you can do one of two of things:
   sion 7.0 or higher. To import the module, select          1. Edit the VBA code. Use the search-and-replace
   File  Get External Data  Import, choose                    feature of the module editor to replace all
   BOSC_V7.mdb, and select Module as the object                 instances of field names in the supplied proce-
   type to import.                                              dures with your own field names. This is the rec-
15.4.2.3 Use the function in your application                   ommended approach, although you need an
                                                                adequate understanding of how the code works
The general syntax of the function call is:
UpdateBackOrders(OrderID, CustomerID).                          in order to know which names to change.
                                                             2. Change the field names in your tables (and all
The OrderID and CustomerID are arguments and
                                                                queries and forms that reference these field
they both must be of the type Long Integer. If this             names). This approach is not recommended.
function is called properly, it will update all the backo-
rdered items returned by the parameter query.                15.4.3 Understanding the
15.4.2.4 Modifying the UpdateBackOrders()                           UpdateBackOrders() function
         function                                            The flowchart for the UpdateBackOrders() func-
The UpdateBackOrders() function looks for spe-               tion is shown in Figure 15.15. This function repeat-
cific fields in three tables: BackOrders, Custom-            edly calls a subroutine, BackOrderItem, which


                                                                      Home      Previous    24 o f 33   Next
15. Advanced Triggers                                                                 Application to the assignment

updates or adds the individual items to the BackO-              FIGURE 15.15: Flowchart for
rders table. The flowchart for the BackOrderItem                  UpdateBackOrders().
subroutine is shown in Figure 15.16.
There are easier and more efficient ways of imple-                         start

menting routines to update the BackOrders table.
Although some amount of VBA code is virtually inev-          run pqryItemsToBackOrder
                                                              to get list of items to backorder
itable, a great deal of programming can be elimi-
nated by using parameter queries and action
queries. Since queries run faster than code in                             is     yes
                                                                         the list
Access, the more code you replace with queries, the                      empty?
                                                                                      error message         stop
better.
                                                                                 no
      To get full marks for the backorders aspect of
      the assignment, you have to create a more                     do until end of list
      elegant alternative to the shortcut supplied
      here.                                                     call BackOrderItems
                                                             (CustID,ProductID,Qty)


                                                                           stop



                                                              Home        Previous         25 o f 33    Next


15. Advanced Triggers                                                                 Application to the assignment


                        FIGURE 15.16: Flowchart for the BackOrderItem subroutine.


               start


    search BackOrders table for
   matching CustID  ProductID
                                                                              yes

                       yes                                    check Products table to
                                                              ensure valid ProductID
              found?          update Qty     stop

                   no                                                              no
      check Customer table to                                            valid?         error message      stop
        ensure valid CustID
                                                                              yes

                        no                                      add new record with
                                                             CustID, ProductID  Qty
              valid?         error message   stop


                                                                          stop



                                                              Home        Previous         26 o f 33    Next
15. Advanced Triggers                                                              Application to the assignment

15.4.4 Annotated source code for the                     MsgBox “Back order cannot be processed:
       backorders shortcut module.                        order contains no items”
                                                         Exit Sub
In the following sections, the two procedures in the
                                                         End If
shortcut module are examined. In each case, the
                                                         Do Until rsBOItems.EOF
code for the procedure is presented followed by
                                                         Call BackOrderItem(lngCustID,
comments on specific lines of code.
                                                          rsBOItems!ProductID, rsBOItems!Qty)
15.4.4.1 The UpdateBackOrders() function                 rsBOItems.MoveNext
Function UpdateBackOrders(ByVal                          Loop
 lngOrdID As Long, ByVal lngCustID As                    rsBOItems.Close
 Long)                                                   End Function
Set dbCurr = CurrentDb
                                                         15.4.4.2 Explanation of the
Dim rsBOItems As Recordset                                        UpdateBackOrders() function
dbCurr.QueryDefs!pqryItemsToBackOrder.
 Parameters!pOrderID = lngOrdID                          Function UpdateBackOrders(ByVal lngOr-
Set rsBOItems =                                          dID As Long, ByVal lngCustID As Long) —
 dbCurr.QueryDefs!pqryItemsToBackOrder                   This statement declares the function and its parame-
 .OpenRecordset()                                        ters. Each item in the parameter list contains three
If rsBOItems.RecordCount = 0 Then                        elements: ByVal or ByRef (optional), the variable's
                                                         name, and the variable's type (optional). The ByVal


                                                                  Home      Previous    27 o f 33   Next


15. Advanced Triggers                                                              Application to the assignment

keyword simply means that a copy of the variables        Dim rsBOItems As Recordset — In this decla-
value is passed the subroutine, not the variable         ration statement, a pointer to a Recordset object is
itself. As a result, variables passed by value cannot    declared. This recordset contains a list of all the
be changed by the sub-procedure. In contrast, if a       items to add to the BackOrders table.
variable is passed by reference (the default), its       dbCurr.QueryDefs!pqryItemsToBackOrder
value can be changed by the sub-procedure.               .Parameters!pOrderID = lngOrdID — This
Set dbCurr = CurrentDb — Declaring a vari-               one is a bit tricky: the current database (dbCurr)
able and setting it to be equal to something are dis-    contains a collection of objects called QueryDefs
tinct activities. In this case, the variable dbCurr      (these are what you create when you use the QBE
(which is declared in the declarations section) is set   query designer). Within the collection of QueryDefs,
to point to a database object. Note that the database    there is one called pqryItemsToBackOrder
object is not created, it already exists.                (which you created in Section 15.4.2.1).
CurrentDb is a function supported in Access ver-         Within every QueryDef, there is a collection of zero
sion 7.0 and higher that returns a reference to the      or more Parameters. In this case, there is one called
current database. In Access version 2.0, this function   pOrderID and this sets the value of the parameter
does not exist and thus the current database must        to the value of the variable lngOrderID (which was
be found by starting at the top level object in the      passed to the function as a parameter).
Access DAO hierarchy, as discussed in                    Set rsBOItems = dbCurr.QueryDefs!pqry-
Section 14.3.1.                                          ItemsToBackOrder.OpenRecordset() — Here


                                                                  Home      Previous    28 o f 33   Next
15. Advanced Triggers                                                                 Application to the assignment

is another set statement. In this one, the variable        MsgBox “Back order cannot be processed:
rsBOItems is set to point at a recordset object.           order contains no items” — The MsgBox
Unlike the current database object above, however,         statement pops up a standard message box with an
this recordset does not yet exist and must be created      Okay button in the middle.
by running the pqryItemsToBackOrder parame-                Exit Sub — If this line is reached, the list contains
ter query.                                                 no items. As such, there is no need to go any further
OpenRecordset is a method that is defined for              in this subroutine.
objects of type TableDef or QueryDef that creates an       End If — The syntax for If… Then… Else… state-
image of the data in the table or query. Since the         ments requires an End If statement at the end of
query in question is a parameter query, and since the      the conditional code. That is, everything between the
parameter query is set in the previous statement, the      If and the End If executes if the condition is true;
resulting recordset consists of a list of backordered      otherwise, the whole block of code is ignored.
items with an order number equal to the value of
                                                           Do Until rsBOItems.EOF — The EOF property
pOrderID.
                                                           of a recordset is set to true when the “end of file” is
If rsBOItems.RecordCount = 0 Then — The                    encountered.
only thing you need to know at this point about the
                                                           Call BackOrderItem(lngCustID, rsBOI-
RecordCount property of a recordset is that it returns
                                                           tems!ProductID, rsBOItems!Qty) — A sub-
zero if the recordset is empty.
                                                           routine is used to increase the modularity and



                                                                    Home       Previous     29 o f 33   Next


15. Advanced Triggers                                                                 Application to the assignment

readability of this function. Note the way in which the    15.4.4.3 The BackOrderItem() subroutine
current values of ProductID and Qty from the               Sub BackOrderItem(ByVal lngCustID As
rsBOItems Recordset are accessed.                           Long, ByVal strProdID As String, ByVal
rsBOItems.MoveNext — MoveNext is a method                   intQty As Integer)
                                                           Set dbCurr = CurrentDb
defined for recordset objects. If this is forgotten, the
EOF condition will never be reached and an infinite        Dim strSearch As String
                                                           Dim rsBackOrders As Recordset
loop will be created. In VBA, the Escape key is usu-
                                                           Set rsBackOrders =
ally sufficient to stop an infinite loop.
                                                            dbCurr.OpenRecordset(“BackOrders”,
Loop — All Do While/Do Until loops must end                 dbOpenDynaset)
with the Loop statement.                                   strSearch = “CustID = “  lngCustID  “
rsBOItems.Close — When you create a new                     AND ProductID = '  strProdID  “'”
object (such as a Recordset using the Open-                rsBackOrders.FindFirst strSearch
Recordset method), you should close it before exit-        If rsBackOrders.NoMatch Then
ing the procedure. Note that you do not close              Dim rsCustomers As Recordset
dbCurr because you did not open it.                        Set rsCustomers =
                                                            dbCurr.OpenRecordset(“Customers”,
End Function — All functions/subroutines need               dbOpenDynaset)
an End Function/End Sub statement.                         strSearch = “CustID = “  lngCustID
                                                           rsCustomers.FindFirst strSearch


                                                                    Home       Previous     30 o f 33   Next
15. Advanced Triggers                                                              Application to the assignment

If rsCustomers.NoMatch Then                             rsBackOrders!Qty = intQty
MsgBox “An invalid Customer ID number                   rsBackOrders.Update
 has been passed to BackOrderItem”                      Else
Exit Sub                                                rsBackOrders.Edit
End If                                                  rsBackOrders!Qty = rsBackOrders!Qty +
Dim rsProducts As Recordset                              intQty
Set rsProducts =                                        rsBackOrders.Update
 dbCurr.OpenRecordset(“Products”,                       End If
 dbOpenDynaset)                                         End Sub
strSearch = “ProductID = '  strProdID
  “'”                                                  15.4.4.4 Explanation of the BackOrderItem()
rsProducts.FindFirst strSearch                                   subroutine
If rsProducts.NoMatch Then                              Since many aspects of the language are covered in
MsgBox “An invalid Product ID number                    the previous subroutine, only those that are unique
 has been passed to BackOrderItem”                      to this subroutine are explained.
Exit Sub                                                Set rsBackOrders = dbCurr.OpenRecord-
End If                                                  set(“BackOrders”, dbOpenDynaset) — The
rsBackOrders.AddNew                                     OpenRecordset method used here is the one
rsBackOrders!CustID = lngCustID                         defined for a Database object. The most important
rsBackOrders!ProductID = strProdID                      argument is the source of the records, which can be


                                                                 Home       Previous     31 o f 33   Next


15. Advanced Triggers                                                              Application to the assignment

a table name, a query name, or an SQL statement.        do this, single quotes are used within the search
The dbOpenDynaset argument is a predefined con-         string.
stant that tells Access to open the recordset as a      rsBackOrders.FindFirst strSearch —
dynaset. You don't need to know much about this         FindFirst is a method defined for Recordset
except that the format of these predefined constants    objects that finds the first record that meets the crite-
is different between Access version 2.0 and version     ria specified in the method's argument. Its argument
7.0 and higher. In version 2.0, constants are of the    is the text string stored in strSearch.
form: DB_OPEN_DYNASET.
                                                        If rsBackOrders.NoMatch Then — The
strSearch = “CustID = ” lngCustID  “                  NoMatch property should always be checked after
AND ProductID = ’”  strProdID  “'” —                  searching a record set. Since it is a Boolean variable
A string variable has been used to break the search     (True / False) it can be used without an comparison
process into two steps. First, the search string is     operator.
constructed; then the string is used as the parameter
                                                        rsBackOrders.AddNew — Before information can
for the FindFirst method. The only tricky part here
                                                        be added to a table, a new blank record must be cre-
is that lngCustID is a long integer and strProdID
                                                        ated. The AddNew method creates a new empty
is a string. The difference is that the value of str-
                                                        record, makes it the active record, and enables it for
ProdID has to be enclosed in quotation marks when
                                                        editing.
the parameter is passed to the FindFirst method. To




                                                                 Home       Previous     32 o f 33   Next
15. Advanced Triggers                                                Application to the assignment

rsBackOrders!CustID = lngCustID — Note
the syntax for changing a variable’s value. In this
case, the null value of the new empty record is
replaced with the value of a variable passed to the
subroutine.
rsBackOrders.Update — After any changes are
made to a record, the Update method must be
invoked to “commit” the changes. The AddNew /
Edit and Update methods are like bookends
around changes made to records.
rsBackOrders.Edit — The Edit method allows
the values in a record to be changed. Note that these
changes are not saved to the underlying table until
the Update method is used.




                                                        Home   Previous   33 o f 33   Next

More Related Content

DOC
msword
PDF
Database management systems_-_pallaw,_vijay_krishna(author)
DOC
Silibus tij3043 (2012) students
PDF
Access 2003 tutorial 2
DOC
Microsoft access exercises
PDF
05 2007 excel 2007
DOC
msword
PDF
812395816
msword
Database management systems_-_pallaw,_vijay_krishna(author)
Silibus tij3043 (2012) students
Access 2003 tutorial 2
Microsoft access exercises
05 2007 excel 2007
msword
812395816

Similar to Ms access tutorials (20)

PDF
(eTextbook PDF) for Starting out with Visual C# 5th Edition
PDF
FYP%3A+P2P+Bluetooth+Communication+Framework+on+Android%0A
PDF
Database Management Systems 3rd Edition Raghu Ramakrishnan
PDF
65487681 60444264-engineering-optimization-theory-and-practice-4th-edition
PDF
Objects First With Java A Practical Introduction Using Bluej 1st Edition Davi...
PDF
JavaScript The Definitive Guide 7th Edition David Flanagan
PDF
(eBook PDF) Introduction to Geographic Information Systems, 9th Edition
PDF
MySQL Cookbook 1st ed Edition Paul Dubois
PDF
Mcts self paced training kit exam 432 sql server 2008 - implementation and ...
PDF
MySQL Cookbook 1st ed Edition Paul Dubois
PDF
Data structures and algorithm analysis in java
PDF
Oracle Business Intelligence Publisher for Primavera Contract Management Trai...
PDF
Communications Level 5 Learner's Record
PDF
A Practical Introduction To Data Structures And Algorithms Analysis, Java Edi...
PDF
ICT 1 - syllabus.pdf
PDF
MySQL Cookbook 1st ed Edition Paul Dubois
PDF
Syllibus web application
PDF
Programming in c++
DOCX
ML Project(by-Ethem-Alpaydin)-Introduction-to-Machine-Learni-24.docx
PDF
Semantic Web Services for Computational Mechanics : A Literature Survey and R...
(eTextbook PDF) for Starting out with Visual C# 5th Edition
FYP%3A+P2P+Bluetooth+Communication+Framework+on+Android%0A
Database Management Systems 3rd Edition Raghu Ramakrishnan
65487681 60444264-engineering-optimization-theory-and-practice-4th-edition
Objects First With Java A Practical Introduction Using Bluej 1st Edition Davi...
JavaScript The Definitive Guide 7th Edition David Flanagan
(eBook PDF) Introduction to Geographic Information Systems, 9th Edition
MySQL Cookbook 1st ed Edition Paul Dubois
Mcts self paced training kit exam 432 sql server 2008 - implementation and ...
MySQL Cookbook 1st ed Edition Paul Dubois
Data structures and algorithm analysis in java
Oracle Business Intelligence Publisher for Primavera Contract Management Trai...
Communications Level 5 Learner's Record
A Practical Introduction To Data Structures And Algorithms Analysis, Java Edi...
ICT 1 - syllabus.pdf
MySQL Cookbook 1st ed Edition Paul Dubois
Syllibus web application
Programming in c++
ML Project(by-Ethem-Alpaydin)-Introduction-to-Machine-Learni-24.docx
Semantic Web Services for Computational Mechanics : A Literature Survey and R...
Ad

Ms access tutorials

  • 1. Microsoft Access Tutorials: Table of Contents 1. Introduction to Microsoft Access 2. Tables 1.1 Introduction: What is Access? 1 2.1 Introduction: The importance of good table 1.1.1 The many faces of Access 1 design 1 1.1.2 What is in an Access database file? 3 2.2 Learning objectives 1 1.2 Learning objectives 3 2.3 Tutorial exercises 1 1.3 Tutorial exercises 4 2.3.1 Datasheet basics 2 1.3.1 Starting Access 4 2.3.2 Creating a new table 2 1.3.2 Creating a new database 4 2.3.3 Specifying the primary key 7 1.3.3 Opening an existing database 6 2.3.4 Setting field properties 7 1.3.4 Importing data from other applications 6 2.3.5 Using the input mask wizard 9 1.3.5 Getting help 9 2.4 Discussion 9 1.3.6 Compacting your database 9 2.4.1 Key terminology 9 1.4 Discussion 14 2.4.2 Fields and field properties 13 1.4.1 The database file in Access 14 2.4.2.1 Field names 13 1.4.2 Compacting a database 14 2.4.2.2 Data types 13 1.4.3 Renaming a database 14 2.4.2.3 “Disappearing” numbers in autonumber 1.4.4 Developing applications in Access 15 fields 14 1.4.5 Use of linked tables 16 2.4.2.4 Input masks 15 1.5 Application to the assignment 16 2.4.2.5 Input masks and literal values 16 © Michael Brydon (brydon@unixg.ubc.ca) Last update: 25-Aug-1997 Home Previous 1 of 8 Next 2.5 Application to the assignment 17 4.3.1 Creating a query 2 4.3.2 Five basic query operations 2 3. Relationships 4.3.2.1 Projection 2 3.1 Introduction: The advantage of using tables 4.3.2.2 Sorting 7 and relationships 1 4.3.2.3 Selection 7 3.1.1 “Normalized” table design 3 4.3.2.4 Complex selection criteria 7 3.2 Learning objectives 4 4.3.2.5 Joining 11 3.3 Tutorial exercises 4 4.3.3 Creating calculated fields 15 3.3.1 Creating relationships between tables 4 4.3.3.1 Refining the calculated field 18 3.3.2 Editing and deleting relationships 7 4.3.3.2 A more complex calculated field 18 3.4 Discussion 7 4.3.4 Errors in queries 20 3.4.1 One-to-many relationships 7 4.4 Discussion 20 3.4.2 Referential integrity 9 4.4.1 Naming conventions for database 3.5 Application to the assignment 10 objects 20 4.4.2 The ampersand (&) operator 21 4. Basic Queries Using QBE 4.4.3 Using queries to populate tables on the 4.1 Introduction: Using queries to get the “many” side of a relationship 22 information you need 1 4.4.4 Non-updatable recordsets 23 4.2 Learning objectives 1 4.5 Application to the assignment 27 4.3 Tutorial exercises 2 Home Previous 2 of 8 Next
  • 2. 5. Basic Queries using SQL 6.3.1.4 Binding an unbound text box to a field 9 5.1 Introduction: The difference between QBE 6.3.2 Creating a single-column form using the and SQL 1 wizard 11 5.2 Learning objectives 1 6.4 Discussion 14 5.3 Tutorial exercises 1 6.4.1 Columnar versus tabular versus 5.3.1 Basic SQL queries 2 datasheet forms 14 5.3.2 Complex WHERE clauses 4 6.5 Application to the assignment 14 5.3.3 Join queries 4 5.4 Discussion 5 7. Subforms 7.1 Introduction: The advantages of forms 6. Form Fundamentals within forms 1 6.1 Introduction: Using forms as the core of an 7.2 Learning objectives 1 application 1 7.3 Tutorial exercises 1 6.2 Learning objectives 1 7.3.1 Creating the main form 3 6.3 Tutorial exercises 2 7.3.2 Creating the subform 3 6.3.1 Creating a form from scratch 2 7.3.3 Linking the main form and subform 3 6.3.1.1 Adding bound text boxes 2 7.3.4 Linking forms and subforms manually 9 6.3.1.2 Using a field’s properties to protect its 7.3.5 Non-synchronized forms 13 contents 6 7.3.6 Aesthetic refinements 13 6.3.1.3 Adding an unbound text box 6 7.3.6.1 Changing the form’s caption 13 Home Previous 3 of 8 Next 7.3.6.2 Eliminating unwanted scroll bars and 8.4.1 Why you should never use a combo box navigation buttons 13 for a non-concatenated key. 19 7.4 Application to the assignment 16 8.4.2 Controls and widgets 21 8.5 Application to the assignment 22 8. Combo Box Controls 8.1 Introduction: What is a combo box? 1 9. Advanced Forms 8.2 Learning objectives 2 9.1 Introduction: Using calculated controls on 8.3 Tutorial exercises 2 forms 1 8.3.1 Creating a bound combo box 2 9.2 Learning objectives 1 8.3.2 Filling in the combo box properties 5 9.3 Tutorial exercises 1 8.3.3 A combo box based on another table or 9.3.1 Creating calculated controls on forms 1 query 6 9.3.2 Showing a total on the main form 2 8.3.3.1 Showing more than one field in the 9.3.2.1 Calculating the aggregate function on combo box 9 the subform 5 8.3.3.2 Hiding the key field 12 9.3.2.2 Hiding the text box on the subform 9 8.3.3.3 Changing the order of items in the 9.4 Discussion 9 combo box 14 9.5 Application to the assignment 11 8.3.4 Changing a form’s tab order 18 8.4 Discussion 19 Home Previous 4 of 8 Next
  • 3. 10. Parameter Queries 11.3.2 Using an update query to rollback 10.1 Introduction: Dynamic queries using changes 3 parameters 1 11.3.3 Using an update query to make 10.2 Learning objectives 1 selective changes 8 10.3 Tutorial exercises 2 11.3.4 Rolling back the changes 9 10.3.1 Simple parameter queries 2 11.3.5 Attaching action queries to buttons 9 10.3.2 Using parameters to generate prompts 11.4 Application to the assignment 11 4 11.4.1 Rolling back your master tables 11 10.3.3 Values on forms as parameters 4 11.4.2 Processing transactions 16 10.4 Application to the assignment 7 12. An Introduction to Visual Basic 11. Action Queries 12.1 Introduction: Learning the basics of 11.1 Introduction: Queries that change data 1 programming 1 11.1.1 What is an action query? 1 12.1.1 Interacting with the interpreter 1 11.1.2 Why use action queries? 1 12.2 Learning objectives 2 11.2 Learning objectives 2 12.3 Tutorial exercises 2 11.3 Tutorial exercises 3 12.3.1 Invoking the interpreter 2 11.3.1 Using a make-table query to create a 12.3.2 Basic programming constructs 3 backup 3 12.3.2.1 Statements 3 12.3.2.2 Variables and assignment 3 Home Previous 5 of 8 Next 12.3.2.3 Predefined functions 4 13.1.2 The Access macro language 2 12.3.2.4 Remark statements 5 13.1.3 The trigger design cycle 3 12.3.3 Creating a module 6 13.2 Learning objectives 3 12.3.4 Creating subroutines with looping and 13.3 Tutorial exercises 4 branching 7 13.3.1 The basics of the macro editor 4 12.3.4.1 Declaring variables 7 13.3.2 Attaching the macro to the event 5 12.3.4.2 Running the subroutine 9 13.3.3 Creating a check box to display update 12.3.4.3 Conditional branching 9 status information 9 12.3.5 Using the debugger 10 13.3.4 The SetValue command 10 12.3.6 Passing parameters 11 13.3.5 Creating conditional macros 10 12.3.7 Creating the Min() function 13 13.3.5.1 The simplest conditional macro 13 12.4 Discussion 14 13.3.5.2 Refining the conditions 15 12.4.1 Interpreted and compiled languages 14 13.3.5.3 Creating a group of named macros 16 12.5 Application to the assignment 16 13.3.6 Creating switchboards 17 13.3.6.1 Using a macro and manually-created 13. Event-Driven Programming Using buttons 21 Macros 13.3.6.2 Using the button wizard 21 13.1 Introduction: What is event-driven 13.3.7 Using an autoexec macro 21 programming? 1 13.4 Discussion 25 13.1.1 Triggers 2 13.4.1 Event-driven programming versus conventional programming 25 Home Previous 6 of 8 Next
  • 4. 13.5 Application to the assignment 26 14.5.1 Using a separate table to store system parameters 20 14. Data Access Objects 14.5.2 Determining outstanding backorders21 14.1 Introduction: What is the DAO hierarchy?1 14.1.1 DAO basics 1 15. Advanced Triggers 14.1.2 Properties and methods 2 15.1 Introduction: Pulling it all together 1 14.1.3 Engines, workspaces, etc. 3 15.2 Learning objectives 1 14.2 Learning objectives 5 15.3 Tutorial exercises 1 14.3 Tutorial exercises 5 15.3.1 Using a macro to run VBA code 1 14.3.1 Setting up a database object 5 15.3.1.1 Creating a wrapper 2 14.3.2 Creating a Recordset object 7 15.3.1.2 Using the RunCode action 2 14.3.3 Using a Recordset object 8 15.3.2 Using activity information to determine 14.3.4 Using the FindFirst method 10 the number of credits 4 14.3.5 The DLookUp() function 12 15.3.2.1 Scenario 4 14.3.5.1 Using DLookUp() in queries 15 15.3.2.2 Designing the trigger 6 14.3.5.2 Understanding the WHERE clause 15 15.3.2.3 Preliminary activities 8 14.4 Discussion 17 15.3.2.4 Looking up the default value 8 14.4.1 VBA versus SQL 17 15.3.2.5 Changing the Record Source of the 14.4.2 Procedural versus Declarative 19 form 10 14.5 Application to the assignment 20 15.3.2.6 Creating the SetValue macro 11 Home Previous 7 of 8 Next 15.3.2.7 Attaching a procedure to the After 15.4.3 Understanding the Update event 11 UpdateBackOrders() function 24 15.3.3 Use an unbound combo box to 15.4.4 Annotated source code for the automate search 12 backorders shortcut module. 27 15.3.3.1 Manual search in Access 12 15.4.4.1 The UpdateBackOrders() function 15.3.3.2 Preliminaries 13 27 15.3.3.3 Creating the unbound combo box 13 15.4.4.2 Explanation of the 15.3.3.4 Automating the search procedure using UpdateBackOrders() function 27 a macro 16 15.4.4.3 The BackOrderItem() subroutine30 15.3.4 Using Visual Basic code instead of a 15.4.4.4 Explanation of the BackOrderItem() macro 19 subroutine 31 15.4 Application to the assignment 20 15.4.1 Triggers to help the user 20 15.4.2 Updating the BackOrders table 22 15.4.2.1 Create the pqryItemsToBackOrder query 23 15.4.2.2 Import the shortcut function 23 15.4.2.3 Use the function in your application 24 15.4.2.4 Modifying the UpdateBackOrders() function 24 Home Previous 8 of 8 Next
  • 5. Access Tutorial 1: Introduction to Microsoft Access The purpose of these tutorials is not to teach you • Microsoft SQL Server Microsoft Access, but rather to teach you some • IBM DB2 generic information systems concepts and skills • Informix using Access. Of course, as a side effect, you will Well-know PC-based (“desktop”) relational DBMSes learn a great deal about the software—enough to include write your own useful applications. However, keep in • Microsoft Access mind that Access is an enormously complex, nearly- • Microsoft FoxPro industrial-strength software development environ- • Borland dBase ment. The material here only scrapes the surface of Access development and database programming. 1.1.1 The many faces of Access Microsoft generally likes to incorporate as many fea- 1.1 Introduction: What is Access? tures as possible into its products. For example, the Microsoft Access is a relational database manage- Access package contains the following elements: ment system (DBMS). At the most basic level, a • a relational database system that supports two DBMS is a program that facilitates the storage and industry standard query languages: Structured retrieval of structured information on a computer’s Query Language (SQL) and Query By Example hard drive. Examples of well-know industrial-strength (QBE); relational DBMSes include • Oracle © Michael Brydon (brydon@unixg.ubc.ca) Last update: 24-Aug-1997 Home Previous 1 o f 17 Next 1. Introduction to Microsoft Access Introduction: What is Access? • a full-featured procedural programming lan- • the procedural programming personality expects guage—essentially a subset of Visual Basic, you to view your application as commands to be • a simplified procedural macro language unique executed sequentially; to Access; • the object-oriented personality expects you to • a rapid application development environment view your application as objects which encapsu- complete with visual form and report develop- late state and behavior information. ment tools; Microsoft makes no effort to provide an overall logi- • a sprinkling of objected-oriented extensions; cal integration of these personalities (indeed, it is and, unlikely that such an integration is possible). Instead, • various wizards and builders to make develop- it is up to you as a developer to pick and choose the ment easier. best approach to implementing your application. For new users, these “multiple personalities” can be Since there are often several vastly different ways to a source of enormous frustration. The problem is implement a particular feature in Access, recogniz- that each personality is based on a different set of ing the different personalities and exploiting the best assumptions and a different view of computing. For features (and avoiding the pitfalls) of each are impor- instance, tant skills for Access developers. • the relational database personality expects you The advantage of these multiple personalities is that to view your application as sets of data; it is possible to use Access to learn about an enor- mous range of information systems concepts without Home Previous 2 o f 17 Next
  • 6. 1. Introduction to Microsoft Access Learning objectives having to interact with a large number of “single-per- • macros and Visual Basic programs for extending sonality” tools, for example: the functionality of database applications. • Oracle for relational databases All these database objects are stored in a single file • PowerBuilder for rapid applications development, named <filename>.mdb. When you are running • SmallTalk for object-oriented programming. Access, a temporary “locking” file named <file- Keep this advantage in mind as we switch back and name>.ldb is also created. You can safely ignore forth between personalities and different computing the *.ldb file; everything of value is in the *.mdb file. paradigms. 1.2 Learning objectives 1.1.2 What is in an Access database file? How do I get started? Although the term “database” typically refers to a col- How do I determine the version I am using? lection of related data tables, an Access database How do I create or edit a database object? includes more than just data. In addition to tables, an What is the database window and what does Access database file contains several different types it contain? of database objects: How do I import an Excel spreadsheet? • saved queries for organizing data, • forms for interacting with the data on screen, How do I delete or rename database objects? • reports for printing results, Home Previous 3 o f 17 Next 1. Introduction to Microsoft Access Tutorial exercises How do I get help from the on-line help Access from the main menu to see which version system? you are using. How do I compact a database to save space? All the screen shots in these tutorials are taken from Access version 7.0 (released as 1.3 Tutorial exercises part of Office 95). Although there are some In this tutorial, you will start by creating a new data- important differences between version 2.0 base file. and version 7.0, the concepts covered here are the same for both. Version 8.0 (released 1.3.1 Starting Access as part of Office 97) is only slightly different • To start Access, you double click the Access icon from version 7.0. ( for version 8.0 and 7.0 or for version 2.0) from within Microsoft Windows. If you are working in the Commerce PC Lab, you will Whenever the instructions given in the tutorial differ significantly from version 7.0, a warning box such as this is used. be working with Access version 2.0. If you are work- ing at home, you will able be to tell what version you 1.3.2 Creating a new database are using by watching the screen “splash” as the pro- gram loads. Alternatively, select Help About • Follow the directions in Figure 1.1 to create a new database file called myfile.mdb. Home Previous 4 o f 17 Next
  • 7. 1. Introduction to Microsoft Access Tutorial exercises FIGURE 1.1: Select the name and location of your new (empty) database. New from thedatabase by selecting File the Create a new main menu or by clicking “new database” button on the tool bar. Note thata you are limited to 8-letter names in Type in new database name and press Enter. version 2.0. Home Previous 5 o f 17 Next 1. Introduction to Microsoft Access Tutorial exercises • Examine the main features of the database win- dow—including the tabs for viewing the different If you are using version 8.0, you can use either univ0_v2.mdb or univ0_v7.mdb for database objects—as shown in Figure 1.2. the tutorials. When you open the file, Access will ask you if you want to convert it to version 1.3.3 Opening an existing database 8.0. Select yes and provide a new name for Since an empty database file is not particularly inter- the converted file (e.g., univ0_v8.mdb) esting, you are provided with an existing database • Open the univ0_vx.mdb file and examine the file containing information about university courses. contents of the Sections table, as shown in For the remainder of this tutorial, we will use a file Figure 1.3. called univ0_v7.mdb, which is available from the tutorial’s Internet site. 1.3.4 Importing data from other If you are using version 2.0, you will need to applications use the univ0_v2.mdb database instead. Access makes it easy to import data from other Although you can open a version 2.0 data- applications. In this section, you will create a new base with version 7.0, you cannot open a ver- table using data from an Excel spreadsheet. sion 7.0 database with version 2.0. Importing • Select File Get External Data Import from the and exporting across versions is possible, main menu and import the depts.xls spread- however. Home Previous 6 o f 17 Next
  • 8. 1. Introduction to Microsoft Access Tutorial exercises FIGURE 1.2: The database window contains all the database objects for a particular application. The database window is always available from the Window menu. Tables — contain data in rows and Modules — columns. contain Visual Basic procedures and functions. Queries — allow the information in Macros — are sets of high- tables to be sorted, level commands that can be filtered, and shown used to process data and in different ways. perform repetitive tasks. Forms — are for Reports —are displaying for organizing information on and printing the screen. information. Home Previous 7 o f 17 Next 1. Introduction to Microsoft Access Tutorial exercises FIGURE 1.3: Open the univ0_vx.mdb file for the version of Access that you are using and then open the Sections table from the mainOpen Database Select File menu. You can open a database object for viewing, for modification, or create a new object. correctthe and Select file open the Sections table. Home Previous 8 o f 17 Next
  • 9. 1. Introduction to Microsoft Access Tutorial exercises sheet as a new table called Departments (see 1.3.5 Getting help Figure 1.4). A recent trend in commercial software (especially from Microsoft) is a reliance on on-line help and doc- In version 2.0, the menu structure is slightly different. As such, you must use File Import. umentation in lieu of printed manuals. As a conse- quence, a good understanding of how to use the on- • Use the import wizard specify the basic import line help system is essential for learning any new parameters. You should accept all the defaults software. In this section, you will use Access’ on-line provided by the wizard except for those shown in help system to tell you how to compact a database. Figure 1.5. • Press F1 to invoke the on-line help system. Find • Double click the Departments table to ensure it information on compacting a database, as shown was imported correctly. in Figure 1.6. • Familiarize yourself with the basic elements of If you make a mistake, you can rename or the help window as shown in Figure 1.7. delete a table (or any database object in the database window) by selecting it and right- 1.3.6 Compacting your database clicking (pressing the right mouse button • Follow the directions provided by the on-line help once). window shown in Figure 1.7 to compact your database. Home Previous 9 o f 17 Next 1. Introduction to Microsoft Access Tutorial exercises FIGURE 1.4: Import the dept.xls spreadsheet as a table called Departments. Double-click depts.xls. ImportFile the from the main menu Select from Get External Data and move the directory containing the file you want to import. with that extension *.xls (files Select files of type will show in the file window). Home Previous 10 o f 17 Next
  • 10. 1. Introduction to Microsoft Access Tutorial exercises FIGURE 1.5: Use the spreadsheet import wizard to import the Excel file. column headings option so Select the first row contains that the column headings in the spreadsheet are not interpreted as data. about primary keystalked Since we have not yet, select no primary key. Home Previous 11 o f 17 Next 1. Introduction to Microsoft Access Tutorial exercises lettersin the first few Type FIGURE 1.6: Use the help system to find of the topic you information on a specific topic are looking for. the list the best match from Select (i.e., “compacting databases”) and double- click to get a list of topics. Double click the most promising entry in this list to get the actual help topic. The Index is the best place to For most students, the help start when you are looking for a system in Access version specific topic. If you need more 2.0 is easier to navigate. structured information or are Use the “cue cards” in looking for an overview, use the version 2.0 to get step-by- Contents tab. step instructions for many operations. Home Previous 12 o f 17 Next
  • 11. 1. Introduction to Microsoft Access Tutorial exercises FIGURE 1.7: Follow the instructions provided by help to compact your database Minimize (rather than close) help when you are working so that you can use the Back button to return to previously visited topics without repeating the search. Press help topics to return to the index. Words underlined with a dashed line provide important definitions. Home Previous 13 o f 17 Next 1. Introduction to Microsoft Access Discussion 1.4 Discussion 1.4.2 Compacting a database As the help system points out, Access database files 1.4.1 The database file in Access can become highly fragmented and grow to become The term “database” means different things depend- much larger than you might expect given the amount ing on the DBMS used. For example in dBase IV, a of data they contain (e.g., multiple megabytes for a database is a file (filename.dbf) containing a handful of records). Compacting the database from single table. Forms and reports are also stored as time to time eliminates fragmentation and can dra- individual files with different extensions. The net matically reduce the disk space requirement of your result is a clutter of files. database. In contrast, an Oracle database has virtually no rela- tionship to individual files or individual projects. For 1.4.3 Renaming a database instance, a database may contain many tables from It is often the case that you are working with a data- different projects/applications and may also be base and want to save it under a different name or stored split into one or more files (perhaps on differ- save it on to a different disk drive. However, one ent machines). command on the File menu that is conspicuous by its Access strikes a convenient balance—all the absence is Save As. “objects” (tables, queries, forms, reports, etc.) for a However, when compacting your database, Access single project/application are stored in a single file. asks for the name and destination of the compacted file. As a result, the compact database utility can be Home Previous 14 o f 17 Next
  • 12. 1. Introduction to Microsoft Access Discussion used as a substitute for the Save As command. This mended sequence for prototyping using Access is is especially useful in situations in which you cannot the following: use the operating system to rename a file (e.g., 1. Model the information of interest in terms of enti- when you do not have access to the Windows file ties and relationships between the entities (this is manager). covered in the lecture portion of the course). 2. Create a table for each entity (Tutorial 2). 1.4.4 Developing applications in Access 3. Specify the relationships between the tables In general, there are two basic approaches to devel- (Tutorial 3). oping information systems: 4. Organize the information in your tables using • in-depth systems analysis, design, and imple- queries (Tutorial 4, Tutorial 5, Tutorial 10) mentation, 5. Create forms and reports to support input and • rapid prototyping (in which analysis, design, and output transactions (Tutorial 6, Tutorial 7). implementation are done iteratively) 6. Enhance you forms with input controls Access provides a number of features (such as (Tutorial 8) graphical design tools, wizards, and a high-level 7. Create action queries (Tutorial 11), macros macro language) that facilitate rapid prototyping. (Tutorial 13), or Visual Basic programs Since you are going to build a small system and (Tutorial 12, Tutorial 14) to perform the transac- since time is limited, you will use a rapid prototyping tion processing functions of the application. approach to build your application. The recom- Home Previous 15 o f 17 Next 1. Introduction to Microsoft Access Application to the assignment 8. Create “triggers” (procedures attached to events) machine, update the links to the data file, and the to automate certain repetitive tasks (Tutorial 15). upgrade is done. 1.4.5 Use of linked tables Do not used linked tables in the assignment. The links are dependent on the absolute Most professional Access developers do not put their directory structure. As a result, if the directory tables in the same database file as their queries, structure on your machine is different from forms, reports, and so on. The reason for this is sim- that on the marker’s machine, the marker will ple: keep the application’s data and interface sepa- not be able to use your application without rate. first updating the links (a time consuming pro- Access allows you to use the “linked table” feature to cess for a large number of assignments). link two database files: one containing all the tables (“data”) and another containing all the interface and 1.5 Application to the assignment logic elements of the application (“interface”). The After completing this tutorial you should be ready to linked tables from the data file show up in the inter- face file with little arrows (indicating that they are not create the database file that you will use for the remainder of the course. actually stored in the interface file). 1. Create an empty database file called your In this way, you can modify or update the interface file without affecting the actual data in any way. You groupID.mdb. Remember that your group number consists of eight digits. just copy the new interface file over to the user’s Home Previous 16 o f 17 Next
  • 13. 1. Introduction to Microsoft Access Application to the assignment 2. Import the inventor.xls spreadsheet as your Products table. 3. Use the compact utility to make a backup copy of your database (use a different name such as backup.mdb). Home Previous 17 o f 17 Next
  • 14. Access Tutorial 2: Tables 2.1 Introduction: The importance 2.2 Learning objectives of good table design How do I enter and edit data in the datasheet Tables are where data in a database is stored; con- view of a table? sequently, tables form the core of any database How do I create a new table? application. In addition to basic data, Access permits a large amount of domain knowledge (such as cap- How do I set the primary key for a table? tions, default values, constraints, etc.) to be stored at How do I specify field properties such as the the table level. input mask and caption? Extra time spent thinking about table design Why won’t an autonumber field restart counting at one? can result in enormous time savings during later stages of the project. Non-trivial changes What are the different types of keys? to tables and relationships become increas- ingly difficult as the application grows in size 2.3 Tutorial exercises and complexity. In this tutorial, you will learn to interact with existing tables and design new tables. © Michael Brydon (brydon@unixg.ubc.ca) Last update: 25-Aug-1997 Home Previous 1 o f 18 Next 2. Tables Tutorial exercises 2.3.1 Datasheet basics such as lecturers, department heads, departmental • If you have not already done so, open the secretaries, and so on. univ0_vx.mdb database file from Tutorial 1. • Return to the database window and create a new • Open the Departments table. The important table as shown in Figure 2.3. elements of the datasheet view are shown in • In the table design window shown in Figure 2.4, Figure 2.1. type in the following information: • Use the field selectors to adjust the width of the Description Field name Data type DeptName field as shown in Figure 2.1. (optional) • Add the Biology department (BIOL) to the table, EmployeeID Text use employee as shown in Figure 2.2. S.I.N. • Delete the “Basket Weaving” record by clicking FName Text First name on its record selector and pressing the Delete LName Text Last name key. Phone Text 2.3.2 Creating a new table Salary Currency In this section you will create and save a very basic skeleton for table called Employees. This table • Select File Save from the main menu (or press could be used to keep track of university employees Control-S) and save the table under the name Employees. Home Previous 2 o f 18 Next
  • 15. 2. Tables Tutorial exercises FIGURE 2.1: The datasheet view of the Departments table. The field names are shown in the “field selectors” across the top of the columns. the columnDeptName draggingby clicking near Resize the border and column the border to the right. You can temporarily sort the records in a particular order by right-clicking any of the field selectors. The records are shown as rows. The black triangle indicates the “current record”. The asterisk (*) indicates a The grey boxes are “record selectors”. place holder for a new record. The “navigation buttons” at the bottom of the window indicate the current record number and allow you to go directly to the first, previous, next, last, or new record. Home Previous 3 o f 18 Next 2. Tables Tutorial exercises FIGURE 2.2: Adding and saving a record to the table. of thea “newrecord byfield (marked byDeptCode field Add new record” clicking in the the asterisk). It is seldom necessary to explicitly save new records (or changes to existing records) since Access automatically saves whenever you move to another record, close the table, quit Access, etc. data, click on thesave theselector (note the To permanently record change to the icon changes from a pencil to a triangle). Home Previous 4 o f 18 Next
  • 16. 2. Tables Tutorial exercises FIGURE 2.3: Create a new table. createthenew table. to Click a New button the table wizard at this point). Select “design view” (avoid using Home Previous 5 o f 18 Next 2. Tables Tutorial exercises FIGURE 2.4: Use the table design window to enter the field properties for the Employees table. data typesfieldthe five and Enter the for names fields. The “description” column allows you to enter a short comment about the field (this information is not processed in any way by Access). The “field properties” section allows you to enter information about the field and constraints on the values for the field. Home Previous 6 o f 18 Next
  • 17. 2. Tables Tutorial exercises 2.3.3 Specifying the primary key FIGURE 2.6: Set the field properties for the Tables normally have a primary key that uniquely EmployeeID field. identifies the records in the table. When you desig- nate a field as the primary key, Access will not allow you to enter duplicate values into the field. • Follow the steps in Figure 2.5 to set the primary key of the table to EmployeeID. 2.3.4 Setting field properties In this section, you will specify a number of field properties for the EmployeeID field, as shown in Figure 2.6. • Since we are going to use the employees’ Social Insurance Number (S.I.N.) to uniquely identify them, set the Field Size property to 11 characters (9 for numbers and 2 for separating spaces) • Set the Input Mask property to the following: 000 000 000;0 • Set the Caption property to Employee ID Home Previous 7 o f 18 Next 2. Tables Tutorial exercises FIGURE 2.5: Set the primary key for the Employees table. fields)on the greythe primary key.field (or Click that form box beside the To select more than one field for use as the primary key, hold down the Control key while clicking on the grey boxes. select Edit the key-shaped from in the tool bar or Either click Primary Key icon the menu. Home Previous 8 o f 18 Next
  • 18. 2. Tables Discussion • Select View Datasheet from the main menu to three small dots ( ) to invoke the input mask switch to datasheet mode as shown in Figure 2.7. wizard. Enter your own S.I.N. and observe the effect of • Follow the instructions provided by the wizard as the input mask and caption on the EmployeeID shown in Figure 2.8. field. • Press F1 while the cursor is still in the input mask • Select View Table Design from the main menu property. Scroll down the help window to find the to return to design mode. meaning of the “0”, “9”, “” and “L” input mask • Set the field properties for FName and LName symbols. (note that Length and Caption are the only two properties that are relevant for these two fields) 2.4 Discussion 2.3.5 Using the input mask wizard 2.4.1 Key terminology In this section, you will use the input mask wizard to A key is one or more fields that uniquely determine create a complex input mask for a standard field the identity of the real-world object that the record is type. You will also use the help system to learn more meant to represent. For example, there is a record in about the meaning of the symbols used to create the student information system that contains infor- input masks. mation about you as a student. To ensure that the • Select the Phone field, move the cursor to the record is associated with you and only you, it con- input mask property, and click the button with Home Previous 9 o f 18 Next 2. Tables Discussion FIGURE 2.7: Observe the effect of the input mask and caption properties on the behavior of the EmployeeID field during data entry numbers intovarious characters and Try entering the EmployeeID field. If a caption is specified, it replaces the done to clear the changes to the record. Press the Escape key when you are field name in the field selector. Note that the input mask will not let you type any characters other than numbers from 0-9. In addition, the spaces between the groups of numbers are added automatically. Input masks provide a relatively easy way to avoid certain basic data input errors without having to write complex error checking programs. Note, however, that it is possible to over-constrain a field so that users are unable to enter legitimate values. Home Previous 10 o f 18 Next
  • 19. 2. Tables Discussion FIGURE 2.8: Use the input mask wizard to create an input mask. number” from the Select “phone list of commonly- used field types. The items in this list depend on the “international settings” specified for Windows (e.g., “Zip Code” may show instead of Since the input mask controls how “Postal Code”). the information in the field looks, it is possible to save some disk space by storing the data without the edit the 2, youmask In Step input may extras symbols, spaces, etc. For the size of system we are building, (e.g., remove the however, this savings is negligible. area code section). Home Previous 11 o f 18 Next 2. Tables Discussion tains a field called “student number” that is guaran- nated key is made by joining together two or teed to be unique. more fields. Course numbers at UBC provide a The advantage of using student number as a key good example of a concatenated key made by instead of some other field—like “student name”—is joining together two fields: DeptCode and that there may be more than one person with the CrsNum. For example, department alone cannot same first and last name. The combination of stu- be the primary key since there are many courses dent name and address is probably unique (it is in each department (e.g., COMM 335, COMM improbable that two people with the same name will 391). Similarly, course number cannot be used as at the same address) but using these two fields as a a key since there are many courses with the key would be cumbersome. same number in different departments (e.g., COMM 335, HIST 335, MATH 335). However, Since the terminology of keys can be confusing, the department and course number together form a important terms are summarized below. concatenated key (there is only one COMM 335). 1. Primary key — The terms “key” and “primary 3. Foreign key: In a one-to-many relationship, a key” are often used interchangeably. Since there foreign key is a field (or fields) in the “child” may be more than one candidate key for an record that uniquely identifies the correct “parent” application, the designer has to select one: this is record. For example, DeptCode and CrsNum in the primary key. the Sections table are foreign keys since these 2. Concatenated key: The verb “concatenate” two keys taken together are the primary key of means to join together in a series. A concate- Home Previous 12 o f 18 Next
  • 20. 2. Tables Discussion the Courses table. Foreign keys are identified in In addition, you can use the comment field in the Access by creating relationships (see Tutorial 3). table design window to document the meaning of field names. 2.4.2 Fields and field properties It is strongly recommended that you avoid all 2.4.2.1 Field names non-alphanumeric characters whenever you Access places relatively few restrictions on field name a field or database object. Although names and thus it is possible to create long, descrip- Access will permit you to use names such as tive names for your fields. The problem is that you Customer#, non-alphanumeric characters have to type these field names when building que- (such as #, /, $, %, ~, @, etc.) may cause ries, macros, and programs. As such, a balance undocumented problems later on. should be struck between readability and ease of typing. You are advised to use short-but-descriptive 2.4.2.2 Data types field names with no spaces. The field's data type tells Access how to handle the For example, in Section 2.3.2 you created a field information in the field. For instance, if the data type with name FName. However, you can use the caption is date/time, then Access can perform date/time property to provide a longer, more descriptive label arithmetic on information stored in the field. If the such as First name. The net result is a field name same date is stored as text, however, Access treats that is easy to type when programming and a field it just like any other string of characters. Normally, caption that is easy to read when the data is viewed. Home Previous 13 o f 18 Next 2. Tables Discussion the choice of data type is straightforward. However, for use as a primary key when no other key is the following guidelines should be kept in mind: provided or is immediately obvious. 1. Do not use a numeric data type unless you are Since an autonumber is really Long Integer going to treat the field as a number (i.e., perform and since relationships can only be created mathematical operations on it). For instance, you between fields with the same data type, it is might be tempted to store a person's student important to remember that if an autonumber number as an integer. However, if the student is used on the “one” side of a relationship, a number starts with a zero, then the first digit is long integer must be used for the “many” side. dropped and you have to coerce Access into dis- playing it. Similarly, a UBC course number (e.g., 2.4.2.3 “Disappearing” numbers in 335) might be considered a number; however, autonumber fields since courses like 439B have to accommodated, If, during the process of testing your application, you a numeric data type for the course number field is add and delete records from a table with an auto- clearly inappropriate. number key, you will notice that the deleted keys are 2. Access provides a special data type called Auto not reclaimed. Number (Counter in version 2.0). An autonum- ber/counter is really a number of type Long Inte- For instance, if you add records to your Customer ger that gets incremented by Access every time table (assuming that CustID is an autonumber), you a new record is added. As such, it is convenient will have a series of CustID values: 1, 2, 3… If you Home Previous 14 o f 18 Next
  • 21. 2. Tables Discussion later delete customer 1 and 2, you will notice that lutely no difference whether the first customer in your your list of customers now starts at 3. customers table is CustID = 1 or 534. Clearly, it would be impossible for Access to renum- 2.4.2.4 Input masks ber all the customers so the list started at 1. What An input mask is a means of restricting what the user would happen, for instance, to all the printed can type into the field. It provides a “template” which invoices with CustID = 2 on them? Would they refer tells Access what kind of information should be in to the original customer 2 or the newly renumbered each space. For example, the input mask LLLL customer 2? consists of two parts: The bottom line is this: once a key is 1. The right brace ensures that every character assigned, it should never be reused, even if the user types is converted into upper case. the entity to which it is assigned is subse- Thus, if the user types comm, it is automatically quently deleted. Thus, as far as you are con- converted to COMM. cerned, there is no way to get your customers 2. The characters LLLL are place holders for letters table to renumber from CustID = 1. from A to Z with blank spaces not allowed. What this means is that the user has to type in exactly Of course, there is a long and complicated way to do four letters. If she types in fewer than four or it, but since used an autonumber in the first place, types a character that is not within the A to Z you do not care about the actual value of the key— scope (e.g., , 7, %), Access will display an error you just want it to be unique. In short, it makes abso- message. Home Previous 15 o f 18 Next 2. Tables Discussion There are a large number of special symbols used The semicolon and zero at the end of this input mask for the input mask templates. Since the meaning of are important because, as the on-line help system many of the symbols is not immediately obvious, points out, an input mask value actually consists of there is no requirement to remember the character three parts (or “arguments”), each separated by a codes. Instead, simply place the cursor on the input semicolon: mask property and press F1 to get help. In addition, • the actual template (e.g., 000-0000), the wizard can be used to provide a basic input mask • a value (0 or 1) that tells Access how to deal with which can later be modified. literal characters, and 2.4.2.5 Input masks and literal values • the character to use as a place holder (showing the user how many characters to enter). To have the input mask automatically insert a char- When you use a literal character in an input mask, acter (such as a space or a dash) in a field, use a slash to indicate that the character following it is a lit- the second argument determines whether the literal value is simply displayed or displayed and stored in eral. the table as part of the data. For example, to create an input mask for local tele- For example, if you use the input mask 000- phone numbers (e.g., 822-6109), you would use the following template: 000-0000;0 (the dash is a lit- 0000;1, Access will not store the dash with the tele- phone number. Thus, although the input mask will eral value and appears automatically as the user enters the telephone number). always display the number as “822-6109”, the num- ber is actually stored as “8226109”. By using the Home Previous 16 o f 18 Next
  • 22. 2. Tables Application to the assignment input mask 000-0000;0, however, you are telling 2.5 Application to the assignment Access to store the dash with the rest of the data. You now have the skills necessary to implement your If you use the wizard to create an input mask, tables. it asks you a simple question about storing lit- • Create all the tables required for the assignment. eral values (as shown in Figure 2.8) and fills • Use the autonumber data type (counter in version in the second argument accordingly. How- 2.0) for your primary keys where appropriate. ever, if you create the input mask manually, • Specify field properties such as captions, input you should be aware that by default, Access mask, and defaults where appropriate. does not store literal values. In other words, If you create an input mask for ProductID, the input mask 000-0000 is identical to the ensure you understand the implications of input mask 000-0000;1. This has impor- Section 2.4.2.5. tant consequences if the field in question is subject to referential integrity constraints (the • Set the Default property of the OrderDate field value “822-6109” is not the same as so that the current date is automatically inserted “8226109”). into the field when a new order is created (hint: see the Date() function in the on-line help sys- tem). Home Previous 17 o f 18 Next 2. Tables Application to the assignment • Do not forget to modify your Products table (the data types, lengths, and field properties of imported tables normally need to be fine tuned) • Populate (enter data into) your master tables. Do not populate your transaction tables. For the purpose of the assignment, the term “transaction” tables refers to tables that con- tain information about individual transactions (e.g., Orders, OrderDetails, Ship- ments, ShipmentDetails). “Master” tables, in contrast, are tables that either do not contain information about transactions (e.g., Customers) or contain only summary or status information about transactions (e.g., BackOrders). Home Previous 18 o f 18 Next
  • 23. Access Tutorial 3: Relationships 3.1 Introduction: The advantage of 1. Wasted space — Note that for COMM 290, the using tables and relationships same basic course information is repeated for every section. Although the amount of disk space A common mistake made by inexperienced data- wasted in this case is trivial, this becomes an base designers (or those who have more experience important issue for very large databases. with spreadsheets than databases) is to ignore the 2. Difficulty in making changes — What happens if recommendation to model the domain of interest in the name of COMM 290 is changed to “Mathe- terms of entities and relationships and to put all the matical Optimization”? This would require the information they need into a single, large table. same change to be made eight times. What if the Figure 3.1 shows such a table containing information person responsible for making the change for- about courses and sections. gets to change all the sections of COMM 290? • If you have not already done so, open the What then is the “true” name of the course? univ0_vx.mdb database. 3. Deletion problems — What if there is only one • Open the Catalog View table. section of COMM 290 and it is not offered in a The advantage of the single-table approach is that it particular year? If section 001 is deleted, then the requires less thought during the initial stages of system no longer contains any information about application development. The disadvantages are too the course itself, including its name and number numerous to mention, but some of the most impor- of credits. tant ones are listed below: © Michael Brydon (brydon@unixg.ubc.ca) Last update: 22-Aug-1997 Home Previous 1 o f 10 Next 3. Relationships Introduction: The advantage of using tables and relation- FIGURE 3.1: The “monolithic” approach to database design—the Catalog View table contains information about courses and sections. The course “COMM 290” consists of many sections. Each section has some information unique to that section (such as Time, Days, Building, Room); however, the basic course information (e.g., Title, Credits) is the same for all sections of a particular course. Home Previous 2 o f 10 Next
  • 24. 3. Relationships Introduction: The advantage of using tables and relation- 4. Addition problems — If a new section is added to FIGURE 3.2: A one-to-many relationship between any course, all the course information has to be Courses and Sections. typed in again. Not only is this a waste of time, it increases the probability of introducing errors into the system. 3.1.1 “Normalized” table design The problems identified above can be avoided by spitting the Catalog View table into two separate tables: 1. Courses— information about courses only 2. Sections — information about sections only. Access uses relationships in the following way: The key to making this work is to specify a relation- Assume you are looking at Section 004 of ship between Courses and Sections so that when COMM 290. Since Dept and CrsNum are included in we look at a section, we know which course it the Sections table, and since a relationship line belongs to (see Figure 3.2). Since each course can exists between the same two fields in the Courses have one or more sections, such a relationship is table, Access can trace back along this line to the called “one-to-many”. Courses table and find all the course-specific infor- mation. All other sections of COMM 290 point back Home Previous 3 o f 10 Next 3. Relationships Learning objectives to the same record in the Courses table so the • Select Tools Relationships from the main course information only needs to be stored once. menu. 3.2 Learning objectives Why do I want to represent my information in In version 2.0 the menu structure is slightly different. As such, you select Edit Relation- ships instead. multiple tables connected by relationships? How do I create relationships in Access? • To add a table to the relationship window, select How do I edit or change relationships? Relationships Show Table from menu or press the show table icon ( ) on the tool bar. What is referential integrity and why is it • Perform the steps shown in Figure 3.3 to add the important? Courses and Sections tables. • Specify the relationship between the primary 3.3 Tutorial exercises key in Courses and the foreign key in Sec- tions. This is shown in Figure 3.4. 3.3.1 Creating relationships between tables Do not check cascading deletions or updates • Close the Catalog View table and return to unless you are absolutely sure what they mean. See on-line help if you are curious. the database window. Home Previous 4 o f 10 Next
  • 25. 3. Relationships Tutorial exercises FIGURE 3.3: Add the Courses and Sections tables to the relationship window. The rectangular “field list” represents a table. Note that the key (or keys) composing double-click or presswish toRepeat aseither Select the table you Add. add and necessary. the primary key are shown in bold type. If you accidently add a table more than once, it will show up with a table name_1 label. To delete the extra version, click anywhere on the unwanted rectangle and press the delete key. Home Previous 5 o f 10 Next 3. Relationships Tutorial exercises FIGURE 3.4: Create a relationship between the two tables. on the “one” side ofkey Select the primary the foreign key on thefields onsidethe the Drag the selected “many” to of relationship. relationship. To select a concatenated key (more than one If done field) hold down the correctly, the Control key while connectivity (1 selecting. to ∞) shows on the relationship line(s). Ensure that the correct fields are associated with each other (this must be done manually for concatenated keys). enforcethe box to Check referential integrity. Home Previous 6 o f 10 Next
  • 26. 3. Relationships Discussion 3.3.2 Editing and deleting relationships Note that simply deleting the table in the rela- There are two common reasons for having to edit or tionship window does not delete the relation- delete a relationship: ship, it merely hides it from view. 1. You want to change the data type of one of the 3.4 Discussion fields in the relationship — Access will not let you do this without first deleting the relationship (after 3.4.1 One-to-many relationships you change the data type, you must re-create the relationship). There are three types of relationships that occur in 2. You forget to specify referential integrity — if the data modeling: “1” and “∞” symbols do not appear on the rela- 1. one-to-one — A one-to-one relationship exists tionship line, then you have not checked the box between a student and a student number. to enforce referential integrity. 2. one-to-many — A one-to-many relationship In this section, assume that we have forgotten to exists between courses and sections: each enforce referential integrity between Courses and course may consist of many sections, but each Sections. section is associated with exactly one course. • Perform the steps shown in Figure 3.5 to edit the 3. many-to-many — A many-to-many relationship relationship between Courses and Sections. exists between students and courses: each stu- dent can take many courses and each course can contain many students. Home Previous 7 o f 10 Next 3. Relationships Discussion FIGURE 3.5: Edit an existing relationship. The missing “1” and “∞” symbols indicate that referential integrity has not been enforced. the joiningrelationshipon either lineon Select the line (click by clicking if the key is concatenated). If you do this correctly, the line becomes darker. click to get the edit/delete pop-up With the relationship selected, right- menu. If you do not get this menu, make sure you have correctly selected the relationship. Home Previous 8 o f 10 Next
  • 27. 3. Relationships Discussion Although the data modeling technique used most “many” side of a relationship has a corresponding often in information system development—Entity- record on the “one” side. Relationship diagraming—permits the specifica- Enforcing referential integrity means that you cannot, tion of many-to-many relationships, these relation- for instance, create a new record in the Sections ships cannot be implemented in a relational table without having a valid record in the Courses database. As a consequence, many-to-many rela- table. This is because having a section called tionships are usually broken down into a series of “BSKW 101 Section 001” is meaningless unless one-to-many relationships via “composite entities” there is a course called “BSKW 101”. In addition, ref- (alternatively, “bridging tables”). Thus to implement erential integrity prevents you from deleting records the student-takes-course relationship, three tables on the “one” side if related records exist on the are used: Students, Courses, and Student- “many” side. This eliminates the problem of TakesCourse. “orphaned” records created when parent records are deleted. 3.4.2 Referential integrity Referential integrity is especially important in the One important feature of Access is that it allows you context of transaction processing systems. Imagine to enforce referential integrity at the relationship that someone comes into your store, makes a large level. What is referential integrity? Essentially, refer- purchase, asks you to bill customer number “123”, ential integrity means that every record on the and leaves. What if your order entry system allows you to create an order for customer “123” without Home Previous 9 o f 10 Next 3. Relationships Application to the assignment first checking that such a customer exists? If you A primary key and a foreign key must be of have no customer 123 record, where do you send the same data type before a relationship can the bill? be created between them. Because of this, it In systems that do not automatically enforce referen- is important to remember that the autonumber tial integrity, these checks have to be written in a pro- data type (or counter in version 2.0) is really a gramming language. This is just one example of how long integer. table-level features can save you enormous pro- It never makes sense to have a relationship gramming effort. between two autonumber fields. A foreign key Enforcing referential integrity has obvious cannot be an autonumber since referential implications for data entry: You cannot popu- integrity constraints require it to take on a an late the “many” side of the table until you pop- existing value from a parent table. ulate the “one” side. 3.5 Application to the assignment • Specify all relationships—including referential integrity constraints—between tables in your sys- tem. You are not responsible for cascading updates/deletions in this assignment. Home Previous 10 o f 10 Next
  • 28. Access Tutorial 4: Basic Queries Using QBE 4.1 Introduction: Using queries to Once a query is defined, it can be used in exactly the get the information you need same way as a table. Because of this, it is useful to think of queries as “virtual tables”. Similarly, in some At first glance, it appears that splitting information DBMSes, queries are called “views” because they into multiple tables and relationships creates more of allow different users and different applications to a headache than it is worth. Many people like to have different views of the same data. have all the information they need on one screen (like a spreadsheet, for instance); they do not want to 4.2 Learning objectives have to know about foreign keys and relationships and so on. Do queries contain any data? Queries address this problem. They allow the user to How do I create a query? join data from one or more tables, order the data in What can I do with a query? different ways, calculate new fields, and specify cri- teria to filter out certain records. How do I create a calculated field? The important thing is that the query itself contains Why does Access add square brackets around field names? no data—it merely reorganizes the data from the table (or tables) on which it is built without changing What names should I give the queries I the “underlying tables” in any way. create? What does the ampersand operator () do? © Michael Brydon (brydon@unixg.ubc.ca) Last update: 25-Aug-1997 Home Previous 1 o f 27 Next 4. Basic Queries Using QBE Tutorial exercises What is a non-updatable recordset? How do I 4.3.2 Five basic query operations tell whether a query results in a non- 4.3.2.1 Projection updatable recordset? Projecting a field into a query simply means includ- 4.3 Tutorial exercises ing it in the query definition. The ability to base a query on a subset of the fields in an underlying table 4.3.1 Creating a query (or tables) is particularly useful when dealing with tables that contain some information that is confiden- • Use the New button in the Queries pane of the tial and some that is not confidential. For instance, database window to create a new query as the Employees table you created in Tutorial 2 con- shown in Figure 4.1. tains a field called Salary. However, most of the • Add the Courses table to the query as shown in queries seen by end-users would not include this Figure 4.2. information, thereby keeping it private. • Examine the basic elements of the query design • Perform the steps shown in Figure 4.4 to project screen as shown in Figure 4.3. the DeptCode, CrsNum, and Title fields into • Save your query (Control-S) using the name the query definition. qryCourses. • Select View Datasheet from the menu to see the results of the query. Alternatively, press the datasheet icon ( ) on the tool bar. Home Previous 2 o f 27 Next
  • 29. 4. Basic Queries Using QBE Tutorial exercises FIGURE 4.1: Create a new query. the database window. in Select the Queries tab createthenew query. to Press a New button Avoid the use of the query wizard at this point. Queries are very important and it is best to learn to create them from scratch. Home Previous 3 o f 27 Next 4. Basic Queries Using QBE Tutorial exercises FIGURE 4.2: Add tables to your query using the “show table” window. by selecting it and pressing Addquery Add the Courses table to the (alternatively, you can simply double- click on the table you want to add). table”Close when“modal”—you can Press window is done (the “show The “show table” window is always available from the Query Show Table not do anything else in Access until a menu. Alternatively, you can press the modal window is closed). “show table” button on the tool bar. Home Previous 4 o f 27 Next
  • 30. 4. Basic Queries Using QBE Tutorial exercises FIGURE 4.3: The basic elements of the query design screen. The upper If you “lose” tables in the top pane contains pane, you have to use the field lists for horizontal and vertical scroll the tables on bars to return to the upper-left which the corner of the pane. query is based. Field row— shows the name of the fields included in the query. The lower Table row— shows the name of the pane contains table that the field comes from. To get the actual table names in version 2.0, select View query Table Names from the menu. definition. Sort row— allows you to specify the order in which the records are Criteria row — allows you Show boxes— determine displayed to specify criteria for whether fields included including or excluding in the query are actually records from the results set. displayed. Home Previous 5 o f 27 Next 4. Basic Queries Using QBE Tutorial exercises FIGURE 4.4: Project a subset of the available fields into the query definition. drag it the field querywish to project and Select into the you definition grid. Alternatively, double-click the field. To project all the fields in the Courses table (including any that might be added to the table after this query is created) drag the asterisk (*) into the query definition grid. To save time when projecting fields, select more than one field at once (by holding down the Control key) and dragging all the fields as a group. Home Previous 6 o f 27 Next
  • 31. 4. Basic Queries Using QBE Tutorial exercises • Select View Query Design to return to design 4.3.2.3 Selection mode. Alternatively, press the design icon ( ) You select records by specifying conditions that each on the tool bar. record must satisfy in order to be included in the 4.3.2.2 Sorting results set. In “query-by-example” you enter exam- ples of the results you desire into the criteria row. When you use a query to sort, you do not change the physical order of the records in the underlying table • Perform the steps shown in Figure 4.6 to select only those courses with a DeptCode = “COMM”. (that is, you do not sort the table). As a result, differ- ent queries based on the same table can display the 4.3.2.4 Complex selection criteria records in different orders. It is also possible to create complex selection criteria • Perform the steps shown in Figure 4.5 to sort the using Boolean constructs such as AND, OR, and results of qryCourses by DeptCode and NOT. CrsNum. • Project the Credits field into the query. • Perform the steps shown in Figure 4.7 to create a Since a query is never used to display data to query giving the following result: a user, you can move the fields around within “Show the department, course number, and title the query definition to get the desired sorting of all courses in the Commerce department for precedence. You then reorder the fields in the which the number of credits is greater than form or report for presentation to the user. three.” Home Previous 7 o f 27 Next 4. Basic Queries Using QBE Tutorial exercises FIGURE 4.5: Sorting the results set on one or more fields. and “descending” for the CrsNum field.field Select “ascending” for the DeptCode When multiple sort fields are specified, the sorting precedence is from left to right (e.g., DeptCode is sorted first the order of the records. View the results and notice and then CrsNum is sorted within each set of matching DeptCodes). Home Previous 8 o f 27 Next
  • 32. 4. Basic Queries Using QBE Tutorial exercises FIGURE 4.6: Select a subset of records from the Courses table matching a specific criterion. of the the expression “COMM”could also typerow Type DeptCode field. You in the criteria = “COMM” but the equal sign is always implied unless another relational operator is used. matching results. Only records View the the criteria are shown. Home Previous 9 o f 27 Next 4. Basic Queries Using QBE Tutorial exercises FIGURE 4.7: Select records using an AND condition. When multiple criteria are placed in the same row, they are AND-ed. In other words, the records in the results set Show the result. must satisfy DeptCode = “COMM” AND Credits 3. Note that the number 3 is not in quotation marks whereas the string of characters “COMM” is. Uncheck the “show” box (Credits is used as a criterion but “COMM” first criteria: Enter the the same row, enter the second In 3 it is not displayed in the results set) Home Previous 10 o f 27 Next
  • 33. 4. Basic Queries Using QBE Tutorial exercises • Perform the steps shown in Figure 4.8 to create a • Project Title from the Courses table and query giving the following result: DeptCode, CrsNum, Section and Catalog- “Show the department, course number, and title Num from the Sections table (see Figure 4.9). of all courses from the Commerce department • Follow the instructions in Figure 4.10 to move and also show those from the Creative Writing CatalogNum to the far left of the query definition department for which the number of credits is grid. greater than three.” Access performs an automatic lookup of information 4.3.2.5 Joining from the “one” side of the relationship whenever the a valid value is entered into the foreign key of the In Tutorial 3, you were advised to break you informa- “many” side of the relationship. To see how this tion down into multiple tables with relationships between them. In order to put this information back works, create a new section of “MUSC 105”: • Scroll to the bottom of the query in datasheet together in a usable form, you use a join query. • Close qryCourses. mode and click on the department field. • Open the relationships window and ensure you • Enter “MUSC”. have a relationship defined between Courses • Enter “105” in the course number field. and Sections. If you do not, create one now (do Once Access knows the DeptCode and CrsNum of not forget to enforce referential integrity). a section, it can uniquely identify the course that the • Create a new query called qryCatalogNum section belongs to (which means it also knows the based on the Courses and Sections tables. values of Title, Credits, Activity, etc.) Home Previous 11 o f 27 Next 4. Basic Queries Using QBE Tutorial exercises FIGURE 4.8: Select records using an AND and an OR condition. When multiple criteria are placed in different rows, then they are OR-ed. In other words, the records in the results set must satisfy DeptCode = “COMM” OR (DeptCode = “CRWR” AND Credits 3). criterion in the Enter the Credits DeptCode Enter the second row. criteria in different rows. Home Previous 12 o f 27 Next
  • 34. 4. Basic Queries Using QBE Tutorial exercises FIGURE 4.9: Create a query that joins Courses and Sections. Note that the relationship betweeninto the query. Bring Courses and Sections the tables is inherited from the relationship window. the query definition.both tables into Project fields from Home Previous 13 o f 27 Next 4. Basic Queries Using QBE Tutorial exercises FIGURE 4.10: Move a field within the query definition grid. “column selector”grey Click once on the above the field you want to move (if properly selected, the column turns black). To delete a field from the query definition, select it and press the Delete key. its new location. column to Drag the selected Home Previous 14 o f 27 Next
  • 35. 4. Basic Queries Using QBE Tutorial exercises 4.3.3 Creating calculated fields the expression involves two fields from the Courses A calculated field is a “virtual field” in a query for table (DeptCode and CrsNum) and the ampersand which the value is a function of one or more fields in operator (see Section 4.4.2 for more information on the underlying table. To illustrate this, we will create using the ampersand operator). two calculated fields: • Create a new query called qryCourseLengths based on the Courses table. 1. one to combine DeptCode and CrsNum into one • Follow the instructions in Figure 4.11 to create field, the calculated field Course 2. one to translate the Credits field into a dichoto- • Run the query to verify the results, as shown in mous string variable (full year or half Figure 4.12. year). The syntax of a calculated field is always the same: When you use field names in expressions, calc field name: definition Access normally adds square brackets. This For example, the syntax for the calculated field is not cause for concern because in Access, called Course is: square brackets simply indicate the name of a Course: DeptCode CrsNum field (or some other object in the Access envi- ronment). However, if your field name con- The calculated field name can be just about any- tains blank spaces (e.g., Dept Code), the thing, as long as it is unique. The definition is any square brackets are NOT optional—you must expression that Access can evaluate. In this case, Home Previous 15 o f 27 Next 4. Basic Queries Using QBE Tutorial exercises FIGURE 4.11: Create a calculated field based on two other fields. The zoom window provides more room to type than the tiny space in the query definition grid. Invoke the zoom window by moving to the area of the grid in which you wish to type and either right-click or press the Shift-F2 keys. the Field row of Put the cursor in the first column and invoke the zoom window. and the definition Type in the name Press OK when you of the calculated have finished typing field. The name the expression. cannot be the same as that of an existing field. Home Previous 16 o f 27 Next
  • 36. 4. Basic Queries Using QBE Tutorial exercises FIGURE 4.12: The resulting calculated field. The name of the calculated field shows in the field selector. When the zoom window is closed, Access adds square brackets to the field names. Since the field names in this example do not contain spaces, the brackets are optional. The ampersand operator () simply tacks CrsNum onto the end of DeptCode. Home Previous 17 o f 27 Next 4. Basic Queries Using QBE Tutorial exercises type them every time you use the field name three credits is a full-year course). To do this, we will in an expression. use the “immediate if” (iif) function. • Search on-line help for information about the 4.3.3.1 Refining the calculated field iif() function. Instead of having DeptCode and CrsNum run Basically, the function uses the following syntax: together in the new Course field, you may prefer to iif(expression, true part, have a space separating the two parts. false part) • Edit the Courses field by clicking on the field row to implement the following logic: and invoking the zoom box. IF expression = TRUE THEN • Add a space (in quotation marks) between the RETURN true part two constituent fields: ELSE Course: DeptCode ” ” CrsNum RETURN false part • Switch to datasheet mode to see the result. END IF 4.3.3.2 A more complex calculated field • Create a new calculated field called Length: To create a calculated field that maps Credits to a Length: iif(Credits 3, “full dichotomous string variable, we need a means of year”, “half year”) testing whether the value of Credits exceeds a • Verify the results, as shown in Figure 4.13. certain threshold (e.g., any course with more than Home Previous 18 o f 27 Next
  • 37. 4. Basic Queries Using QBE Tutorial exercises FIGURE 4.13: Create a calculated field using the “immediate if” function Length: iif(Credits3, “fullwith the following expression: Create a calculated field called Length year”, “half year”) Home Previous 19 o f 27 Next 4. Basic Queries Using QBE Discussion 4.3.4 Errors in queries 4.4 Discussion It may be that after defining a calculated field, you get the “enter parameter” dialog box shown in 4.4.1 Naming conventions for database Figure 4.14 when you run the query. This occurs objects when you spell a field name incorrectly. Access can- There are relatively few naming restrictions for data- not resolve the name of the misspelled field and thus base objects in Access. However, a clear, consistent asks the user for the value. To eliminate the problem, method for choosing names can save time and avoid simply correct the spelling mistake. confusion later on. Although there is no hard and fast FIGURE 4.14: A spelling error in a calculated naming convention required for the assignment, the field. following points should be kept in mind: • Use meaningful names — An object named Table1 does not tell you much about the con- Access cannot find the tents of the table. Furthermore, since there is no field named Creditz practical limit to the length of the names, you should not use short, cryptic names such as s96w_b. As the number of objects in your data- base grows, the time spent carefully naming your objects will pay itself back many times. Home Previous 20 o f 27 Next
  • 38. 4. Basic Queries Using QBE Discussion • Use capitalization rather than spaces to separate • Stick to standard alphanumeric characters — You words — Unlike many database systems, Access should limit yourself to the characters [A...Z], allows spaces in object names. However, if you [a...z], [0...9], and perhaps underscore (_) and choose to use spaces, you will have to enclose dash (-). Although Access allows you to use virtu- your field names in square brackets whenever ally any character, undocumented problems have you use them in expressions (e.g., [Back been encountered in the past with non-alphanu- Orders]). As such, it is slightly more efficient to meric characters such as the pound sign (#). use a name such as BackOrders than Back Table 4.1 shows a suggested naming convention for Orders. Access database objects (you will discover what • Give each type of object a distinctive prefix (or these objects are in the course of doing the tutorials). suffix) — This is especially important in the con- text of queries since tables and queries cannot 4.4.2 The ampersand () operator have the same name. For example, you cannot The ampersand operator is like any other operator (e.g., +, -, ×, ÷) except that it is intended for use on have a table named BackOrders and a query named BackOrders. However, if all your query strings of characters. What the ampersand does is names are of the form qryBackOrders, then simply add one string on to the end of another string distinguishing between tables and queries is (hence its other name: the “concatenation” operator). straightforward. For example, the expression “First string” “Second string” Home Previous 21 o f 27 Next 4. Basic Queries Using QBE Discussion Table 4.1: A suggested naming convention for yields the result Access database objects. First stringSecond string However, if a space is include within the quotation Object type Prefix Example marks of the second string (“ Second string”), table (none) OrderDetails the result is: query qry qryNonZeroBackOrders First string Second string parameter pqry pqryItemsInOrder query 4.4.3 Using queries to populate tables form frm frmOrders on the “many” side of a relationship sub form sfrm sfrmOrderDetails In Section 4.3.2.5, you added a record to the Sec- switchboard swb swbMainSwitchboard form tions table to demonstrate the automatic lookup feature of Access. However, a common mistake report rpt rptInvoice when creating queries for entering data into tables sub report srpt srptInvoiceDetails on the “many” side of a relationship is to forget to macro mcr mcrOrders project the table’s foreign key. That is, faced with two Visual Basic bas basUtilities tables containing the fields DeptCode and CrsNum, module you project the fields from the wrong table (the “one” side) into your query definition. Home Previous 22 o f 27 Next
  • 39. 4. Basic Queries Using QBE Discussion To illustrate the problem, do the following: 4.4.4 Non-updatable recordsets • Open the qryCatalogNum query and make the Another problem that sometimes occurs when creat- changes shown in Figure 4.15. ing join queries is that the query is not quite right in • Attempt to save the new section of “MUSC 105” some way. In such cases, Access will allow you to as shown in Figure 4.16. view the results of the query, but it will not allow you There are two ways to avoid this error when deciding to edit the data. which fields to project into your join queries: In this section, will look at a nonsensical query that 1. Always show the table names when creating a results from an incompletely specified relationship. query based on more than one table. That way, As you will probably discover, however, there are you can quickly determine whether the query many different way to generate nonsensical queries. makes sense. • Create a new query called qryNonUpdate 2. Always ask yourself: “What is the purpose of this based on the Courses and Sections tables. query?” If the answer is: “To add new records to • Delete the CrsNum relationship but leave the the Sections table,” you automatically have to DeptCode relationship intact, as shown in include all the fields from the Sections table. Figure 4.17. Fields from the Courses table are only shown The result of this query is that every section in a for validation purposes. Commerce course will be associated with every Commerce course. Since allowing the user to update Home Previous 23 o f 27 Next 4. Basic Queries Using QBE Discussion FIGURE 4.15: Create a data-entry query without a foreign key. In version 2.0 you have to Reorder the fields (by dragging and dropping) so select View Table Names to display the that DeptCode and table row. CrsNum are on the far left. DeptCodesource table for Change the and CrsNum from Sections to Courses. Switch to datasheet mode and attempt to add a new section of “MUSC 105”. Home Previous 24 o f 27 Next
  • 40. 4. Basic Queries Using QBE Discussion FIGURE 4.16: The result of attempting to save a record in which the foreign key is missing Since the fields are bound to the Courses table, you are attempting to replace the current record in the Courses table with “MUSC 105”. But since a “MUSC 105” already exists, you get an error. new sectionsave the Attempt to by clicking its record selector. Home Previous 25 o f 27 Next 4. Basic Queries Using QBE Discussion FIGURE 4.17: Create a non-updatable recordset. view thefields fromdatasheet mode Project query in both tables and (i.e., view the “recordset”). Attempt to change a value in the recordset. CrsNum relationship byquery, deleteitthe To create a nonsensical clicking on Note the absence of the asterisk and the “new record” and pressing the Delete key. Leave the row. This is a sure sign that the recordset is non-updatable. DeptCode relationship intact. Home Previous 26 o f 27 Next
  • 41. 4. Basic Queries Using QBE Application to the assignment the values in this recordset would create anomalies, should appear automatically. If they do not, see Access designates the recordset as non-updatable. Section 4.4.3. • Create a calculated field in your qryOrderDe- A common mistake is to build data entry tails query that calculates the extended price forms on nonsensical queries and to assume (quantity shipped × price) of each order detail. that there is a mistake in the form when the • Enter the first order into your system by entering forms do not work. Clearly, if a query is non- the information directly into tables or queries. updatable, a form based on the query is also This involves creating a single Orders record going to be non-updatable. A quick check for and several OrderDetails records. You must a “new record” row in the query can save time also consult the Products and BackOrders and frustration. tables to determine the quantity of each item to ship. 4.5 Application to the assignment • Create a query to sort the Products table by Entering orders into your system will be much ProductID. less work once the input forms and triggers • Create a query that joins the OrderDetails are in place. The goal at this point is to get and Products tables. When you enter a valid you thinking about the order entry process ProductID, the information about the product and ways in which it can be automated. (such as name, quantity on hand, and so on) Home Previous 27 o f 27 Next
  • 42. Access Tutorial 5: Basic Queries using SQL 5.1 Introduction: The difference Although you normally use QBE in Access, the ubiq- between QBE and SQL uity of SQL in organizations necessitates a brief overview. Query-By-Example (QBE) and Structured Query Language (SQL) are both well-known, industry-stan- 5.2 Learning objectives dard languages for extracting information from rela- tional database systems. The advantage of QBE (as What is the difference between QBE and you saw in Tutorial 4) that it is graphical and rela- SQL? tively easy to use. The advantage of SQL is that it How do I create an SQL query? has achieved nearly universal adoption within the relational database world. 5.3 Tutorial exercises With only a few exceptions (which you probably will In this section, you will create a few simple queries in not encounter in this assignment) QBE and SQL are SQL. completely interchangeable. If you understand the • Create a new query but close the “show table” underlying concepts (projection, selection, sorting, dialog box with out adding tables. joining, and calculated fields) of one, you understand • Select View SQL to switch to the SQL editor as the underlying concepts of both. In fact, in Access shown in Figure 5.1. you can switch between QBE and SQL versions of your queries with the click of a mouse. © Michael Brydon (brydon@unixg.ubc.ca) Last update: 22-Aug-1997 Home Previous 1 of 5 Next 5. Basic Queries using SQL Tutorial exercises 2. … FROM table … — specifies the underlying FIGURE 5.1: Open a query in SQL mode table (or tables) for the query; 3. … WHERE condition1 AND/OR condition2, …, AND/OR conditionn — specifies one or more conditions that each record must satisfy in order to be included in the results set; 4. ; (semicolon) — all SQL statements must end with a semicolon (but if you forget it, Access will add it for you). 5.3.1 Basic SQL queries These can now be put together to build an SQL A typical SQL statement resembles the following: query: SELECT DeptCode, CrsNum, Title FROM • Type the following into the SQL window: Courses WHERE DeptCode = “COMM”; SELECT DeptCode, CrsNum, Title FROM There are four parts to this statement: Courses WHERE DeptCode = “COMM”; • Select View Datasheet to view the results. 1. SELECT field1, field2, …, fieldn … — specifies which fields to project (the DIS- • Select View Query Design to view the query in QBE mode, as shown in Figure 5.2. TINCTROW predicate shown in Figure 5.1 is optional and will not be discussed in this tutorial); • Save your query as qryCoursesSQL. Home Previous 2 of 5 Next
  • 43. 5. Basic Queries using SQL Tutorial exercises FIGURE 5.2: The SQL and QBE views are interchangeable. When you return to SQL mode after viewing your query in QBE mode, you will notice that Access has added some additional text. This optional text does not change the query in any way Home Previous 3 of 5 Next 5. Basic Queries using SQL Tutorial exercises 5.3.2 Complex WHERE clauses 5.3.3 Join queries You can use AND, OR, and NOT conditions in your Join queries use the same elements as a basic WHERE clauses in a straightforward manner. select query. The only difference is that the FROM • Change your query to the following to get all statement is replaced with a statement that Commerce courses with more than three credits: describes the tables to be joined and the relationship SELECT DeptCode, CrsNum, Title (i.e., foreign key) between them: FROM Courses ... FROM table1 INNER JOIN table2 ON WHERE DeptCode = “COMM” AND Credits table1.field1 = table2.field2 ... 3 Note that since both tables contain the fields Dept- Code and CrsNum, the table name.field Note that since DeptCode is a text field, its name notation must be used to remove any ambi- criterion must be a string (in this case, the lit- guity. eral string “COMM”). However, Credits is a • Create a new SQL query containing the text: numeric field and its criterion must be a num- SELECT Courses.DeptCode, ber (thus, there cannot be quotation marks Courses.CrsNum, Courses.Title, around the 3). Sections.CatalogNum FROM Courses INNER JOIN Sections ON Courses.CrsNum = Sections.CrsNum Home Previous 4 of 5 Next
  • 44. 5. Basic Queries using SQL Discussion AND Courses.DeptCode = Sections.DeptCode WHERE Courses.DeptCode=”COMM”; 5.4 Discussion Although the syntax of SQL is not particularly diffi- cult, writing long SQL queries is tedious and error- prone. For this reason, you are advised to use QBE for the assignment. In the real world, however, when you say you know something about databases, it usually implies you know the “data definition” and “data manipulation” aspects of SQL in your sleep. If you plan to pursue a career in information systems, a comprehensive SQL reference book can be a worthwhile investment. Home Previous 5 of 5 Next
  • 45. Access Tutorial 6: Form Fundamentals 6.1 Introduction: Using forms as FIGURE 6.1: The relationship between forms, the core of an application queries, and tables. Forms provide a user-oriented interface to the data in a database application. They allow you, as a forms developer, to specify in detail the appearance and behavior of the data on screen and to exert a certain amount of control over the user’s additions and mod- queries ifications to the data. Like queries, forms do not contain any data. Instead, they provide a “window” through which tables and tables queries can be viewed. The relationship between Courses Departments Employees tables, queries, and forms is shown in Figure 6.1. In this tutorial, we are going to explore the basic ele- ments of form creation using Access’ form design 6.2 Learning objectives tools. In subsequent tutorials, we will extend the Do forms contain data? functionality and ease-of-use of our basic forms with subforms (Tutorial 7), “combo box” controls How do I create a form? (Tutorial 8), and triggers (Tutorial 13). © Michael Brydon (brydon@unixg.ubc.ca) Last update: 24-Aug-1997 Home Previous 1 o f 15 Next 6. Form Fundamentals Tutorial exercises How do I make the contents of a field on a • Create a new blank form based on the Courses form read-only? table, as shown in Figure 6.2. What is an unbound text box? How do I create • The basic elements of the design screen are one? shown in Figure 6.3. Use the View menu to dis- How do I create a form using the form wizard? play the toolbox and field list if they are not already visible. What is the difference between a columnar 6.3.1.1 Adding bound text boxes (single-column) and tabular form? • Add a “bound” text box for the DeptCode field by dragging DeptCode from the field list to the form 6.3 Tutorial exercises background, as shown in Figure 6.4. • Reposition the DeptCode text box in the upper 6.3.1 Creating a form from scratch left of the form. Although Access provides an excellent wizard for creating simple forms, you will start by building a Remember that you can always use the form from scratch. This will give you a better appreci- “undo” feature to reverse mistakes. Select ation of what it is the wizard does and provide you Edit Undo from the menu or simply press with the basic knowledge needed to customize and Control-Z (this works the same in virtually all refine the wizard’s output. Windows applications). Home Previous 2 o f 15 Next
  • 46. 6. Form Fundamentals Tutorial exercises FIGURE 6.2: Create a new form to display data from the Courses table. the database window. from Select the Forms tab use theDesign at this (do not Select wizard View point) Bind the form to the Courses table. Since you can build a form on top of a table or a query, both are shown in this list (here is where a meaningful naming convention starts to pay off) Home Previous 3 o f 15 Next 6. Form Fundamentals Tutorial exercises FIGURE 6.3: The basic elements of the form design screen. To change the size of the form, drag the edges of the detail section. The field list — shows the fields The toolbox — the icons in the If the field list and toolbox in the table or query to which the toolbox are used to create graphical are not displayed, use the form is bound. items and controls on the form. View menu or toolbar icons. Home Previous 4 o f 15 Next
  • 47. 6. Form Fundamentals Tutorial exercises FIGURE 6.4: Create a bound text box for the DeptCode field. Access uses the field’s caption property as the default label for the text box. If no caption is specified, the field name (e.g., DeptCode) is used. To save time editing labels, choose your captions with this feature in mind. to thethe highlightedsection.on Drag form’s detail field To move an object and its label, drag the center of the object (the cursor becomes a white arrow). To move just the object or just the label, drag the upper left handle (the cursor becomes a pointing finger). field inthe DeptCode Select the field list. Home Previous 5 o f 15 Next 6. Form Fundamentals Tutorial exercises • Drag the remaining fields on to the form, as • Scroll down the property sheet to the Locked shown in Figure 6.5 (do not worry about whether property and set it to Yes, as shown in the fields are lined up perfectly). Figure 6.7. • Select View Form to see the resulting form. • Switch to the form view and attempt to change Alternatively, press the form view icon ( ). the contents of the DeptCode field. • Select View Form Design or press the design A stronger form of protection than locking a field is view icon ( ) to return to design mode. “disabling” it. 6.3.1.2 Using a field’s properties to protect its • Return to design mode and make the following contents changes: reset the Locked property to No; set the Every object on an Access form (e.g., text box, label, Enabled property to No. • Attempt to change the contents of the DeptCode detail section, etc.) has a set of properties that can be modified. In this section, you are going to use the field in form view, as shown in Figure 6.8. • Save the form as frmCourses. Locked and Enabled properties to control the user’s ability to change the information in a field. 6.3.1.3 Adding an unbound text box • Select the DeptCode text box and right-click to All the text boxes created in the previous section bring up its property sheet, as shown in were “bound” text boxes—that is, they were bound to Figure 6.6. a field in the underlying table or query. When you change the value in a bound text box, you are mak- Home Previous 6 o f 15 Next
  • 48. 6. Form Fundamentals Tutorial exercises FIGURE 6.5: Add the text boxes and switch to form view to see the resulting form. Text boxes are simply “windows” on to the fields in the underlying table. fieldsthe the form. Add to remaining main menu toview the form. Select View Form from the You can add more than one field to the form with one drag-and-drop operation by holding down the Control button when selecting the fields from the field list. Home Previous 7 o f 15 Next 6. Form Fundamentals Tutorial exercises FIGURE 6.6: Bring up the property sheet for the DeptCode text box. object to getoncepop-up selected Right-click the on the menu. Select Properties to get the property sheet. DeptCode text box) for Select the object (e.g., the The properties are broken down into four groups. To see all the which you wish to see the properties, select the All tab. properties. When an object has been selected, it is bordered by six dark “handles”. Some properties of the text box (such as input mask) are inherited from the field to which the text box is bound. Home Previous 8 o f 15 Next
  • 49. 6. Form Fundamentals Tutorial exercises ing the change directly to the data in the underlying FIGURE 6.7: Change the Locked property of table. DeptCode to Yes. It is possible, however, to create objects on forms that are not bound to anything. Although you will not use many “unbound” text boxes in the assignment, it is instructive to see how they work. • Create a new empty form bound to the Courses table and save it using the name frmCoursesUB. • Select the text box tool ( ) from the toolbox and create and unbound text box, as shown in Figure 6.9. 6.3.1.4 Binding an unbound text box to a field The only difference between a bound and an unbound text box is that the Control Source property of a bound text box is set to the name of a field. In this section, you are going to change the unbound the Locked property.find Use the scroll bar to text box shown in Figure 6.9 to a bound text box. Home Previous 9 o f 15 Next 6. Form Fundamentals Tutorial exercises FIGURE 6.8: Set the Enabled property of DeptCode to No and attempt to change the value in the field. Enabled to No. and Set Locked to No to see the result.view Switch to form When a form object is disabled, it cannot receive the “focus” (that is, you cannot put the cursor on it). By default, disabled form objects are greyed out. To override this feature, set the Locked property to Yes and the Enabled property to No. Home Previous 10 o f 15 Next
  • 50. 6. Form Fundamentals Tutorial exercises • Bring up the property sheet for the unbound text FIGURE 6.9: Create an unbound text box. box. Change its Control Source property from null to DeptCode, as shown in Figure 6.10. The cursortext box toolsmall texttoolbox. Select the becomes a from the box. 6.3.2 Creating a single-column form using the wizard Now that you understand the basics of creating and modifying bound text boxes, you can rely on the form wizard to create the basic layout of all your forms. • Create a new form bound to the Courses table using the form wizard, as shown in Figure 6.11. • Use the form wizard to specify the fields you want on your form and the order in which they appear, detail section to create a Click anywhere on the as shown in Figure 6.12. Select “columnar” when new unbound text box. prompted for the form type. “Columnar” forms are called “single column” forms in version 2.0. Home Previous 11 o f 15 Next 6. Form Fundamentals Tutorial exercises FIGURE 6.10: Set the Control Source property FIGURE 6.11: Create a new form using the form of an unbound text box. wizard. wizard.the form Select Courses table. the Bind the form to the Control Source property Use the pull-down list to set to DeptCode. Home Previous 12 o f 15 Next
  • 51. 6. Form Fundamentals Tutorial exercises FIGURE 6.12: Use the form wizard to determine the order of fields on your form. The order in which the fields appear in this pane is the order in which they will appear on the form. Use the and buttons to move fields back to the pane on the left. to show a field, either double- click it or press the button. To show all the fields, press the button. Home Previous 13 o f 15 Next 6. Form Fundamentals Discussion The primary advantage of the wizard is that it auto- look and behavior of the data. The three different matically creates, formats, and aligns the bound text types of forms are shown in Figure 6.13. boxes. Of course, once the wizard has created a form, you are free to modify it in any way. 6.5 Application to the assignment • Use the wizard to create columnar forms for all If you make a mistake when creating a form your master tables. Note that in some cases (e.g., you put the fields in the wrong order) it (e.g., BackOrders) you will want to base the is often easier to use the wizard and start over form on a join query rather than table in order to than to fix the problem manually. show important information such as CustName and ProductName. 6.4 Discussion 6.4.1 Columnar versus tabular versus datasheet forms Columnar forms show one record per page. Tabular forms, in contrast, show many records per page and are used primarily as subforms. There is also a a datasheet form type, but it is seldom used since it gives the developer relatively little control over the Home Previous 14 o f 15 Next
  • 52. 6. Form Fundamentals Application to the assignment FIGURE 6.13: The same information displayed as a columnar, tabular, and datasheet form. A columnar form displays one record per page. A tabular form displays more than one record per page. A datasheet form is identical to the datasheet view of a table or query. Since it gives the designer very little control over the format of the data, it is generally inappropriate for use in an end-user application. Home Previous 15 o f 15 Next
  • 53. Access Tutorial 7: Subforms 7.1 Introduction: The advantages of fact, there is no need to show DeptCode and forms within forms CrsNum in the subform). Although you will quickly learn to take a feature such A columnar/single-column main form with a tabular as form/subform synchronization for granted, it is subform is a natural way of representing information from tables with a one-to-many relationship. For worthwhile to consider what this feature does and what it would take if you had to implement the same example, the form shown in Figure 7.1 is really two forms: the main form contains information about a feature using a programming language. specific course; the subform shows all the sections associated with the course. 7.2 Learning objectives In the Courses and Sections example, the foreign What is form/subform synchronization? key (DeptCode and CrsNum) provides a link How do I create a form/subform combination? between the two forms. This connection allows Access to synchronize the forms, meaning: How do I link a form with a subform? • when you move to another course record, only 7.3 Tutorial exercises the relevant sections are shown in the subform; • when you add a new section, the foreign key in Although there are a number of different ways to cre- the Sections table is automatically filled in (in ate a subform within a main form, the recommended procedure is the following: © Michael Brydon (brydon@unixg.ubc.ca) Last update: 25-Aug-1997 Home Previous 1 o f 19 Next 7. Subforms Tutorial exercises FIGURE 7.1: A typical form/subform combination. Because a link is established between the main form and the subform, only the sections that belong with “COMM 351” are displayed in the subform. The main part of the form is columnar (one record per page) and displays information from the Courses table. The subform is a separate tabular form that displays information from the Sections table. Home Previous 2 o f 19 Next
  • 54. 7. Subforms Tutorial exercises 1. create and save both forms (one columnar, one space they occupy. A number of editing issues tabular) separately; are highlighted in Figure 7.5. 2. drag the subform on to the main form; and, • Save the form as sfrmSections and close it. 3. verify the linkage between the two forms. 7.3.3 Linking the main form and subform 7.3.1 Creating the main form In this section, you are going to return to the main • Use the wizard to create a columnar form based form and drag the saved subform from the database on the Courses table. window to an appropriate position on the main form. • Rearrange the fields so that they make efficient • Open the main form (frmCoursesMain) in use of the top part of the form, as shown in design mode. Figure 7.2. • Select Window univ0_vx: Database to open the • Save the form as frmCoursesMain. database window in the foreground. Alternatively, you can press the database window icon ( ) on 7.3.2 Creating the subform the tool bar. • Use the wizard to create the subform, as shown • Perform the steps shown in Figure 7.6 to drag the in Figure 7.3 and Figure 7.4. subform on to the main form. • Subforms created by the wizard typically require • The result of the drag-and-drop operation are some fine tuning in order to reduce the amount of shown in Figure 7.7. The advantage of the drag- and-drop method of creating a sub form is that Home Previous 3 o f 19 Next 7. Subforms Tutorial exercises FIGURE 7.2: Rearrange the text boxes on the main form to make room for the subform. columnar form based on a Use the wizard to create Courses. rearrange the text boxes to Enter form design mode and make room for the subform. Save the form under the name frmCoursesMain. To move more than one form object at a time, either hold down the Shift key when selecting or drag a box through the objects (click and drag to create a box). Home Previous 4 o f 19 Next
  • 55. 7. Subforms Tutorial exercises FIGURE 7.3: Use the wizard to create the Sections subform (part 1). DeptCodeneedCrsNum since they There is no and to include are shown in the main form. The order in which the fields are added to the right-hand pane determines their order (from left to right) on the form. Use the and buttons to get the desired ordering. new form to thewizard and bind the Select the form Sections table. Home Previous 5 o f 19 Next 7. Subforms Tutorial exercises FIGURE 7.4: Use the wizard to create the Sections subform (continued) In version 7.0, the title appears in the bar across the top of the form’s window. In version 2.0, however, the wizard creates a title in a form header. As such, you should ensure this is blank if you are using version 2.0. Select Tabular layout. form, you do not is embedded in aamain Since a subform have to provide title. Select Modify the form’s design to enter form design mode directly. Home Previous 6 o f 19 Next
  • 56. 7. Subforms Tutorial exercises FIGURE 7.5: Edit the subform to reduce the amount of space it uses. “detail band” and bringingby moving footer” band to the Reduce the vertical space the “form the fields up up by the headings and fields. used Reduce the horizontal space against the fields (to move a band, drag it using the mouse). To split the headings into two or more lines, place the cursor at the desired split location and press Shift-Enter. To move all the fields at once, drag a “selection box” so that it touches each field. Note that the box does not have to enclose objects for them to be selected. Home Previous 7 o f 19 Next 7. Subforms Tutorial exercises FIGURE 7.6: Drag the subform on to the main form. in design mode.form Open the main window so that the Position the database subform’s target destination is visible. Drag the subform on to the main form. Home Previous 8 o f 19 Next
  • 57. 7. Subforms Tutorial exercises the width of the subform control (the white win- Since both the forms created in Section 7.3.3 were dow) is automatically set to equal the width of the built on tables, Access could automatically deter- subform. mine the relationship. • Verify the link between the form and the subform If you make changes to the size of your sub- by examining the property sheet of the subform form once the subform control is created, you control, as shown in Figure 7.8. may have to resize the subform control by clicking and dragging a corner handle. The terminology “link child field” and “link master field” is identical to “foreign key” and 7.3.4 Linking forms and subforms “primary key”. The main form is the parent manually (“one” side) and the subform is the child If both the form and the subform are based on (“many” side). tables, and if relationships have been defined • View the resulting form. Notice that as you move between the tables, Access normally has no problem from course to course, the number of sections determining which fields “link” the information on the shown in the subform changes (see Figure 7.9). main form with the information in the subform. How- ever, when the forms are built on queries, Access has no relationship information to rely on. As such, you have to specify the form/subform links manually. Home Previous 9 o f 19 Next 7. Subforms Tutorial exercises FIGURE 7.7: The drag-and-drop operation creates a subform control. The white area is a “subform control”. It is essentially a window through which the subform shows. You may want to delete the label created with the subform window. To This is the name of the form to which delete the label only, select it and press the subform control is bound. Delete. The form footer is pushed down when the subform control is created. You may move the footer to create more or less area at the bottom of the form. Home Previous 10 o f 19 Next
  • 58. 7. Subforms Tutorial exercises FIGURE 7.8: Verify the link fields for the form/subform. controlthe Sections subform bring Select (the white window) and up its property sheet. determined Access has correctly Verify that the link fields. When there are more than one link fields (i.e., the foreign key is concatenated), separate the field names with a semicolon. In Access version 7.0, a builder is available to select the field names from a list. Home Previous 11 o f 19 Next 7. Subforms Tutorial exercises FIGURE 7.9: A synchronized main form/subform. 290, eightfor COMM Note that courses are For COMM 291, four sections are listed in listed in the subform. the subform. record” navigation Click the “next button on the main form to move to the next course. There are two sets of navigation buttons: one for the main form (bottom) and one for the subform (at the bottom of the subform window). Home Previous 12 o f 19 Next
  • 59. 7. Subforms Tutorial exercises 7.3.5 Non-synchronized forms itself) to make your form more attractive and easier In this section, you will delete the link fields shown in to use. Figure 7.8 in order to explore some of the problems In Figure 7.11, the basic form created in the previous associated with non-synchronized forms. sections is shown and a number of shortcomings are • Return to form design mode and delete the link identified. fields (highlight the text and press the Delete 7.3.6.1 Changing the form’s caption key). • Select the form as shown in Figure 7.12. • View the form. Note that all records in the Sec- • Change its Caption property to “Courses and tions table (not just those associated with a Sections”. particular course) are shown. • Attempt to add a new section to COMM 290 as 7.3.6.2 Eliminating unwanted scroll bars and shown in Figure 7.10. navigation buttons • Re-establish the correct link fields and save the Scroll bars and navigation buttons are also form- form. level properties. However, in this case, you need to modify the properties of the subform. 7.3.6 Aesthetic refinements • To quickly open the subform in design mode, In this section, you will modify the properties of sev- double-click the subform control when viewing eral form objects (including the properties of the form the main form in design mode (this takes some practice) Home Previous 13 o f 19 Next 7. Subforms Tutorial exercises FIGURE 7.10: A non-synchronized main form/subform. fields for the Delete the link subform control and view the resulting form. sections show37 Note that all in the subform (moving to a different course has no effect). Add a new catalog number and click the record selector Since the forms are not synchronized, the to try to save the DeptCode and CrsNum fields of the Sections new record. table are not automatically filled in by Access. Home Previous 14 o f 19 Next
  • 60. 7. Subforms Tutorial exercises FIGURE 7.11: A form/subform in need of some basic aesthetic refinements. The caption of the form shows the form’s name. A more attractive/descriptive caption is required. Since the subform control was automatically sized to fit the underlying form, a horizontal scroll bar is not necessary. The navigation buttons for the subform are too easily confused with the navigation buttons for the main form Home Previous 15 o f 19 Next 7. Subforms Application to the assignment • Bring up the property sheet for the form and scroll FIGURE 7.12: Select the entire form. down to change its Scroll Bars and Navigation Button properties, as shown in Figure 7.13. and horizontal rulerswhere in order to Click on the square meet the vertical The net result, as shown in Figure 7.14, is a more get the property sheet for the form. attractive, less cluttered form. 7.4 Application to the assignment • Create a form and subform for your Shipment and ShipmentDetails information. You will use this form to record the details of shipments from your suppliers. Note that both forms should be based on queries: • the Shipment form should be based on a “sort” query so that the most recent shipment always shows first; • the ShipmentDetails form should be based on a join query so that validation information (such as the name of the product) is shown when a product number is entered. Home Previous 16 o f 19 Next
  • 61. 7. Subforms Application to the assignment • Create a form/subform to show customer orders FIGURE 7.13: Change the scroll bars and that have already been placed (such as the one navigation buttons of the subform. you entered manually in Section 4.5). The top part of the form should contain information about propertyScroll Bar Set the to “Vertical the order plus some information about the cus- Only” and the Navigation tomer; the subform should contain information Buttons property to “No”. about what was ordered and what was actually shipped. The form you created in the preceding step is used for viewing existing orders, not for add- ing new orders. To add new orders, the form must be more complex. For example, it has to show the quantity on hand and the back ordered quantity for each item so the user can decide how many to ship. You will create a form for order entry in the latter tutorials. • Set the Allow Additions and Allow Edits proper- ties of the “order viewing” form to No. This pre- Home Previous 17 o f 19 Next 7. Subforms Application to the assignment FIGURE 7.14: A form without subform scroll bars or navigation buttons. Home Previous 18 o f 19 Next
  • 62. 7. Subforms Application to the assignment vents the user from changing the details of an order that has already been invoiced or attempt- ing to use the form for order entry. Home Previous 19 o f 19 Next
  • 63. Access Tutorial 8: Combo Box Controls 8.1 Introduction: What is a combo box? FIGURE 8.1: A combo box for filling in the Activity field. So far, the only kind of “control” you have used on your forms has been the text box. However, Access provides other controls (such as combo boxes, list boxes, check boxes, radio buttons, etc.) that can be used to improve the attractiveness and functionality of your forms. A combo box is list of values from which the user can select a single value. Not only does this save typing, it adds another means of enforcing referential integ- rity since the user can only pick values in the combo box. For example, a combo box for selecting course same. For example, in Figure 8.1, the combo box is activities from a predefined list is shown in bound to the Activity field. When an item in the Figure 8.1. combo box is selected, the string (e.g., “LEC”) is Although advanced controls such as combo boxes copied into the underlying field exactly as if you had and list boxes look and behave very differently than typed the letters L-E-C into a text box. simple text boxes, their function is ultimately the © Michael Brydon (brydon@unixg.ubc.ca) Last update: 25-Aug-1997 Home Previous 1 o f 23 Next 8. Combo Box Controls Learning objectives It is important to realize that combo boxes What is tab order? How do I change it so that have no intrinsic search capability. Combo the cursor moves in the correct order? boxes change values—they do not automati- Should I put a combo box on a key field? cally move to the record with the value you select. If you want to use a combo box for 8.3 Tutorial exercises search, you have to program the procedure • Open your frmCourses form in design mode. yourself (see Tutorial 15 for more details). • Ensure the toolbox and field list are visible (recall Figure 6.3). 8.2 Learning objectives How do I create a bound combo box? 8.3.1 Creating a bound combo box Can I create a combo box that displays values Although Access has a wizard that simplifies the pro- from a different table? cess of creating combo boxes, you will start by build- How do I show additional information in a ing a simple combo box (similar to that shown in Figure 8.1) with the wizard turned off. This will give combo box? you a better appreciation for what the wizard does How do I prevent certain information from and provide you with the skills to make refinements showing in the combo box? to wizard-created controls. Can I change the order in which the items • Delete the existing Activity text box by select- appear in a combo box? ing it and pressing the Delete key. Home Previous 2 o f 23 Next
  • 64. 8. Combo Box Controls Tutorial exercises • The wizard toggle button ( ) in the toolbox an unbound combo box, the easiest thing to allows you to turn wizard support on and off. do is to delete it and try again. Ensure the button is out (wizards are turned off). FIGURE 8.3: An unbound combo box (not what • Click on the combo box tool ( ). The cursor you want). turns into a small combo box. • With the combo box tool selected, drag the Activity field from the field list to the desired location on the form’s detail section, as shown in Figure 8.2. The process of selecting a tool from the toolbox, and then using the tool to drag a field from the field list ensures that the control you create (text box, combo box, etc.) is bound to a field in the underlying table or query. Since the control is unbound, no If you forget to drag the field in from the field field name list, you will create an unbound combo box, as shows and the shown in Figure 8.3. If you accidently create label is generic. Home Previous 3 o f 23 Next 8. Combo Box Controls Tutorial exercises FIGURE 8.2: Create a bound combo box. depressed. wizard button is not Ensure the activate the combo box tool. to Click on the combo box button Select the Activity field from the field list. have doneActivity field onname ofdetailunderlying Drag the this correctly, the to the the area. If you field should show in the combo box and the label should take the value of the field’s caption Home Previous 4 o f 23 Next
  • 65. 8. Combo Box Controls Tutorial exercises 8.3.2 Filling in the combo box properties • Change the Row Source Type property to Value In this section, you will tell Access what you want to List as shown in Figure 8.4. This tells Access to appear in the rows of new combo box. expect a list of values in its Row Source property. • Switch to form view and test the combo box. FIGURE 8.4: Set the Row Source Type property. At this point, the combo box does not show any list items because we have not specified what the list items should be. There are three methods of specify- ing what shows up in the combo box list: 1. enter a list of values into the combo box’s Row Source property; 2. tell Access to get the value from an existing table or query; 3. tell Access to use the names of fields in an exist- ing table (you will not use this approach). Although the second method is the most powerful and flexible, you will start with the first. • Bring up the property sheet for the Activity combo box. Home Previous 5 o f 23 Next 8. Combo Box Controls Tutorial exercises • Enter the following into the Row Source property: 8.3.3 A combo box based on another LAB;LEC;TUT table or query • Set the Limit To List property to Yes. An obvious limitation of the value-list method of cre- ating combo boxes is that it is impossible to change If the Limit To List property is set to No, the or update the items that appear in the list without user can ignore the choices in the combo box and simply type in a value (e.g., “SEM”). In knowing about the Row Source property. this particular situation, you want to limit the A more elegant and flexible method of populating the user to the three choices given. rows of a combo box is to have Access look up the values from an existing table or query. Although the • Switch to form view and experiment with the basic process of setting the combo box properties combo box. remains the same, it is more efficient to rely on the wizard when building this type of combo box. Notice that the combo box has some useful Before you can continue, you need a table that con- built-in features. For example, if you choose tains appropriate values for course activities. to type values rather than select them with a mouse, the combo box anticipates your • Switch to the database window and create a new table called Activities. choice based on the letters you type. Thus, to select “TUT”, you need only type “T”. • The table should consist of two fields: one called Activity and the other called Descript, as shown in Figure 8.5. Home Previous 6 o f 23 Next
  • 66. 8. Combo Box Controls Tutorial exercises • Populate the table with the same values used in FIGURE 8.5: Create a table containing course Section 8.3.2. activities. The result is a table containing all the possible course activities and a short description to explain the meaning of the three-letter codes. You can now return to creating a combo box based on these val- ues. • Delete the existing Activity combo box. • Ensure the wizard button ( ) in the toolbox is depressed (wizards are activated). • Repeat the steps for creating a bound combo box (i.e., select the combo box tool and drag the Activity field from the field list on to the detail section). As shown in Figure 8.6, this activates the combo box wizard. The wizard asks you to specify a number of things about the combo box: 1. the table (or query) from which the combo box values are going to be taken; Home Previous 7 o f 23 Next 8. Combo Box Controls Tutorial exercises FIGURE 8.6: Create a combo box using the combo box wizard. combo abox. Create bound valuesAccessa look up the Have from table or query. Home Previous 8 o f 23 Next
  • 67. 8. Combo Box Controls Tutorial exercises 2. the field (or fields) that you would like to show up source table or query change while the form is as columns in the in the combo box; open these changes are not automatically 3. the width of the field(s) in the combo box (see reflected in the combo box rows. As a conse- Figure 8.7); quence, you have to either (a) close and re- 4. the column from the combo box (if more than one open the form, or (b) requery the form. field is showing) that is inserted into the underly- Although you can automate the requery pro- ing field; and, cess, we will rely on the F9 key for the time 5. the label attached to the field (see Figure 8.8). being. When you are done, the combo box should look sim- 8.3.3.1 Showing more than one field in the ilar to that shown in Figure 8.1. However, updating or combo box changing the values in the combo box is much easier when the combo box is based on a table. One problem the combo boxes created so far is that • Add “SEM” (Seminar) to the Activities table. they are not of much use to a user who is not familiar • Return to the form, click on the Activity combo with the abbreviations “TUT”, “SEM”, and so on. In box, and press F9 to requery the combo box. this section, you will use the Descript field of the • Verify that “SEM” shows up in combo box. Activities table to make the combo box more readable, as shown in Figure 8.9. Access creates the rows in a combo box • Delete the existing combo box and start again. when the form is opened. If the values in the Home Previous 9 o f 23 Next 8. Combo Box Controls Tutorial exercises FIGURE 8.7: Fill in the combo box wizard dialog sheets. morecomboone field. show The than box can Select Activities The new only Activity for now. tables contains the values for the combo box. Use the column selector (the grey bar at the top of the column) to resize the column to the desired width. Home Previous 10 o f 23 Next
  • 68. 8. Combo Box Controls Tutorial exercises FIGURE 8.8: Fill in the combo box wizard dialog sheets (continued). to thecombo box is already bound The Activity field, this step is automatically filled in for you. Because the combo box is bound, the Activity field’s caption is provided as a default label. Home Previous 11 o f 23 Next 8. Combo Box Controls Tutorial exercises tions and want them to select a course activity value FIGURE 8.9: A combo box that shows two fields based solely on the Descript field. from the source table or query. In such a case, you could include only the Descript column in the combo box. However, this would not work because the Activity field of the Courses table expects a three-letter abbreviation. As such, the combo box would generate an error when it tried to stuff a long description into the rela- tively short field to which it is bound. In this section, you will create a combo box identical to that shown in Figure 8.9 except that the key col- umn (Activity) will be hidden from view. Despite its invisibility, however, the Activity column will • Fill in the wizard dialog sheets as in Section 8.3.3 still be bound to the Activity field of the underly- but make the changes shown in Figure 8.10. ing table and thus the combo box will work as it • Verify that your combo box resembles Figure 8.9. should. 8.3.3.2 Hiding the key field • Delete the existing combo box and start again Assume for a moment that you, as a developer, do using the combo box wizard. not want users to even see the three-letter abbrevia- Home Previous 12 o f 23 Next
  • 69. 8. Combo Box Controls Tutorial exercises FIGURE 8.10: Use the wizard to add more than one field to the combo box. Activities table into the combo box. Bring both fields from the resize the the “hide appropriately. Uncheck columns key” box and Note that Access version 2.0 does not have the “hide key” feature Select the column that provides the value of interest (in this case, Activity). Home Previous 13 o f 23 Next 8. Combo Box Controls Tutorial exercises • Include both the Activity and Descript fields in the combo box. FIGURE 8.12: A combo box with a hidden key. • Resize the Activity column as shown in Figure 8.11. Note that users of version 7.0 can simply leave the “hide key” box checked—the result is the same. • Ensure that the Input Mask property for the combo box (which is inherited from the field’s Input Mask property) is blank. • Verify that the resulting combo box resembles that shown in Figure 8.12. Combo boxes with hidden keys can be con- 8.3.3.3 Changing the order of items in the fusing. The important thing to remember is combo box that even though the description (e.g., “Lec- ture”) now shows in the combo box, what is A combo box based on a table shows the records in really stored in the underlying field is the hid- one of two ways: den key (e.g., “LEC”). 1. If the table does not have a primary key, the records are shown in their natural order (that is, in the order they were added to the database). Home Previous 14 o f 23 Next
  • 70. 8. Combo Box Controls Tutorial exercises FIGURE 8.11: Resize the columns to hide the key. the column selector andof Click on the right side drag the edge of the Activity column to the far left (i.e., make its width zero) Hiding the key is such a common operation that Access version 7.0 includes the “hide key” check box. Home Previous 15 o f 23 Next 8. Combo Box Controls Tutorial exercises 2. If the table does have a primary key, then the If the changes are quite minor (for instance, sorting records are sorted in ascending order according the records in a different order), you may prefer to to the key. modify the Row Source property. It may be, however, that you want a different order In Section 8.3.2, you set the Row Source property to within the rows of the combo box. To achieve this, equal a list of values. When the combo box is based you can do one of two thing: on values from a table or a query, however, the Row 1. Create a stand-alone query (in which the sort Source is an SQL statement (recall Tutorial 5) rather order is specified) and use this query as the than a list of values. You can either edit the SQL source for the combo box. statement directly or invoke the QBE editor. 2. Modify the “ad hoc” query within the Row Source In this section, you will order the items in you combo property of the combo box. box according to the length of the Descript field If you intend to make several major changes to the (this is done merely for illustrative purposes). basic information in the underlying table (e.g., joins, • Bring up the property sheet for the Activity calculated fields), it is usually better to create a combo box. stand-alone query. In this way, the same query can • Put the cursor in the Row Source property. As be used by many combo boxes. shown in Figure 8.13, a builder button ( ) appears. • Press the builder button to enter the “SQL builder” (i.e., the QBE editor). Home Previous 16 o f 23 Next
  • 71. 8. Combo Box Controls Tutorial exercises (Len() is a built-in function that returns the FIGURE 8.13: Invoke the builder for the Row length of a string of characters). Source property. • Sort on DescLength in descending order. • Switch to datasheet view to ensure the query is working as it should. • Ensure the Show box for the field is unchecked, as shown in Figure 8.14. • Instead of saving the query in the normal way, simply close the QBE box using the close button ( ). If you save the query, it will be added to your collection of saved queries (the ones that are bring up the QBEbutton to Click the builder editor. displayed in the database window). However, if you simply close the QBE window, the Row Alternatively, you can edit the SQL statement directly. Source property will be updated and no new database object will be created. • Create a calculated field called DescLength using the following expression: DescLength: Len([Descript]) Home Previous 17 o f 23 Next 8. Combo Box Controls Tutorial exercises 8.3.4 Changing a form’s tab order FIGURE 8.14: Use the QBE editor to modify the A form’s tab order determines the order in which the Row Source property. objects on a form are visited when the Tab or Enter (or Return) keys are pressed. Access sets the tab order based on the order in which objects are added to the form. As a result, when you delete a text box and replace it with a combo box or some other con- calleda DescLength. Add calculated field trol, the new control becomes the last item in the tab order regardless of its position on the form. To illustrate the problem, you are going to create a combo box for the DeptCode field. • Delete the DeptCode text box and replace it with a combo box based on the Departments table. • Switch to form view. Notice that the focus starts off in the CrsNum field instead of the DeptCode field. calculated field. Sort on the Uncheck the Show box • Press tab to move from field to field. Notice that after DeptCode is left, the focus returns to the CrsNum field of the next record. Home Previous 18 o f 23 Next
  • 72. 8. Combo Box Controls Discussion • To fix the problem, return to form design mode For example, it never makes sense to put a combo and select View Tab Order from the main box on a non-concatenated primary key. To illustrate menu. this, consider the Departments form shown in Figure 8.16. On this form, the DeptCode text box In Access version 2.0, the menu structure is slightly different. As such, you must select has been replaced with a combo box that draws its values from the Departments table. Edit Tab Order. FIGURE 8.16: A combo box bound to a key field. • Perform the steps in Figure 8.15 to move Dept- Code to the top of the tab order. 8.4 Discussion 8.4.1 Why you should never use a combo box for a non-concatenated key. A mistake often made once new users learn how to This combo box appears to work. However, if you make combo boxes is to put a combo box on every- think about it, it makes no sense: The form in thing. There are certain situations, however, in which Figure 8.16 is a window on the Departments table. the use of a combo box is simply incorrect. As such, when the DeptCode combo box is used, Home Previous 19 o f 23 Next 8. Combo Box Controls Discussion FIGURE 8.15: Adjust the tab order of fields on a form. selector torecord Drag the the selector of the field Click on the record desired position in you wish to move. the list. For forms in which the fields are arranged in a single column from top to bottom (such as this one), you can press Auto Order to order them automatically. Home Previous 20 o f 23 Next
  • 73. 8. Combo Box Controls Discussion one of two things can occur depending on whether a combo box is identical to typing “CPSC” over new record is being created or an existing record is whatever is currently in the DeptCode field. This being edited: causes all sorts of problems; the most obvious of 1. A new record is being created — If a new these is that by overwriting an existing value of record is being created (i.e., a new department is DeptCode, a “duplicate value in index, primary being added to the information system), a unique key, or relationship” error is generated (there is value of DeptCode must be created to distin- already a department with “CPSC” as its Dept- guish the new department from the existing Code). departments. However, the combo box only Note that a combo box may make sense when the shows DeptCode values of existing depart- key is concatenated. An example of this is the ments. If the Limit To List property is set to Yes, DeptCode combo box you created in Section 8.3.4. then the combo box prevents the user from enter- ing a valid DeptCode value. 8.4.2 Controls and widgets 2. An existing record is being edited — It is Predefined controls are becoming increasingly popu- important to remember that a combo box has no lar in software development. Although Microsoft intrinsic search capability. As such, selecting includes several predefined controls with Access “CPSC” in the DeptCode combo box does not (such as combo boxes, check boxes, radio buttons, result in a jump to the record with “CPSC” as its etc.), a large number of more compex or specialized key value. Rather, selecting “CPSC” from the controls are available from Microsoft and other ven- Home Previous 21 o f 23 Next 8. Combo Box Controls Application to the assignment dors. In addition, you can write your own custom 8.5 Application to the assignment controls using a language like Visual C++ or Visual There are a number of forms in your assignment that Basic and use them in many different forms and can be greatly enhanced by combo boxes. applications. • Create a combo box on your order form to allow An example of a more complex control is the calen- the user to select customers by name rather than dar control shown in Figure 8.17. A calendar control CustID. Since your CustID value is a counter, it can be added to a form to make the entry of dates has no significance beyond its use as a primary easier for the user. Microsoft calls such components key. Generally, such keys should be hidden from “ActiveX controls” (formerly known as “OLE con- view. trols”). Non-microsoft vendors provide similar com- • Create a combo box in your order details subform ponents but use different names, such as “widgets”. to allow the user to select products. Since the There are two main advantages of using controls. ProductID values are used by both you and First, they cut down on the time it takes to develop your customers, they have some significance an application since the controls are predefined and beyond the information system. As such, Pro- pre-tested. Second, they are standardized so that ductID should be visible in all combo boxes. In users encounter the same basic behavior in all appli- addition, the items in the product list should be cations. sorted by ProductID. This makes it easier to select a product by typing the first few numbers. • Create combo boxes on other forms as required. Home Previous 22 o f 23 Next
  • 74. 8. Combo Box Controls Application to the assignment FIGURE 8.17: A calendar control on a form. The calendar control can be bound to date/time fields, thereby making it easier for users to enter dates. Like other objects in Access, controls have properties and events that determine the appearance and behavior of the control. Home Previous 23 o f 23 Next
  • 75. Access Tutorial 9: Advanced Forms 9.1 Introduction: Using calculated best course of action. However, as you will see in the controls on forms context of subtotals, this is not always possible. It is often useful to show summary information from 9.2 Learning objectives the subform on the main form. The classic example of this is showing the subtotal from a list of order How do I create a calculated text box? details on the main order form. What is the expression builder? When is it In this tutorial, you are going to explore one means used? of implementing this feature using calculated con- Where can put an intermediate result of a trols. A calculated control is an unbound control for calculation on a form so that it does not which the Control Source property is set to an show? expression that Access can evaluate. Clearly, calculated controls have a great deal in com- 9.3 Tutorial exercises mon with the calculated query fields you created in Section 4.3.3. Although there are no hard-and-fast 9.3.1 Creating calculated controls on rules that dictate when to use a one over the other, forms pushing your calculations to the lowest level (i.e., In this section, you are going to create a simple cal- performing calculations in the query) is usually the culated text box to translate the Credits field into a dichotomous text variable [full year, © Michael Brydon (brydon@unixg.ubc.ca) Last update: 24-Aug-1997 Home Previous 1 o f 11 Next 9. Advanced Forms Tutorial exercises half year]. Recall that you have already imple- • Test your form. Note that you are prevented from mented this feature in Section 4.3.3.2 using a calcu- editing the calculated field. If, however, you lated query field. change the value of Credits, the value of txt- • Perform the steps shown in Figure 9.1 to create CourseLength changes accordingly when you an unbound text box on your fmrCoursesMain leave the Credits field. form. • Set the Control Source property of the text box 9.3.2 Showing a total on the main form using the syntax: In this section, you will create a calculated text box = expression that displays the number of sections associated In this case, the expression should be an “imme- with each course. The primary motivation for this diate if” function (see Section 4.3.3.2). exercise is to illustrate some of the limitations of cal- culated controls (as they are implemented in Access) By default, Access interprets text in the Con- and to provide an opportunity to explore an interest- trol Source property field as the name of a ing work-around. variable (i.e., the name of a field or another • Create a text box call txtNumSections on the control). As such, you must remember to main form as shown in Figure 9.2. include the equals sign when setting this property. The logical next step is to set the Control Source of the field to an expression that includes the Count() function. However, Access has a limitation in this Home Previous 2 o f 11 Next
  • 76. 9. Advanced Forms Tutorial exercises FIGURE 9.1: Create an unbound text box on your main form. Credits text boxbytodragging the Make some room the left. tool from the box Select the text toolbox and click on an appropriate space in the detail area. Adjust the tab order of the fields as necessary. (e.g.,the label and give the textThe txt prefix is name Edit txtCourseLength). box a meaningful used here to indicate an unbound text box. Home Previous 3 o f 11 Next 9. Advanced Forms Tutorial exercises FIGURE 9.2: Create an unbound text box to show the number of sections associated with each course. Sincean unbound textboundcalled txtNumSections. Add it is currently box to nothing, it is blank. What you want is a means of counting the records in the subform and } displaying the count in the new text box. Home Previous 4 o f 11 Next
  • 77. 9. Advanced Forms Tutorial exercises regard: you cannot use an aggregate function 9.3.2.1 Calculating the aggregate function on (Sum(), Avg(), Count(), etc.) on a main form that the subform refers to a field in a subform. As a consequence, you • Create an unbound text box on the subform as have to break the calculation into two steps: shown in Figure 9.3. 1. use the aggregate function to create a calculated • Save the subform but do not close it. text box on the subform (i.e., a “dummy” field to • Return to the main form and set the Control hold an intermediate result); Source of txtNumSections to equal the value 2. create a calculated control on the main form that of txtNumSectionsOnSub. Since the naming references the dummy text box created in the first conventions for objects on forms and subforms step. can be tricky, use the expression builder (as shown in Figure 9.4) to build the name for you. It is important that you realize that this proce- The expression builder organizes all the elements of dure does not involve any immutable, funda- the database environment into a hierarchical struc- mental information systems knowledge. ture. You build an expression by “drilling down” to the Rather, it is merely an example of the type of element you need and double-clicking to copy its work-around (hack, kludge, etc.) that is rou- name into the text area. tinely used when using a tool like Access to create a custom application. The expression builder takes some practice. One problem is that it is easy to double-click Home Previous 5 o f 11 Next 9. Advanced Forms Tutorial exercises FIGURE 9.3: Perform the count on the subform. txtNumSectionsOnSub and place it in the form header Create a calculate control called (do not worry about its location, you will move it later). propertyControl Source Set the to =Count([Section]). Note that any field can be used as the argument for the Count() function. Home Previous 6 o f 11 Next
  • 78. 9. Advanced Forms Tutorial exercises FIGURE 9.4: Use the builder to drill down to the calculated control on the subform. Controlthe builder from the drill Invoke Source property and down to the calculated control you just created on the subform. Note that when the main form and the subform are both open, the subform appears twice in the builder: once as a “stand-alone” form (under “Loaded Forms”) and once as a component of the main form (press the + sign on the frmCoursesMain folder). You want to use the latter (you will never access the subform in stand- alone mode). Home Previous 7 o f 11 Next 9. Advanced Forms Tutorial exercises on the wrong thing. Another problem is that • Test the form. The value of txtNumSections Access attempts to guide you by inserting and txtNumSectionsOnSub should be identi- «Expr» place-holders all over the place. The cal, as shown in Figure 9.5. solution to both problems is to click on the text FIGURE 9.5: The number of sections on the main window and make liberal use of the Delete form. key. The point made about “stand-alone” and “component” subforms in Figure 9.4 is extremely important. The reason you use the sfrm prefix is so you know that the form is designed to be a component of another form. If you select the stand-alone version the form in the builder, the name created by the builder The “dummy” text box is visible in will be incorrect and an error will result. the subform. Although you will eventually hide it, it is useful to • Close the subform (in version 7.0 and 8.0, the display it until you know both steps main form and subform cannot be open at the of the calculation are working properly. same time). Home Previous 8 o f 11 Next
  • 79. 9. Advanced Forms Discussion 9.3.2.2 Hiding the text box on the subform • Drag (or cut and paste) txtNumSectionsOn- The obvious problem in Figure 9.5 is that the dummy Sub from the form header to the page header, as text box shows on the subform. There are at least shown in Figure 9.6. two ways to get around this: one is to set the Visible • Test the result. property of the text box to No; a slightly more elegant approach is to use the page header or page footer 9.4 Discussion to hide the text box. In Section 4.3.3.2 and Section 9.3.1, you accom- The page header and footer are areas on the form plished the same thing (showing half year or that only show when the form is printed. Since you full year) using different techniques. The advan- will never print a form (reports are used for printed tage of implementing this as a calculated query field material), these areas can be used to hide intermedi- is that you can use this field repeatedly in other ate results, etc. forms. On the other hand, if you do the transforma- • In design mode, select View Page Header/ tion on the form, you have to repeat the calculation Footer from the menu. on every form that requires the calculated field. In the case of the aggregate function, the situation is In version 2.0, the menu structure is slightly different. As such, you must select Format slightly different. Although you can use the totals feature of QBE (see on-line help) to count the num- Page Header/Footer. ber of sections for a particular course within a query, the resulting recordset is non-updatable (and hence Home Previous 9 o f 11 Next 9. Advanced Forms Discussion FIGURE 9.6: Hide the intermediate result in the page header. menu (Format Page Header/Footer fromversion Select View Page Header/Footer in the the field you and paste) Drag (or cut want to hide 2.0) to show the page header and footer. into the page header. Home Previous 10 o f 11 Next
  • 80. 9. Advanced Forms Application to the assignment not much use for editing course names, etc.). As a result, you are forced to do the calculation on the form rather than in the query. 9.5 Application to the assignment To show the subtotal, tax, and grand total on your order form, you use the same techniques illustrated here. The only difference is that you use the Sum() function instead of the Count() function to get the subtotal for the order. • Create a dummy field on your OrderDetails subform to calculate the subtotal for the order. • Calculate the tax (G.S.T. only for wholesale) and grand total on the main form (traditionally, this information is located near the bottom of the form—but not in the form footer). Home Previous 11 o f 11 Next
  • 81. Access Tutorial 10: Parameter Queries The last few tutorials have been primarily concerned result is that parameters can be used to create with interface issues. In the remaining tutorials, the extremely flexible queries. focus shifts to transaction processing. When the concepts from this tutorial are combined with action queries (Tutorial 11) and triggers 10.1 Introduction: Dynamic queries (Tutorial 13), you will have a the skills required to using parameters create a simple transaction processing system with- A parameter query is a query in which the criteria out writing a line of programming code. for selecting records are determined when the query is executed rather than when the query is designed. 10.2 Learning objectives For example, recall the select query shown in What is a parameter query? How do I create Figure 4.6. In this query, the results set is limited to one? records that satisfy the criterion DeptCode = How do I prompt the user to enter parameter “COMM”. If you wanted a different set of results, you values? would have to edit the query (e.g., change the crite- rion to “CPSC”) and rerun the query. How do I create a query whose results depend on a value on a form? However, if a variable (parameter) is used for the cri- terion, Access will prompt the user for the value of the variable before executing the query. The net © Michael Brydon (brydon@unixg.ubc.ca) Last update: 24-Aug-1997 Home Previous 1 o f 11 Next 10. Parameter Queries Tutorial exercises 10.3 Tutorial exercises attempts to bind the variable to some value. To do this, it performs the following tests: 10.3.1 Simple parameter queries 1. First, Access checks whether the variable is the • If you do not already have a qryCourses query name of a field or a calculated field in the query. If like the one shown in Figure 4.6, create one now it is, the variable is bound to the current value of and save it under the name pqryCourses. the field. For example, if the parameter is named • Replace the literal string in the criteria row [DeptCode], Access replaces it with the current (“COMM”) with a variable ([X]). value of the DeptCode field. Since X is not the name of a field or a calculated field in this particu- By default, Access expects criteria to be literal lar query, this test fails. strings of text. As a result, it automatically 2. Second, Access attempts to resolve the parame- adds quotation marks to text entered in the ter as a reference to something within the current criteria row. To get around this, place your environment (e.g., the value on an open form). parameter names inside of square brackets. Since there is nothing called X in the current envi- ronment, this test fails. • Execute the query as shown in Figure 10.1. 3. As a last resort, Access asks the user for the When Access encounters a variable (i.e., something value of the parameter via the “Enter Parameter that is not a literal string) during execution, it Value” dialog box. Home Previous 2 o f 11 Next
  • 82. 10. Parameter Queries Tutorial exercises FIGURE 10.1: Convert a select query into a parameter query. (herethe queryisand supply the value of value Run Access asking for a parameter X). (“COMM”) with a parameter (X) Replace the literal criterion Home Previous 3 o f 11 Next 10. Parameter Queries Tutorial exercises Note that the spelling mistakes discussed in may be useful to be able to generate a list of courses Section 4.3.4 are processed by Access as offered by the department currently being viewed. parameters. Although you could use a creatively-named parame- ter to invoke the “Enter Parameter Value” dialog, this 10.3.2 Using parameters to generate requires the user to type in the value of DeptCode. prompts A more elegant approach is to have Access pull the Since the name of the parameter can be anything value of a parameter directly from the open form. (as long as it is enclosed in square brackets), you This exploits the second step in the operation of a can exploit this feature to create quick and easy dia- parameter query (Access will attempt to resolve a log boxes. parameter with the value of an object within the cur- • Change the name of your DeptCode parameter rent environment). The basic idea is shown in from [X] to [Courses for which depart- Figure 10.3. ment?]. The key to making this work is to provide a parame- • Run the query, as shown in Figure 10.2. ter name that correctly references the form object in which you are interested. In order to avoid having to 10.3.3 Values on forms as parameters remember the complex naming syntax for objects on A common requirement is to use the value on a form forms, you can invoke the expression builder to to influence the outcome of a query. For instance, if select the correct name from the hierarchy of data- the user is viewing information about departments, it base objects. Home Previous 4 o f 11 Next
  • 83. 10. Parameter Queries Tutorial exercises FIGURE 10.2: Select a parameter name that generates a useful prompt. the value of the for When Access asks parameter, it uses the parameter’s name. Only records that satisfy the criteria are included in the results set. for which department?]. Name the parameter [Courses Home Previous 5 o f 11 Next 10. Parameter Queries Tutorial exercises FIGURE 10.3: Using the value on an open form as a parameter in a query. The current value in the DeptCode field on the form is used as a parameter in the query. Home Previous 6 o f 11 Next
  • 84. 10. Parameter Queries Application to the assignment • Create a very simple form based on the Although the naming syntax of objects in Departments table and save it as frmDepart- Access is tricky, it is not impossible to com- ments. prehend. For example, the name • Leave the form open (in form view or design Forms![frmDepartments]![DeptCode] mode, it does not matter). consists of the following elements: Forms • Open pqryCourses in design mode, place the refers to a collection of Form objects; [frm- cursor in the criteria row of the DeptCode field, Departments] is a specific instance of a and invoke the expression builder as shown in Form object in the Forms collection; [Dept- Figure 10.4. Code] is a Control belonging to the form. See • Perform the steps shown in Figure 10.5 to create Tutorial 14 for more information on the hierar- a parameter that references the DeptCode field chy of objects used by Access. on the frmDepartments form. • Run the query. The results set should correspond 10.4 Application to the assignment to the department showing in the frmDepart- You will use parameter queries as the basis for sev- ments form. eral action queries (see Tutorial 11) that process • Move to a new record on the form. Notice that transactions against master tables. For now, simply you have to requery the form (Shift-F9) in order create the parameter queries that take their criteria for the new parameter value to be used (see values from forms you have already created. Figure 10.6). Home Previous 7 o f 11 Next 10. Parameter Queries Application to the assignment FIGURE 10.4: Invoke the builder to build a parameter. Criteria row of the the Place the cursor in DeptCode field and right-click to bring up the pop-up menu. Departmentsform basedleavetheopen Create a simple table and on it in the background. Select Build to invoke the builder. Home Previous 8 o f 11 Next
  • 85. 10. Parameter Queries Application to the assignment FIGURE 10.5: Use the builder to select the name of the object you want to use as a parameter. aDouble-click DeptCode toarea, delete the text,area.tryyou make mistake, move to the text move it to the text and If again. the forms in yourget a list of all Select Forms to database. form isthe frmDepartments Since open, click on Loaded Forms and select the form. Press OK when done. Move to the middle pane and select Field List to get a list of the The text will be copied fields on the form in the pane on into the the far right. criteria row. Home Previous 9 o f 11 Next 10. Parameter Queries Application to the assignment FIGURE 10.6: Requery the results set to reflect changes on the form. form. Notice that the query is not Move to a new record on the automatically updated. parameter valueto(MATH in this case) Press Shift-F9 requery. The new is used to select records. Home Previous 10 o f 11 Next
  • 86. 10. Parameter Queries Application to the assignment • Create a parameter query to show all the order • It shows the change (positive or negative but not details for a particular order. zero) in backorders for each item in a particular • Create a second parameter query to show all the order. shipment details for a particular shipment. • The query consist of three fields: OrderID, Pro- Each order may result in a number of changes being ductID and a calculated field Qty (i.e., the made to the BackOrders table. For some items in change in the back order for a particular product). the order, more product is ordered than is actually • The name of the parameter is in this query is sim- shipped (i.e., a backorder is created). For other ply[pOrderID]. Since the value of this parame- items, more product is shipped than is ordered (i.e., ter will be set by the Visual Basic shortcut before a backorder is filled). the query is run, there is no need to set it to a value on a form. In Tutorial 15, you are supplied with a “shortcut” Visual Basic procedure that makes the changes to Since the query is accessed by a program, the BackOrders table for you. However, the short- the name of the query and all the fields must cut procedure requires a query that lists the changes be exactly as described above. In other that must be made to the BackOrders table for a words, you are given a precise specification particular order. The requirements for this query are for a database object that fills a role in a pro- the following: cess designed and implemented by someone • The name of the query is else. You will not understand how the query pqryItemsToBackOrder fits in until Tutorial 15. Home Previous 11 o f 11 Next
  • 87. Access Tutorial 11: Action Queries 11.1 Introduction: Queries that 2. Append — similar to a make-table query, except change data that the results set of the query is appended to an existing table; 11.1.1 What is an action query? 3. Update — allows the values of one or more fields in the result set to be modified; and, All of the queries that you have created to this point 4. Delete — deletes all the records in the results set have been variations of “select” queries. Select que- from the underlying table. ries are used to display data but do not actually change the data in any way. Since the operation of all four types of action queries is similar, we will focus on update queries in this tuto- Action queries, in contrast, are used to change the rial. data in existing tables or make new tables based on the query's results set. The primary advantage of 11.1.2 Why use action queries? action queries is that they allow you to modify a large To motivate the examples in the first part of this tuto- number of records without having to write Visual rial, we are going to assume that the number of cred- Basic programs. its allocated to courses in certain departments need Access provides four different types of action que- to be changed. For example, assume that you need ries: to increase the number of credits for courses in the 1. Make table — creates a new table based on the Commerce department by 1.5 times their current val- results set of the query; © Michael Brydon (brydon@unixg.ubc.ca) Last update: 25-Aug-1997 Home Previous 1 o f 16 Next 11. Action Queries Learning objectives ues. There are at least four different ways of accom- 3. Write a Visual Basic program to automate Step 2. plishing this task: This is a good approach; however, it clearly 1. Create a calculated field called NewCredits that requires the ability to write Visual Basic pro- multiplies the value of Credits by 1.5 — The grams. query containing the calculated field can be used 4. Create an update query that (a) selects only in place of the Courses table whenever credit those courses that require modification and (b) information is required. Of course, the values replaces the value of Credits with Credits * stored in the Courses table are still the old val- 1.5. — This approach is computationally efficient ues. Although there might be some advantages and allows you to work with the QBE editor rather to keeping the old values, it may cause confusion than a programming language. about which values to use. In addition, the use of a calculated field creates a computational load 11.2 Learning objectives that becomes larger as the number of courses What is an action query? Why would I want to increases. use one? 2. Go through the Courses table record by record and manually change all the values — This How do I make a backup copy of one of my tables? approach is tedious and error prone. Further- more, it is simply impractical if the number of How to I undo (rollback) an action query once courses is large. I have executed it? Home Previous 2 o f 16 Next
  • 88. 11. Action Queries Tutorial exercises How do I update only certain records in a • While still in query design mode, select Query table? Make Table from the main menu and provide a How do I create a button on a form? How do I name for the target table (e.g., CoursesBackup) make an action query execute when the as shown in Figure 11.1. button is pressed? • Select Query Run from the main menu to exe- cute the action query, as shown in Figure 11.2. 11.3 Tutorial exercises Action queries do not execute until you explic- itly run them. Switching to datasheet mode 11.3.1 Using a make-table query to create only provides a preview of the results set. a backup Since action queries permanently modify the data in • Save the query. If you switch to the database win- tables, it is a good idea to create a backup of the dow, you will notice that the new make-table table in question before running the query. An easy query has a different icon than the select queries. way to do this is to use a make-table query. • Create a select query based on the Courses 11.3.2 Using an update query to rollback table and save it as qryCoursesBackup. changes • Project the asterisk (*) into the query definition so Having a backup table is not much use without a that all the fields are included in the results set. means of using it to restore the data in your original table. In this section, you will use an update query to Home Previous 3 o f 16 Next 11. Action Queries Tutorial exercises FIGURE 11.1: Use a make-table query to back up and existing table aTransform the Select query into Make Table query Provide a name for the new (target) table. the query definition.into Project all fields (*) Home Previous 4 o f 16 Next
  • 89. 11. Action Queries Tutorial exercises FIGURE 11.2: Run the make-table query. You can switch to datasheet mode to view the results set. Note that this does not actually execute the query. Query Run. query, you must select To execute the Alternatively, you can press the “run” (!) icon on the toolbar. The warning box reminds you that you are about to make permanent changes to the data in the database. Home Previous 5 o f 16 Next 11. Action Queries Tutorial exercises replace some of the values in your Courses table FIGURE 11.3: Create an ad hoc relationship with values from your CoursesBackup table. between the table and its backup. • Create a new query based on the Courses and CoursesBackup tables. • Since no relationship exists between these tables, create an ad hoc relationship within the query as shown in Figure 11.3. • Select Query Update from the main menu. Note that this results in the addition of an Update To row in the query definition grid. • Project Credits into the query definition and fill in the Update To row as shown in Figure 11.4. • Save the query as qryRollbackCredits. Now is a good point to stop and interpret what you counterparts in thethe key on to their Drag the fields in backup table. have done so far: 1. By creating a relationship between the Courses You cannot drag two fields at once or table and its backup, you are joining together the enforce referential integrity in a QBE relationship like you can in the main records from both tables that satisfy the condi- relationship editor. Home Previous 6 o f 16 Next
  • 90. 11. Action Queries Tutorial exercises tion: FIGURE 11.4: Fill in the Update To field. Courses.DeptCode = CoursesBackup.DeptCode AND the query an update query. make Select Query Update to Courses.CrsNum = CoursesBackup.CrsNum. 2. By projecting Courses.Credits into the query, you are making it the target for the update. In other words, the values in Courses.Credits are going to be modified by the update action. 3. By setting the Update To field to Courses- Backup.Credits, you are telling Access to replace the contents of Courses.Credits with the contents of CoursesBackup.Credits. Whenever this query is run, it will replace whatever is in the Credits field of all the records in the Courses table with values from the backup. You will use this query to “rollback” updates made later on. syntax totable name.field name Use the disambiguate the field name. Home Previous 7 o f 16 Next 11. Action Queries Tutorial exercises 11.3.3 Using an update query to make FIGURE 11.5: Create an update query that selective changes updates a subset of the records. Now that you have an infrastructure for undoing any errors, you can continue with the task of updating credits for the Commerce department. • Create an update query based on the Courses table and save it as qryUpdateCredits. To fieldUpdate Set the to replace Credits with • Set the Update To field to [Courses]*1.5. Credits × 1.5 Note that if you do not include the square brack- ets, Access will interpret Courses as a literal string rather than a field name. Since this particular query only contains one table, the table name.field name syntax is not required for specifying the Update To expression. • Since you only want to apply the change to Com- the update. Note limitDeptCodeofis Add a criteria to that the scope merce courses, enter a criterion for the Dept- not changed in any way by this query. Code field, as shown in Figure 11.5. Home Previous 8 o f 16 Next
  • 91. 11. Action Queries Tutorial exercises • Run the query and verify that update has been 11.3.5 Attaching action queries to performed successfully. buttons As a designer, you should not expect your users to 11.3.4 Rolling back the changes understand your query naming convention, rum- While testing the qryUpdateCredits query, your mage through the queries listed in the database win- exuberance may have led you to execute it more dow, and execute the queries that need to be than once. To return the Courses table to its state executed. As such, it is often useful to create buttons before any updates, all you need to do it run your on forms and “attach” the action queries to the but- rollback query. tons. When the button is pressed, the query is exe- • Run qryRollback credits by double-clicking its cuted. icon in the database window. Although we have not yet discussed buttons (or Once an action query is created, it has more events in general), the button wizard makes the cre- in common with subroutines written in Visual ation of this type of form object straightforward. Basic than standard select queries. As such, it • Modify qryUpdateCredits so that it updates is best to think of action queries in terms of only those departments matching the DeptCode procedures to be executed rather than virtual value in the frmDepartments table (see tables or views. Double-clicking an action Figure 11.6). query executes it. • Save the resulting action parameter query as pqryUpdateCredits and close it. Home Previous 9 o f 16 Next 11. Action Queries Tutorial exercises FIGURE 11.6: Create an action parameter query to update Credits for a particular department. specifies theoperation The update action to update to those records scope of the The criterion limits the matching perform on the records. the current parameter value Home Previous 10 o f 16 Next
  • 92. 11. Action Queries Application to the assignment • Switch to the design view of frmDepartments • Create backup copies of your Products and and add a button as shown in Figure 11.7. BackOrders tables using make-tables queries. • Attach the pqryUpdateCredits query to the Save these queries but note that they only need button as shown in Figure 11.8. to be run once. • Provide a caption and a name for the button as • Create a rollback query that allows you to return shown in Figure 11.9. your Products table to its original state. • Switch to form view. Press the button to run the Rolling back the BackOrders table is more complex query (alternatively, use the shortcut key by than rolling back the Products table. This is pressing Alt-U) as shown in Figure 11.10. because we are making the assumption that no products are ever added or deleted to the system. As 11.4 Application to the assignment such, all the information needed for the rollback is in the backup copy of Products. 11.4.1 Rolling back your master tables In contrast, records are added to the BackOrders As you begin to implement the transaction process- table on a regular basis. As a result, the Back- ing component of your system, it is worthwhile to Orders table and its backup may contain a different have a means of returning your master tables to their number of records. If so, the match-and-replace pro- original state (i.e., their state when you started devel- cess used for rolling back Products is inappropri- oping the system). ate. Home Previous 11 o f 16 Next 11. Action Queries Application to the assignment FIGURE 11.7: Add a button to the form using the button wizard. thethere is insufficient space fortoa the rightdrag If border of the detail section button, wizard button in the Ensure that the toolbox is depressed (wizards are activated). Select the “command button” tool and click on an appropriate location on the form detail section. The button wizard should appear Home Previous 12 o f 16 Next
  • 93. 11. Action Queries Application to the assignment FIGURE 11.8: Use the wizard to attach an action query to the button. perform can bedifferentto Buttons many created actions in Access. The button wizard organizes these actions into categories. Select Miscellaneous Run Query. queries (including non-action queries). The wizard lists all the available Select pqryUpdateCredits. Home Previous 13 o f 16 Next 11. Action Queries Application to the assignment FIGURE 11.9: Use the wizard to attach a query to a button (continued) You can show either a picture (icon) or a caption on the button. Enter a suitable caption. Including an ampersand () in the caption creates a shortcut key from the letter immediately following the ampersand. Shortcut keys can be invoked using the Alt-letter combination (the letter is underlined). In this case, Alt-U moves the focus directly to the button. button. The cmd prefixname for the Provide a meaningful indicates a command button. Home Previous 14 o f 16 Next
  • 94. 11. Action Queries Application to the assignment FIGURE 11.10: Execute the action query by pressing the button. (or press Alt-U to use the shortcut). query Press the button to execute the action Home Previous 15 o f 16 Next 11. Action Queries Application to the assignment The easiest way to rollback the BackOrders table is ries. These queries will allow you to perform to delete all the records it contains and use an reasonably complex transaction processing opera- append query to replace the records from the tions on your master tables. backup. • Create an update query to add all products in a • Open your BackOrders table in datasheet mode shipment to inventory. and select Edit Select All Records from the menu (alternatively, press Control-A) Note that this query should only process ship- • Press the Delete key. ment details for the current shipment (i.e., it • Create an append query that adds the records should be based on a parameter query similar in the backup table to the BackOrders table. to the one you created in Section 10.4). Once you learn the Access macro language or • Create a button on the shipments form to perform Visual Basic for Applications, you will be able to write this update. a small procedure to execute these steps for you. • Create an update query to subtract items from For the assignment, however, this “manual rollback” inventory when you process an order from your is sufficient. customers. Do not attach this query to a button at this point. 11.4.2 Processing transactions You are now in a position to combine parameter que- This query should only process order details ries and action queries into parameter-action que- from the current order. Home Previous 16 o f 16 Next
  • 95. Access Tutorial 12: An Introduction to Visual Basic 12.1 Introduction: Learning the simple programs we are writing here, these basics of programming terms are interchangeable. Programming can be an enormously complex and 12.1.1 Interacting with the interpreter difficult activity. Or it can be quite straightforward. In Access provides two ways of interacting with the either case, the basic programming concepts remain VBA language. The most useful of these is through the same. This tutorial is an introduction to a handful saved modules that contain VBA procedures. These of programming constructs that apply to any “third procedures (subroutines and functions) can be run to generation” language, not only Visual Basic for do interesting things like process transactions Applications (VBA). against master tables, provide sophisticated error Strictly speaking, the language that is checking, and so on. included with Access is not Visual Basic—it is The second way to interact with VBA is directly a subset of the full, stand-alone Visual Basic through the interpreter. Interpreted languages are language (which Microsoft sells separately). easier to experiment with since you can invoke the In Access version 2.0, the subset is called interpreter at any time, type in a command, and “Access Basic”. In version 7.0, it is slightly watch it execute. In the first part of this tutorial, you enlarged subset called “Visual Basic for Appli- are going to invoke Access’ VBA interpreter and exe- cations” (VBA). However, in the context of the cute some very simple statements. © Michael Brydon (brydon@unixg.ubc.ca) Last update: 25-Aug-1997 Home Previous 1 o f 16 Next 12. An Introduction to Visual Basic Learning objectives In the second part of the tutorial, you are going to 12.3 Tutorial exercises create a couple of VBA modules to explore looping, conditional branching, and parameter passing. 12.3.1 Invoking the interpreter • Click on the module tab in the database window 12.2 Learning objectives and press New. What is the debug/immediate window? How This opens the module window which we will use in do I invoke it? Section 12.3.3. You have to have a module window What are statements, variables, the open in order for the debug window to be available assignment operator, and predefined from the menu. functions? • Select View Debug Window from the main How do I create a module containing VBA menu. Note that Control-G can be used in ver- sion 7.0 and above as a shortcut to bring up the code? debug window. What are looping and conditional branching? What language constructs can I use to In version 2.0, the “debug” window is called implement them? the “immediate” window. As such, you have to How do I use the debugger in Access? use View Immediate Window. The term What is the difference between an interpreted debug window will be used throughout this tutorial. and compiled programming language? Home Previous 2 o f 16 Next
  • 96. 12. An Introduction to Visual Basic Tutorial exercises 12.3.2 Basic programming constructs 12.3.2.2 Variables and assignment In this section, we are going to use the debug win- A variable is space in memory to which you assign a dow to explore some basic programming constructs. name. When you use the variable name in expres- sions, the programming language replaces the vari- 12.3.2.1 Statements able name with the contents of the space in memory Statements are special keywords in a programming at that particular instant. language that do something when executed. For • Type the following: example, the Print statement in VBA prints an s = “Hello”↵ expression on the screen. ? s “ world”↵ • In the debug window, type the following: ? “s” “ world”↵ Print “Hello world!”↵ In the first statement, a variable s is created and the (the ↵ symbol at the end of a line means “press the string Hello is assigned to it. Recall the function of Return or Enter key”). the concatenation operator () from Section 4.4.2. In VBA (as in all dialects of BASIC), the ques- Contrary to the practice in languages like C tion mark (?) is typically used as shorthand for and Pascal, the equals sign (=) is used to the Print statement. As such, the statement: assign values to variables. It is also used as ? “Hello world!”↵ is identical to the the equivalence operator (e.g., does x = y?). statement above. Home Previous 3 o f 16 Next 12. An Introduction to Visual Basic Tutorial exercises When the second statement is executed, VBA recog- is a function that is provided as part of the program- nizes that s is a variable, not a string (since it is not ming environment. in quotations marks). The interpreter replaces s with For example, cos(x) is a predefined function in its value (Hello) before executing the Print com- many computer languages—it takes some number x mand. In the final statement, s is in quotation marks as an argument, does some processing to find its so it is interpreted as a literal string. cosine, and returns the answer. Note that since this function is predefined, you do not have to know any- Within the debug window, any string of char- thing about the algorithm used to find the cosine, you acters in quotations marks (e.g., “COMM”) is just have to know the following: interpreted as a literal string. Any string with- out quotation marks (e.g., COMM) is interpreted 1. what to supply as inputs (e.g., a valid numeric as a variable (or a field name, if appropriate). expression representing an angle in radians), Note, however, that this convention is not uni- 2. what to expect as output (e.g., a real number versally true within different parts of Access. between -1.0 and 1.0). 12.3.2.3 Predefined functions The on-line help system provides these two pieces of information (plus a usage example In computer programming, a function is a small pro- and some additional remarks) for all VBA pre- gram that takes one or more arguments (or param- defined functions. eters) as input, does some processing, and returns a value as output. A predefined (or built-in) function Home Previous 4 o f 16 Next
  • 97. 12. An Introduction to Visual Basic Tutorial exercises In this section, we are going to explore some basic FIGURE 12.1: Interacting with the Visual Basic predefined functions for working with numbers and interpreter. text. The results of these exercises are shown in Figure 12.1. • Print the cosine of 2π radians: pi = 3.14159↵ ? cos(2*pi)↵ The argument contains • Convert a string of characters to uppercase: an expression. s = “basic or cobol”↵ ? UCase(s)↵ UCase() converts a string to uppercase. • Extract the middle six characters from a string starting at the fifth character: ? mid (s,5,6)↵ Mid() extracts characters from the 12.3.2.4 Remark statements string defined earlier. When creating large programs, it is considered good programming practice to include adequate internal documentation—that is, to include comments to explain what the program is doing. Home Previous 5 o f 16 Next 12. An Introduction to Visual Basic Tutorial exercises Comment lines are ignored by the interpreter when FIGURE 12.2: The declarations page of a Visual the program is run. To designate a comment in VBA, Basic module. use an apostrophe to start the comment, e.g.: ‘ This is a comment line! Print “Hello” ‘the comment starts here The original REM (remark) statement from BASIC can also be used, but is less common. REM This is also a comment (remark) 12.3.3 Creating a module strings are compared (e.g., does uppercase/ lower- • Close the debug window so that the declaration case matter?). The Option Explicit statement page of the new module created in forces you to declare all your variables before using Section 12.3.3 is visible (see Figure 12.2). them. The two lines: Option Compare Database Option Explicit In version 2.0, Access does not add the Option Explicit statement by default. As are included in the module by default. The Option such you should add it yourself. Compare statement specifies the way in which Home Previous 6 o f 16 Next
  • 98. 12. An Introduction to Visual Basic Tutorial exercises A module contains a declaration page and one or 12.3.4 Creating subroutines with looping more pages containing subroutines or user-defined and branching functions. The primary difference between subrou- In this section, you will explore two of the most pow- tines and functions is that subroutines simply exe- erful constructs in computer programming: looping cute whereas functions are expected to return a and conditional branching. value (e.g., cos()). Since only one subroutine or • Create a new subroutine by typing the following function shows in the window at a time, you must anywhere on the declarations page: use the Page Up and Page Down keys to navigate Sub LoopingTest()↵ the module. Notice that Access creates a new page in the mod- The VBA editor in version 8.0 has a number of ule for the subroutine, as shown in Figure 12.3. enhancements over earlier version, including 12.3.4.1 Declaring variables the capability of showing multiple functions When you declare a variable, you tell the program- and subroutines on the same page. ming environment to reserve some space in memory for the variable. Since the amount of space that is required is completely dependent on the type of data the variable is going to contain (e.g., string, integer, Boolean, double-precision floating-point, etc.), you Home Previous 7 o f 16 Next 12. An Introduction to Visual Basic Tutorial exercises • Save the module as basTesting. FIGURE 12.3: Create a new subroutine. One of the most useful looping constructs is For condition... Next. All statements between the For and Next parts are repeated as long as the condition part is true. The index i is automati- cally incremented after each iteration. • Enter the remainder of the LoopingTest pro- You can use the procedure gram: combo box to switch between procedures in a module. s = “Loop number: ” For i = 1 To 10 have to include data type information in the declara- Debug.Print s i tion statement. Next i • Save the module. In VBA, you use the Dim statement to declare vari- ables. It is customary in most programming lan- • Type the following into the space between the guages to use the Tab key to indent the ele- Sub... End Sub pair: ments within a loop slightly. This makes the Dim i as integer program more readable. Dim s as string Home Previous 8 o f 16 Next
  • 99. 12. An Introduction to Visual Basic Tutorial exercises Note that the Print statement within the subroutine FIGURE 12.4: Run the LoopingTest is prefaced by Debug. This is due to the object-ori- subroutine in the debug window. ented nature of VBA which will be explored in greater detail in Tutorial 14. 12.3.4.2 Running the subroutine Now that you have created a subroutine, you need to run it to see that it works. To invoke a subroutine, you simply use its name like you would any statement. • Select View Debug Window from the menu (or press Control-G in version 7.0). • Type: LoopingTest↵ in the debug window, as shown in Figure 12.4. 12.3.4.3 Conditional branching We can use a different looping construct, Do Until condition... Loop, and the conditional branching construct, If condition Then... Else, to achieve the same result. by typing its name in the debug window. Invoke the LoopingTest subroutine Home Previous 9 o f 16 Next 12. An Introduction to Visual Basic Tutorial exercises • Type the following anywhere under the End Sub Loop statement in order to create a new page in the • Run the program module: Sub BranchingTest↵ 12.3.5 Using the debugger • Enter the following program: Access provides a rudimentary debugger to help you Dim i As Integer step through your programs and understand how Dim s As String they are executing. The two basic elements of the Dim intDone As Integer debugger used here are breakpoints and stepping s = “Loop number: “ (line-by-line execution). i = 1 • Move to the s = “Loop number: ” line in your intDone = False BranchingTest subroutine and select Run Do Until intDone = True Toggle Breakpoint from the menu (you can also If i 10 Then press F9 to toggle the breakpoint on a particular Debug.Print “All done” line of code). intDone = True Note that the line becomes highlighted, indicating the Else presence of an active breakpoint. When the program Debug.Print s i runs, it will suspend execution at this breakpoint and i = i + 1 pass control of the program back to you. End If Home Previous 10 o f 16 Next
  • 100. 12. An Introduction to Visual Basic Tutorial exercises • Run the subroutine from the debug window, as FIGURE 12.5: Execution of the subroutine is shown in Figure 12.5. suspended at the breakpoint. • Step through a couple of lines in the program line-by-line by pressing F8. By stepping through a program line by line, you can usually find any program bugs. In addition, you can use the debug window to examine the value of vari- ables while the program’s execution is suspended. • click on the debug window and type ? i↵ to see the current value of the variable i. 12.3.6 Passing parameters In the BranchingTest subroutine, the loop starts The outlined box indicates the current location of the at 1 and repeats until the counter i reaches 10. It interpreter in the program. Press may be preferable, however, to set the start and fin- F8 to execute the line of code. ish quantities when the subroutine is called from the debug window. To achieve this, we have to pass parameters (or arguments) to the subroutine. Home Previous 11 o f 16 Next 12. An Introduction to Visual Basic Tutorial exercises The main difference between passed parameters FIGURE 12.6: Highlight the code to copy it. and other variables in a procedure is that passed parameters are declared in the first line of the sub- routine definition. For example, following subroutine declaration Sub BranchingTest(intStart as Integer, intStop as Integer) not only declares the variables intStart and intStop as integers, it also tells the subroutine to expect these two numbers to be passed as parame- ters. To see how this works, create a new subroutine called ParameterTest based on Branch- ingTest. • Type the declaration statement above to create the ParameterTest subroutine. • Switch back to BranchingTest and highlight all the code except the Sub and End Sub state- ments, as shown in Figure 12.6. Home Previous 12 o f 16 Next
  • 101. 12. An Introduction to Visual Basic Tutorial exercises • Copy the highlighted code to the clipboard (Con- 12.3.7 Creating the Min() function trol-Insert), switch to ParameterTest, and In this section, you are going to create a user- paste the code (Shift-Insert) into the Parame- defined function that returns the minimum of two terTest procedure. numbers. Although most languages supply such a To incorporate the parameters into ParameterT- function, Access does not (the Min() and Max() est, you will have to make the following modifica- function in Access are for use within SQL statements tions to the pasted code: only). • Replace i = 1 with i = intStart. • Create a new module called basUtilities. • Replace i 10 with i intStop. • Type the following to create a new function: • Call the subroutine from the debug window by Function MinValue(n1 as Single, n2 typing: as Single) as Single↵ ParameterTest 4, 12↵ This defines a function called MinValue that returns a single-precision number. The function requires two If you prefer enclosing parameters in brack- single-precision numbers as parameters. ets, you have to use the Call sub name(parameter1, ..., parametern) Since a function returns a value, the data type syntax. For example: of the return value should be specified in the Call ParameterTest(4,12)↵ function declaration. As such, the basic syn- tax of a function declaration is: Home Previous 13 o f 16 Next 12. An Introduction to Visual Basic Discussion Function function 12.4 Discussion name(parameter1 As data type, …, parametern As data type) As 12.4.1 Interpreted and compiled data type languages The function returns a variable named VBA is an interpreted language. In interpreted lan- function name. guages, each line of the program is interpreted (con- • Type the following as the body of the function: verted into machine language) and executed when the program is run. Other languages (such as C, If n1 = n2 Then Pascal, FORTRAN, etc.) are compiled, meaning MinValue = n1 that the original (source) program is translated and Else saved into a file of machine language commands. MinValue = n2 This executable file is run instead of the source End If code. • Test the function, as shown in Figure 12.7. Predictably, compiled languages run much faster then interpreted languages (e.g., compiled C++ is generally ten times faster than interpreted Java). However, interpreted languages are typically easier to learn and experiment with. Home Previous 14 o f 16 Next
  • 102. 12. An Introduction to Visual Basic Discussion FIGURE 12.7: Testing the MinValue() function. function using conditional branching. Implement the MinValue() various parameterby passing it Test the function values. According to the function declaration, MinValue() expects two single-precision numbers as parameters. Anything else generates an error. These five lines could be replaced with one line: MinValue = iif(n1 = n2, n1, n2) Home Previous 15 o f 16 Next 12. An Introduction to Visual Basic Application to the assignment 12.5 Application to the assignment You will need a MinValue() function later in the assignment when you have to determine the quantity to ship. • Create a basUtilities module in your assign- ment database and implement a MinValue() function. To ensure that no confusion arises between your user-defined function and the built-in SQL Min() function, do not call you function Min(). Home Previous 16 o f 16 Next
  • 103. Access Tutorial 13: Event-Driven Programming Using Macros 13.1 Introduction: What is event- the order entry is complete, the inventory update driven programming? module is executed, and so on. Event-driven programming, graphical user interfaces In conventional programming, the sequence of oper- ations for an application is determined by a central (GUIs), and object-orientation are all related since forms (like those created in Tutorial 6) and the controlling program (e.g., a main procedure). In graphical interface objects on the forms serve as the event-driven programming, the sequence of opera- skeleton for the entire application. To create an tions for an application is determined by the user’s event-driven application, the programmer creates interaction with the application’s interface (forms, menus, buttons, etc.). small programs and attaches them to events associ- ated with objects, as shown in Figure 13.1. In this For example, rather than having a main procedure way, the behavior of the application is determined by that executes an order entry module followed by a the interaction of a number of small manageable pro- data verification module followed by an inventory grams rather than one large program. update module, an event-driven application remains in the background until certain events happen: when a value in a field is modified, a small data verification program is executed; when the user indicates that © Michael Brydon (brydon@unixg.ubc.ca) Last update: 25-Aug-1997 Home Previous 1 o f 26 Next 13. Event-Driven Programming Using Macros Introduction: What is event-driven programming? 13.1.1 Triggers FIGURE 13.1: In a trigger, a procedure is attached to an event. Since events on forms “trigger” actions, event/proce- dure combinations are sometimes called triggers. An object, such as the interface object button created in For example, the action query you attached to a but- cmdUpdateCredits Section 11.3.5, has ton in Section 11.3.5 is an example of a simple, one- predefined properties and action trigger. However, since an action query can properties events. For a button, the Caption most important event is only perform one type of action, and since you typi- Enabled On Click. cally have a number of actions that need to be per- ... formed, macros or Visual Basic procedures are events procedure typically used to implement a triggers in Access. On Click On Got Focus ... 13.1.2 The Access macro language As you discovered in Tutorial 12, writing simple VBA A procedure (such as an programs is not difficult, but it is tedious and error- action query, macro, or VBA prone. Furthermore, as you will see in Tutorial 14, function or subroutine) can be VBA programming becomes much more difficult attached to an event. When the event occurs, the when you have to refer to objects using the naming procedure is executed. conventions of the database object hierarchy. As a consequence, even experienced Access program- Home Previous 2 o f 26 Next
  • 104. 13. Event-Driven Programming Using Macros Learning objectives mers often turn to the Access macro language to attach the procedure to the correct event of the cor- implement basic triggers. rect object. The macro language itself consists of 40 or so com- Selecting the correct object and the correct mands. Although it is essentially a procedural lan- event for a trigger is often the most difficult guage (like VBA), the commands are relatively high part of creating an event-driven application. It level and easy to understand. In addition, the macro is best to think about this carefully before you editor simplifies the specification of the action argu- get too caught up in implementing the proce- ments (parameters). dure. 13.1.3 The trigger design cycle 13.2 Learning objectives To create a trigger, you need to answer two ques- tions: What is event-driven programming? What is a trigger? 1. What has to happen? 2. When should it happen? How do I design a trigger? Once you have answered the first question (“what”), How does the macro editor in Access work? you can create a macro (or VBA procedure) to exe- How do I attach a macro to an event? cute the necessary steps. Once you know the answer to the second question (“when”), you can What is the SetValue action? How is it used? Home Previous 3 o f 26 Next 13. Event-Driven Programming Using Macros Tutorial exercises How do I make the execution of particular 13.3.1 The basics of the macro editor macro actions conditional? In this section, you are going to eliminate the warn- What is a switchboard and how do I create ing messages that precede the trigger you created one for my application? Section 11.3.5. How to I make things happen when the As such, the answer to the “what” question is the fol- application is opened? lowing: What are the advantages and disadvantages 1. Turn off the warnings so the dialog boxes do not of event-driven programming? pop up when the action query is executed; 2. Run the action query; and, 13.3 Tutorial exercises 3. Turn the warnings back on (it is generally good programming practice to return the environment In this tutorial, you will build a number of very simple to its original state). triggers using Access macros. These triggers, by themselves, are not particularly useful and are Since a number of things have to happen, you can- intended for illustrative purposes only. not rely on an action query by itself. You can, how- ever, execute a macro that executes several actions including one or more action queries. Home Previous 4 o f 26 Next
  • 105. 13. Event-Driven Programming Using Macros Tutorial exercises • Select the Macros tab from the database window FIGURE 13.4: Bring up the On Click property for and press New. This brings up the macro editor the button. shown in Figure 13.2. • Add the three commands as shown in Figure 13.3. Note that the OpenQuery command is used to run the action query. • Save the macro as mcrUpdateCredits and close it. 13.3.2 Attaching the macro to the event The answer to the “when” question is: When the cmdUpdateCredits button is pressed. Since you already created the button in Section 11.3.5, all you need to do is modify its On Click property to point the mcrUpdateCredits macro. • Open frmDepartments in design mode. • Bring up the property sheet for the button and scroll down until you find the On Click property, The button wizard attached a as shown in Figure 13.4. VBA procedure to the button. Home Previous 5 o f 26 Next 13. Event-Driven Programming Using Macros Tutorial exercises FIGURE 13.2: The macro editor. Macro actions can be selected from a list. The SetWarnings command is used to turn the warning In the comment column, you can messages (e.g., before you run an action query) on and off. document your macros as required Multiple commands are executed from top to bottom. Most actions have one or more arguments that determine the specific behavior of the action. In this case, the SetWarnings action is set to turn warnings off. The area on the right displays information about the action. Home Previous 6 o f 26 Next
  • 106. 13. Event-Driven Programming Using Macros Tutorial exercises FIGURE 13.3: Create a macro that answers the “what” question. the macro. commands to Add the three SetWarningsfor the two The arguments actions are straightforward. For the OpenQuery command, you can select the query to open (or run) from a list. Since this is an action query, the second and third arguments are not applicable. Home Previous 7 o f 26 Next 13. Event-Driven Programming Using Macros Tutorial exercises • Press the builder button ( ) beside the existing FIGURE 13.5: Select the macro to attach to the procedure and look at the VBA subroutine cre- On Click property. ated by the button wizard. Most of this code is for error handling. Unlike the stand-along VBA modules you cre- ated in Tutorial 12, this module (collection of of available macrosget a list functions and subroutines) is embedded in Press the arrow to the frmDepartments form. • Since you are going to replace this code with a macro, you do not want it taking up space in your database file. Highlight the text in the subroutine and delete it. When you close the module win- dow, you will see the reference to the “event pro- cedure” is gone. • Bring up the list of choice for the On Click prop- erty as shown in Figure 13.5. Select mcrUp- dateCredits. Home Previous 8 o f 26 Next
  • 107. 13. Event-Driven Programming Using Macros Tutorial exercises • Switch to form view and press the button. Since to modify the structure of the table until the no warnings appear, you may want to press the query or form is closed. button a few times (you can always use your roll- back query to reset the credits to their original • Set the Caption property to Credits updated? values). and the Default property to No as shown in Figure 13.6. 13.3.3 Creating a check box to display Changes made to a table do not automatically carry update status information over to forms already based on that table. As such, Since the warning boxes have been disabled for the you must manually add the new field to the depart- update credits trigger, it may be useful to keep track ments form. of whether courses in a particular department have • Open frmDepartments in design mode. already been updated. • Make sure the toolbox and field list are visible. Notice that the new field (CrUpdated) shows up To do this, you can add a field to the Departments in the field list. table to store this “update status” information. • Use the same technique for creating combo • Edit the Departments table and add a Yes/No boxes to create a bound check box control for the field called CrUpdated. yes/no field. This is shown in Figure 13.7. If you have an open query or form based on the Departments table, you will not be able Home Previous 9 o f 26 Next 13. Event-Driven Programming Using Macros Tutorial exercises this section, you are going to use one of the most FIGURE 13.6: Add a field to the Departments useful commands—SetValue—to automatically table to record the status of updates. change the value of the CrUpdated check box. • Open your mcrUpdateCredits macro in design mode and add a SetValue command to change the CrUpdated check box to Yes (or True, if you prefer). This is shown in Figure 13.8. • Save the macro and press the button on the form. Notice that the value of the check box changes, reminding you not to update the courses for a particular department more than once. 13.3.5 Creating conditional macros Rather than relying on the user not to run the update when the check box is checked, you may use a con- ditional macro to prevent an update when the check box is checked. 13.3.4 The SetValue command So far, you have used two commands in the Access macro language: SetWarnings and OpenQuery. In Home Previous 10 o f 26 Next
  • 108. 13. Event-Driven Programming Using Macros Tutorial exercises FIGURE 13.7: Add a check box control to keep track of the update status. from the toolbox.box tool Select the check A check box is a control that can be bound to fields of the yes/no data type. When the box is checked, True is stored in the table; when the box is field list to the detail section.from the Drag the CrUpdated field unchecked, False is stored. Home Previous 11 o f 26 Next 13. Event-Driven Programming Using Macros Tutorial exercises FIGURE 13.8: Add a SetValue command to set the value of the update status field when the update is compete. from the SetValue command Pick the list or simply type it in. The Item argument is the thing you The Expression argument is the value you want the SetValue want the SetValue action to set the action to set the value of the Item value of. You can use the builder or to. Type in Yes (no quotation simply type in CrUpdate. marks are required since Yes is recognized as a constant in this context). Home Previous 12 o f 26 Next
  • 109. 13. Event-Driven Programming Using Macros Tutorial exercises • Select View Conditions to display the condi- 13.3.5.1 The simplest conditional macro tions column in the macro editor as shown in If there is an expression in the condition column of a Figure 13.9. macro, the action in that row will execute if the condi- FIGURE 13.9: Display the macro editors tion is true. If the condition is not true, the action will condition column be skipped. • Fill in the condition column as shown in Figure 13.10. Precede the actions you want to execute if the check box is checked with [CrUp- dated]. Precede the actions you do not want to execute with Not [CrUpdated]. Since CrUpdated is a Boolean (yes/no) vari- able, you do not need to write [CrUpdated] = True or [CrUpdated] = False. The “conditions” Conditions toolpress the Select View or true and false parts are implied. However, if a button on the bar. non-Boolean data type is used in the expres- sion, a comparison operator must be included (e.g., [DeptCode] = “COMM”, [Cred- its] 3, etc.) Home Previous 13 o f 26 Next 13. Event-Driven Programming Using Macros Tutorial exercises FIGURE 13.10: Create a conditional macro to control which actions execute. is true if the CrUpdated check box is The expression Not [CrUpdated] not checked. Use this expression in front of the actions you want to execute in this situation. true if the CrUpdated check box is The expression [CrUpdated] is checked. In this situation, you should indicate to the user that the update is not being performed. The MsgBox action displays a standard Windows message box. You can set the message and other message box features in the arguments section. Home Previous 14 o f 26 Next
  • 110. 13. Event-Driven Programming Using Macros Tutorial exercises • Switch to the form and test the macro by pressing 13.3.5.2 Refining the conditions the button. If the CrUpdated check box is The macro shown in Figure 13.10 can be improved checked, you should get a message similar to by using an ellipsis (…) instead of repeating the that shown in Figure 13.11. same condition in line after line. In this section, you FIGURE 13.11: The action query is not executed will simplify your conditional macro slightly. and the message box appears instead. Move the message box action and condition to the top of the list of actions by dragging its record selec- tor (grey box on the left). • Insert a new row immediately following the mes- sage and add a StopMacro action, as shown in Figure 13.12. The macro in Figure 13.12 executes as follows: If CrUpdate is true (i.e., the box is checked), the MsgBox action executes. Since the next line has an ellipsis in the condition column, the condition contin- ues to apply. However, that action on the ellipsis line is StopMacro, and thus the macro ends without executing the next four lines. Home Previous 15 o f 26 Next 13. Event-Driven Programming Using Macros Tutorial exercises If the CrUpdate box is not checked, the first two FIGURE 13.12: Rearrange the macro actions and lines are ignored (i.e., the lines with the false condi- insert a new row. tion and the ellipsis) and the update proceeds. message box action to theand drag thelist. Click the record selector top of the 13.3.5.3 Creating a group of named macros It is possible to store a number of related macros Add an ellipsis together in one macro “module”. These group mac- (…) and a ros have two advantages: StopMacro action. 1. Modular macros can be created — instead of having a large macro with many conditions and branches, you can create a small macro that call other small macros. 2. Similar macros can be grouped together — for example, you could keep all you Departments- related macros or search-related macros in a macro group. to insert a new rowyou would like Right-click where and select In this section, we will focus on the first advantage. • Select View Macro Names to display the macro Insert Row from the popup menu. name column. Home Previous 16 o f 26 Next
  • 111. 13. Event-Driven Programming Using Macros Tutorial exercises • Perform the steps in Figure 13.13 to modularize • Remove the scroll bars, navigation buttons, and your macro. record selectors from the form using the form’s • Change the macro referred to in the On Click property sheet. property of the cmdUpdateCredits button from • Save the form as swbMain. mcrUpdateCredits to There are two ways to add button-based triggers to a mcrUpdateCredits.CheckStatus. form: • Test the operation of the button. 1. Turn the button wizard off, create the button, and attach an macro containing the appropriate 13.3.6 Creating switchboards action (or actions). One of the simplest (but most useful) triggers is an 2. Turn the button wizard on and use the wizard to OpenForm command attached to a button on a form select from a list of common actions (the wizard consisting exclusively of buttons. writes a VBA procedure for you). This type of “switchboard” (as shown in Figure 13.14) can provide the user with a means of Since the wizard can only attach one action to navigating the application. a button (such as opening a form or running • Create an unbound form as shown in an action query) it is less flexible than a Figure 13.15. macro. However, once you are more comfort- able with VBA, there is nothing to stop you Home Previous 17 o f 26 Next 13. Event-Driven Programming Using Macros Tutorial exercises FIGURE 13.13: Use named macros to modularize the macro. the macro names column. to display Select View Macro Names A macro executes until it encounters a blank line. Use blank lines to separate the named macros within a group. CheckStatusmacro called the Create a named that contains conditional logic for the procedure. Create two other macros, Updated and NotUpdated that correspond to the logic in the CheckStatus macro. particular macro. action executes a to The RunMacro Select the macro execute from a list in the arguments pane. Note the naming convention for macros within a macro group. Home Previous 18 o f 26 Next
  • 112. 13. Event-Driven Programming Using Macros Tutorial exercises FIGURE 13.14: A switchboard interface to the application. The command buttons are placed on an Although it is not shown here, switchboards can unbound form. Note the absence of scroll bars, call other switchboards, allowing you to add a record selectors, or navigation buttons. hierarchical structure to your application. Gratuitous clip art can be used to Shortcut keys are include on each clutter your forms and reduce the button to allow the user to navigate application’s overall performance. the application with keystrokes. Home Previous 19 o f 26 Next 13. Event-Driven Programming Using Macros Tutorial exercises FIGURE 13.15: Create an unbound form as the switchboard background. leave the “record source”wizard) and Select Design View (no box empty. you can buildayour switchboard. The result is blank form on which Home Previous 20 o f 26 Next
  • 113. 13. Event-Driven Programming Using Macros Tutorial exercises from editing the VBA modules created by the • Follow the directions provided by the wizard to wizard to add additional functionality. set the action for the button (i.e., open the frm- Courses form) as shown in Figure 13.17. 13.3.6.1 Using a macro and manually-created • Change the button’s font and resize it as buttons required. • Ensure the wizard is turned off and use the but- ton tool to create a button. You can standardize the size of your form • Modify the properties of the button as shown in objects by selecting more than one and using Figure 13.16. Format Size to Tallest and to Widest com- • Create a macro called mands. Similarly, you can select more than mcrSwitchboard.OpenDept and use the one object and use the “multiple selection” OpenForm command to open the form frmDe- property sheet to set the properties all at partments. once. • Attach the macro to the On Click event of the cmdDepartments button. 13.3.7 Using an autoexec macro • Test the button. If you use the name autoexec to save a macro (in 13.3.6.2 Using the button wizard lieu of the normal mcrname convention), Access • Turn the button wizard back on and create a new will execute the macro actions when the database is button. opened. Consequently, auto-execute macros are Home Previous 21 o f 26 Next 13. Event-Driven Programming Using Macros Tutorial exercises FIGURE 13.16: Create a button and modify its appearance. (ensure the wizard activated).a button Use the button tool to create (e.g., cmdDepartments) and caption Give the button a meaningful name (including a shortcut key.). Scroll down the property sheet and change the value of the button’s Font Size property. Resize the button by dragging its handles. Home Previous 22 o f 26 Next
  • 114. 13. Event-Driven Programming Using Macros Tutorial exercises FIGURE 13.17: Use the command button wizard to create a button for the switchboard. the action type associated with the button.as Select Form Operations Open Form Provide a caption for the button. from the list. form Select the correct Home Previous 23 o f 26 Next 13. Event-Driven Programming Using Macros Tutorial exercises often used to display a switchboard when the user from the menu system. Consequently, you need to starts the application. know something about the menu structure of Access Another typical auto-execute operation is to hide the before you create your macro. database window. By doing this, you unclutter the screen and reduce the risk of a user accidentally making a change to the application (by deleting a In version 8.0, the DoMenuItem action has been replaced by the slightly more intuitive RunCommand action. See on-line help for database object, etc.). more information on RunCommand. To unhide the database window, select Win- • Create an auto-execute macro dow Unhide from the main menu or press • Add the DoMenuItem and OpenForm actions to the database window icon ( ) on the toolbar. hide the database window and open the main The problem with hiding the database window using switchboard, as shown in Figure 13.18. a macro is that there is no HideDatabaseWindow • Close the database and reopen it after a short command in the Access macro language. As such, delay to test the macro. you have to rely on the rather convoluted DoMenu- In version 7.0 and above, you do not need to Item action. use an autoexec macro to hide the database As its name suggests, the DoMenuItem action per- window and open a form. Instead, you can forms an operation just as if it had been selected right-click on the database window, select Home Previous 24 o f 26 Next
  • 115. 13. Event-Driven Programming Using Macros Discussion 13.4 Discussion FIGURE 13.18: Create an auto-execute macro. 13.4.1 Event-driven programming versus conventional programming The primary advantages of event-driven program- ming are the following: 1. Flexibility — since the flow of the application is controlled by events rather than a sequential pro- gram, the user does not have to conform to the programmer’s understanding of how tasks should be executed. WindowDoMenuItem action, select the For the Hide commands from the 2. Robustness — Event-driven applications tend to be more robust since they are less sensitive to Database menu (i.e., the menu that is active when the database window is being used). the order in which users perform activities. In conventional programming, the programmer has to anticipate virtually every sequence of activities Startup, and fill in the properties for the appli- the user might perform and define responses to cation. these sequences. Home Previous 25 o f 26 Next 13. Event-Driven Programming Using Macros Application to the assignment The primary disadvantage of event-driven programs • Create a main switchboard for you application. It is that it is often difficult to find the source of errors should provide links to all the database objects when they do occur. This problem arises from the your user is expected to have access to (i.e., your object-oriented nature of event-driven applications— forms). since events are associated with a particular object you may have to examine a large number of objects before you discover the misbehaving procedure. This is especially true when events cascade (i.e., an event for one object triggers an event for a different object, and so on). 13.5 Application to the assignment • Add “update status” check boxes to you transac- tion processing forms (i.e., Orders and Ship- ments) • Create a conditional macro for your Shipments form to prevent a particular shipment from being added to inventory more than once. Home Previous 26 o f 26 Next
  • 116. Access Tutorial 14: Data Access Objects 14.1 Introduction: What is the DAO that its modularity supports easier development and hierarchy? maintenance of applications. The disadvantage is that is you have to understand a The core of Microsoft Access and an important part large part of the hierarchy before you can write your of Visual Basic (the stand-alone application develop- ment environment) is the Microsoft Jet database first line of useful code. This makes using VBA diffi- cult for beginners (even for those with considerable engine. The relational DBMS functionality of Access comes from the Jet engine; Access itself merely pro- experience writing programs in BASIC or other 3GLs*). vides a convenient interface to the database engine. Because the application environment and the data- 14.1.1 DAO basics base engine are implemented as separate compo- Although you probably do not know it, you already nents, it is possible to upgrade or improve Jet have some familiarity with the DAO hierarchy. For without altering the interface aspects of Access, and example, you know that a Database object (such as vice-versa. univ0_vx.mdb) contains other objects such as Microsoft takes this component-based approach fur- tables (TableDef objects) and queries (QueryDef ther in that the interface to the Jet engine consists of objects). Moving down the hierarchy, you know that a hierarchy of components (or “objects”) called Data TableDef objects contain Field objects. Access Objects (DAO). The advantage of DAO is * Third-generation programming languages. © Michael Brydon (brydon@unixg.ubc.ca) Last update: 25-Aug-1997 Home Previous 1 o f 22 Next 14. Data Access Objects Introduction: What is the DAO hierarchy? Unfortunately, the DAO hierarchy is somewhat more every object has a number of properties that can be complex than this. However, at this level, it is suffi- either observed (read-only properties) or set (read/ cient to recognize three things about DAO: write properties). For example, each TableDef (table 1. Each object that you create is an instance of a definition) object has a read-only property called class of similar objects (e.g., univ0_vx is a par- DateCreated and a read/write property called Name. ticular instance of the class of Database objects). To access an object’s properties in VBA, you nor- 2. Each object may contain one or more Collec- mally use the object name.property tions of objects. Collections simply keep all name syntax, e.g., objects of a similar type or function under one Employees.DateCreated. umbrella. For example, Field objects such as To avoid confusion between a property called DeptCode and CrsNum are accessible through a DateCreated and a field (defined by you) Collection called Fields). called DateCreated, Access version 7.0 3. Objects have properties and methods (see and above require that you use a bang (!) below). instead of a period to indicate a field name or some other object created by you as a devel- 14.1.2 Properties and methods oper. For example: You should already be familiar with the concept of Employees!DateCreated.Value object properties from the tutorial on form design identifies the Value property of the DateCre- (Tutorial 6). The idea is much the same in DAO: Home Previous 2 o f 22 Next
  • 117. 14. Data Access Objects Introduction: What is the DAO hierarchy? ated field (assuming one exists) in the object summaries in the on-line help if you are Employees table. unsure. Methods are actions or behaviors that can be A more obvious example of a method is the Cre- applied to objects of a particular class. In a sense, ateField method of TableDef objects, e.g.: they are like predefined functions that only work in Employees.CreateField(“Phone”, the context of one type of object. For example, all dbText, 25) Field objects have a method called FieldSize that This creates a field called Phone, of type dbText (a returns the size of the field. To invoke a object’s constant used to represent text), with a length of 25 methods, you use the characters. object name.method [parameter1, ..., parametern] syntax, e.g.,: 14.1.3 Engines, workspaces, etc. DeptCode.FieldSize. A confusing aspect of the DAO hierarchy is that you cannot simply refer to objects and their properties as A reasonable question at this point might be: done in the examples above. As Figure 14.1 illus- Isn’t FieldSize a property of a field, not a trates, you must include the entire path through the method? The answer to this is that the imple- hierarchy in order to avoid any ambiguity between, mentation of DAO is somewhat inconsistent in say, the DeptCode field in the Courses TableDef this respect. The best policy is to look at the object and the DeptCode field in the qryCourses QueryDef object. Home Previous 3 o f 22 Next 14. Data Access Objects Introduction: What is the DAO hierarchy? FIGURE 14.1: Navigating the DAO hierarchy. To access a particular field, you DBEngine By creating a database object at have to understand the structure the start of your VBA of the DAO hierarchy. programs, you bypass the top Workspaces part of the hierarchy. Databases other classes... TableDefs QueryDefs Recordsets other classes... Courses other tables... qryCourses other queries... Fields Fields Legend DeptCode DeptCode TableDefs object or collection Indexes Indexes Courses instance Home Previous 4 o f 22 Next
  • 118. 14. Data Access Objects Learning objectives Working down through the hierarchy is especially 14.3 Tutorial exercises confusing since the first two levels (DBEngine and Workspaces) are essentially abstractions that have 14.3.1 Setting up a database object no physical manifestations in the Access environ- In this section you will write VBA code that creates a ment. The easiest way around this is to create a pointer to the currently open database. Database object that refers to the currently open • Create a new module called basDAOTest (see database (e.g., univ0_vx.mdb) and start from the Section 12.3.3 for information on creating a new database level when working down the hierarchy. module). Section 14.3.1 illustrates this process for version 2.0. • Create a new subroutine called PrintRecords. • Define the subroutine as follows: 14.2 Learning objectives Dim dbCurr As DATABASE What is the DAO hierarchy? Set dbCurr = What are objects? What are properties and DBEngine.Workspaces(0).Databases(0) methods? Debug.Print dbCurr.Name How do I create a reference to the current • Run the procedure, as shown in Figure 14.2. Let us examine these three statements one by one. database object? Why is this important? What is a recordset object? 1. Dim dbCurr As DATABASE This statement declares the variable dbCurr as How do I search a recordset? an object of type Database. For complex objects Home Previous 5 o f 22 Next 14. Data Access Objects Tutorial exercises FIGURE 14.2: Create a pointer to the current database. (dbCurr) toset the pointer Declare and the current database. of thea database. the name Add line to print Although you can use the Print statement by itself Run the procedure to ensure it works. in the debug window, you must invoke the Print method of the Debug object Version 7.0 and above support a less from a module—hence the cumbersome way referring to the current Debug.Print syntax. database—the CurrentDb function: Set dbCurr = CurrentDb Home Previous 6 o f 22 Next
  • 119. 14. Data Access Objects Tutorial exercises (in contrast to simple data types like integer, Do not worry if you are not completely sure string, etc.) Access does not allocate memory what is going on at this point. As long as you space for a whole database object. Instead, it understand that you can type the above two allocates space for a pointer to a database lines to create a pointer to your database, object. Once the pointer is created, you must set then you are in good shape. it to point to an object of the declared type (the object may exist already or you may have to cre- 3. Debug.Print dbCurr.Name ate it). This statement prints the name of the object to 2. Set dbCurr = DBEngine.Work- which dbCurr refers. spaces(0).Databases(0) (Note: this should be typed on one line). In this 14.3.2 Creating a Recordset object statement, the variable dbCurr (a pointer to a As its name implies, a TableDef object does not con- Database object) is set to point to the first Data- tain any data; instead, it merely defines the structure base in the first Workspace of the only Database of a table. When you view a table in design mode, Engine. Since the numbering of objects within a you are seeing the elements of the TableDef object. collection starts at zero, Databases(0) indi- When you view a table in datasheet mode, in con- cates the first Database object. Note that the first trast, you are seeing the contents of Recordset Database object in the Databases collection is object associated with the table. always the currently open one. Home Previous 7 o f 22 Next 14. Data Access Objects Tutorial exercises To access the data in a table using VBA, you have to 2. Sets rsCourses to point to the newly created invoke the OpenRecordset method of the Data- recordset. base object. Since most of the processing you do in Note that this Set statement is different than the pre- VBA involves data access, familiarity with Recordset vious one since the OpenRecordset method objects is essential. In this section, you will create a results in a new object being created (dbCurr points Recordset object based on the Courses table. to an existing database—the one you opened when • Delete the Debug.Print dbCurr.Name line you started Access). from your program. • Add the following: 14.3.3 Using a Recordset object Dim rsCourses As Recordset In this section, you will use some of the properties Set rsCourses = and methods of a Recordset object to print its con- dbCurr.OpenRecordset(“Courses”) tents. The first line declares a pointer (rsCourses) to a • Add the following to PrintRecords: Recordset object. The second line does two things: Do Until rsCourses.EOF 1. Invokes the OpenRecordset method of dbCurr Debug.Print rsCourses!DeptCode “ ” to create a Recordset object based on the table rsCourses!CrsNum named “Courses”. (i.e., the name of the table is rsCourses.MoveNext a parameter for the OpenRecordset method). Loop • This code is explained in Figure 14.3. Home Previous 8 o f 22 Next
  • 120. 14. Data Access Objects Tutorial exercises FIGURE 14.3: Create a program to loop through the records in a Recordset object. EOF is a property of the recordset. It is true if the record counter has reached the “end of file” (EOF) marker and false otherwise. The exclamation mark (!) indicates that DeptCode is a user-defined field (rather than a method or property) of the recordset object. Since the Value property is the default property of a field, you do not have to use the recordset!field.Value syntax. The MoveNext method moves the record counter to the next record in the recordset. Home Previous 9 o f 22 Next 14. Data Access Objects Tutorial exercises 14.3.4 Using the FindFirst method WHERE condition (a string) that ensures that only one In this section, you will use the FindFirst method record is found. of Recordset objects to lookup a specific value in a For example, to get the Title of COMM 351 from table. the Courses table, you would provide MyLookUp() • Create a new function called MyLookUp() using with the following parameters: the following declaration: 1. “Title” — a string containing the name of the Function MyLookUp(strField As field from which we want to return a value; String, strTable As String, 2. “Course” — a string containing the name of the strWhere As String) As String source table; and, An example of how you would use this function is to 3. “DeptCode = ‘COMM’ AND CrsNum = return the Title of a course from the Courses ‘335’” — a string that contains the entire table with a particular DeptCode and CrsNum. In WHERE clause for the search. other words, MyLookUp() is essentially an SQL statement without the SELECT, FROM and WHERE Note that both single and double quotation clauses. marks must be used to signify a string within a The parameters of the function are used to specify string. The use of quotation marks in this the name of the table (a string), the name of the field manner is consistent with standard practice in (a string) from which you want the value, and a English. For example, the sentence: “He shouted, ‘Wait for me.’” illus- Home Previous 10 o f 22 Next
  • 121. 14. Data Access Objects Tutorial exercises trates the use of single quotes within double Recordset object to be opened (the Find- quotes. First method only works with “dynaset” type recordsets, hence the need to include the • Define the MyLookUp() function as follows: additional parameter in this segment of code). Dim dbCurr As DATABASE Set dbCurr = CurrentDb rsRecords.FindFirst strWhere If you are using version 2.0, you cannot use VBA uses a rather unique convention to the CurrentDb method to return a pointer to determine whether to enclose the arguments the current database. You must use long form of a function, subroutine, or method in paren- (i.e., Set dbCurr = DBEngine…) theses: if the procedure returns a value, enclose the parameters in parentheses; oth- Dim rsRecords As Recordset erwise, use no parentheses. For example, in Set rsRecords = the line above, strWhere is a parameter of dbCurr.OpenRecordset(strTable, the FindFirst method (which does not dbOpenDynaset) return a value). In version 2.0, the name of some of the pre- defined constants are different. As such, you If Not rsRecords.NoMatch() Then MyLookUp = must use DB_OPEN_DYNASET rather than rsRecords.Fields(strField).Value dbOpenDynaset to specify the type of Home Previous 11 o f 22 Next 14. Data Access Objects Tutorial exercises Else need in your application, it is occasionally necessary MyLookUp = “” to perform a stand-alone query—that is, to use the End If DLookUp() function to retrieve a value from a table • Execute the function with the following statement or query. (see Figure 14.4): When using DLookUp() for the first few times, the ? MyLookUp(“Title”, “Courses”, syntax of the function calls may seem intimidating. “DeptCode = 'COMM' AND CrsNum = But all you have to remember is the meaning of a '351'”) handful of constructs that you have already used. As it turns out, what you have implemented exists These constructs are summarized below: already in Access in the form of a predefined func- • Functions — DLookUp() is a function that tion called DLookUp(). returns a value. It can be used in the exact same • Execute the DLookUp() function by calling it in manner as other functions, e.g., the same manner in which you called x = DLookUp(…) is similar to MyLookUp(). x = cos(2*pi). • Round brackets ( ) — In Access, round brackets 14.3.5 The DLookUp() function have their usual meaning when grouping The DLookUp() function is the “tool of last resort” in together operations, e.g., 3*(5+1). Round Access. Although you normally use queries and brackets are also used to enclose the arguments recordsets to provide you with the information you of function calls, e.g., x = cos(2*pi). Home Previous 12 o f 22 Next
  • 122. 14. Data Access Objects Tutorial exercises FIGURE 14.4: MyLookUp(): A function to find a value in a table. The NoMatch() method returns True if the FindFirst method finds no matching records, and False otherwise. Since strField contains the name of a valid Field object (Title) in the Fields collection, this notation returns the value of Title. Home Previous 13 o f 22 Next 14. Data Access Objects Tutorial exercises • Square brackets [ ] — Square brackets are not x = COMM means that the variable x is equal to a universally defined programming construct like the value of the variable COMM. round brackets. As such, square brackets have a • Single quotation marks ‘ ’ — Single quotation particular meaning in Access/VBA and this marks have only one purpose: to replace normal meaning is specific to Microsoft products. Simply quotation marks when two sets of quotation put, square brackets are used to signify the name marks are nested. For example, the expression of a field, table, or other object in the DAO hierar- x = “[ProductID] = ‘123’” means that the chy—they have no other meaning. Square brack- variable x is equal to the string ProductID = ets are mandatory when the object names “123”. In other words, when the expression is contain spaces, but optional otherwise. For evaluated, the single quotes are replaced with example, [Forms]![frmCourses]![Dept- double quotes. If you attempt to nest two sets of Code] is identical to Forms!frm- double quotation marks (e.g., x = “[Produc- Courses!DeptCode. tID] = “123””) the meaning is ambiguous • Quotation marks “ ” — Double quotation marks and Access returns an error. are used to distinguish literal strings from names • The Ampersand — The ampersand is the con- of variables, fields, etc. For example, catenation operator in Access/VBA and is unique x = “COMM” means that the variable x is equal to Microsoft products. The concatenation opera- to the string of characters COMM. In contrast, tor joins two strings of text together into one string of text. For example, Home Previous 14 o f 22 Next
  • 123. 14. Data Access Objects Tutorial exercises x = “one” “_two” means that the variable • Create a calculated field called Title using the x is equal to the string one_two. following expression (see Figure 14.5): If you understand these constructs at this point, then Title: DLookUp(“Title”, “Courses”, understanding the DLookUp() function is just a mat- “DeptCode = ‘” [DeptCode] “’ AND ter of putting the pieces together one by one. CrsNum = ‘” [CrsNum] “’”) 14.3.5.2 Understanding the WHERE clause 14.3.5.1 Using DLookUp() in queries The first two parameters of the DLookUp() are The DLookUp() function is extremely useful for per- straightforward: they give the name of the field and forming lookups when no relationship exists between the table containing the information of interest. How- the tables of interest. In this section, you are going to ever, the third argument (i.e., the WHERE clause) is use the DLookUp() function to lookup the course more complex and requires closer examination. name associated with each section in the Sections table. Although this can be done much easier using a At its core, this WHERE clause is similar to the one join query, this exercise illustrates the use of vari- you created in Section 5.3.2 in that it contains two ables in function calls. criteria. However, there are two important differ- • Create a new query called qryLookUpTest ences: based on the Sections table. 1. Since it is a DLookUp() parameter, the entire • Project the DeptCode, CrsNum, and Section clause must be enclosed within quotation marks. fields. This means single and double quotes-within- quotes must be used. Home Previous 15 o f 22 Next 14. Data Access Objects Tutorial exercises FIGURE 14.5: Create a query that uses DLookUp(). table onlyquerynot includethe Sections Create a (do based on Courses). correct course title for function to get the Use the DLookUp() each section. Home Previous 16 o f 22 Next
  • 124. 14. Data Access Objects Discussion 2. It contains variable (as opposed to literal) criteria. • Use strWhere in a DLookUp() call. For example, [DeptCode] is used instead of “COMM”. This makes the value returned by the 14.4 Discussion function call dependent on the current value of the DeptCode field. 14.4.1 VBA versus SQL In order to get a better feel for syntax of the function The PrintRecords procedure you created in call, do the following exercises (see Figure 14.6): Section 14.3.3 is interesting since it does essentially Switch to the debug window and define two string the same thing as a select query: it displays a set of variables (see Section 12.3.1 for more information records. on using the debug window): You could extend the functionality of the Print- strDeptCode = “COMM” Records subroutine by adding an argument and an strCrsNum = “351” IF-THEN condition. For example: These two variables will take the place the field val- Sub PrintRecords(strDeptCode as ues while you are in the debug window. String) • Write the WHERE clause you require without the Do Until rsCourses.EOF variables first. This provides you with a template If rsCourses!DeptCode = strDeptCode Then for inserting the variables. • Assign the WHERE clause to a string variable Debug.Print rsCourses!DeptCode “ ” rsCourses!CrsNum called strWhere (this makes it easier to test). Home Previous 17 o f 22 Next 14. Data Access Objects Discussion FIGURE 14.6: Examine the syntax of the WHERE clause. values of DeptCode and CrsNum.valid Create string variables that refer to criteriathe WHERE clause using literal Write first to get a sense of what is required. Use the variables in the WHERE clause and assign the expression to a string variable called strWhere. third parameter of the DLookUp()the To save typing, use strWhere as call. When replacing a literal string with a variable, you have to stop the quotation marks, insert the variable (with ampersands on either side) and restart the quotation marks. This procedure is evident when the literal and variable version are compared to each other. Home Previous 18 o f 22 Next
  • 125. 14. Data Access Objects Discussion End If SQL and QBE are declarative languages because rsCourses.MoveNext you (as a programmer) need only tell the computer Loop what you want done, not how to do it. In contrast, rsCourses.Close VBA is a procedural language since you must tell the End Sub computer exactly how to extract the records of inter- This subroutine takes a value for DeptCode as an est. argument and only prints the courses in that particu- Although procedural languages are, in general, more lar department. It is equivalent to the following SQL flexible than their declarative counterparts, they rely command: a great deal on knowledge of the underlying struc- SELECT DeptCode, CourseNum FROM ture of the data. As a result, procedural languages Courses WHERE DeptCode = tend to be inappropriate for end-user development strDeptCode (hence the ubiquity of declarative languages such as SQL in business environments). 14.4.2 Procedural versus Declarative The difference between extracting records with a query language and extracting records with a pro- gramming language is that the former approach is declarative while the latter is procedural. Home Previous 19 o f 22 Next 14. Data Access Objects Application to the assignment 14.5 Application to the assignment As a result, it is possible to cheat a little bit and cre- ate a stand-alone table (e.g., SystemVariables) 14.5.1 Using a separate table to store that contains a single record: system parameters VariableName Value When you calculated the tax for the order in GST 0.07 Section 9.5, you “hard-coded” the tax rate into the form. If the tax rate changes, you have to go through Of course, other system-wide variables could be all the forms that contain a tax calculation, find the contained in this table, but one is enough for our pur- hard-coded value, and change it. Obviously, a better poses. The important thing about the SystemVari- approach is to store the tax rate information in a ables table is that it has absolutely no relationship table and use the value from the table in all form- with any other table. As such, you must use a based calculations. DLookUp() to access this information. Strictly speaking, the tax rate for each product is a • Create a table that contains information about the property of the product and should be stored in the tax rate. Products table. However, in the wholesaling envi- • Replace the hard-coded tax rate information in ronment used for the assignment, the assumption is your application with references to the value in made that all products are taxed at the same rate. the table (i.e., use a DLookUp() in your tax cal- culations). Although the SystemVariables table only contains one record at this point, you Home Previous 20 o f 22 Next
  • 126. 14. Data Access Objects Application to the assignment should use an appropriate WHERE clause to The reason you must use a DLookUp() to get this ensure that the value for GST is returned (if no information is that there is no relationship between WHERE clause is provided, DLookUp() returns the OrderDetails and BackOrders tables. the first value in the table). Any relationship that you manage to create The use of a table such as SystemVari- between OrderDetails and BackOrders ables contradicts the principles of relational will be nonsensical and result in a non-updat- database design (we are creating an attribute able recordset. without an entity). However, trade-offs between theoretical elegance and practicality • In the query underlying your OrderDetails are common in any development project. subform, create a calculated field called QtyOn- BackOrder to determine the number of items on 14.5.2 Determining outstanding backorder for each item added to the order. This backorders calculated field will use the DLookUp() function. An good example in your assignment of a situation There are two differences between this DLookUp() requiring use of the DLookUp() is determining the and the one you did in Section 14.3.5.1 backordered quantity of a particular item for a partic- 1. Both of the variables used in the function (e.g., ular customer. You need this quantity in order to cal- CustID and ProductID) are not in the query. culate the number of each item to ship. As such, you will have to use a join to bring the Home Previous 21 o f 22 Next 14. Data Access Objects Application to the assignment missing information into the query. zero. To do this, use the iif() and IsNull() 2. ProductID is a text field and the criteria of text functions, e.g.: fields must be enclosed in quotation marks, e.g.: QtyOnBackOrderNoNull: ProductID = “123” iif(IsNull([QtyOnBackOrder]),0,[Qty However, CustID is a numeric field and the crite- OnBackOrder]) ria for numeric fields is not enclosed in quotations • Use this “clean” version in your calculations and marks, e.g.: on your form. CustID = 4. It is possible to combine these two calculated Not every combination of CustID and Pro- fields into a one-step calculation, e.g.: ductID will have an outstanding backorder. iif(IsNull(DLookUp(…)),0, When a matching records is not found, the DLookUp(…)). DLookUp() function returns a special value: The problem with this approach is that the Null. The important thing to remember is DLookUp() function is called twice: once to that Null plus or minus anything equals test the conditional part of the immediate if Null. This has implications for your “quantity statement and a second time to provide the to ship” calculation. “false” part of the statement. If the Back- Orders table is very large, this can result in • Create a second calculated field in your query to an unacceptable delay when displaying data convert any Nulls in the first calculated field to in the form. Home Previous 22 o f 22 Next
  • 127. Access Tutorial 15: Advanced Triggers 15.1 Introduction: Pulling it all How do I create an unbound combo box? together Can I implement the search capability using In this tutorial, you will bring together several of the Visual Basic? skills you have learned in previous tutorials to imple- ment some sophisticated triggers. 15.3 Tutorial exercises 15.2 Learning objectives 15.3.1 Using a macro to run VBA code How do I run VBA code using a macro? There a some things that cannot be done using the Access macro language. If the feature you wish to How do I use the value in one field to implement is critical to your application, then you automatically suggest a value for a different must implement it using VBA. However, since it is field? possible to call a VBA function from within a macro, How do I change the table or query a form is you do not have to abandon the macro language bound to once the form is already created? completely. What is the After Update event? How is it In this section, you are going to execute the Param- used? eterTest subroutine you created in Section 12.3.6 How do I provide a search capability for my from within a macro. Since the RunCode action of the Access macro language can only be used to exe- forms? © Michael Brydon (brydon@unixg.ubc.ca) Last update: 25-Aug-1997 Home Previous 1 o f 33 Next 15. Advanced Triggers Tutorial exercises cute functions (not subroutines) you must do one of 'this function calls the two things before you create the macro: ParameterTest subroutine ParameterTest intStart, intStop 1. Convert ParameterTest to a function — you do this simply by changing the Sub at the start of the ParameterTestWrapper = True 'return a value procedure to Function. End Function 2. Create a new function that executes Parame- • Call the function, as shown in Figure 15.1. terTest and call the function from the macro. 15.3.1.1 Creating a wrapper Note that the return value of the function is Since the second alternative is slightly more interest- declared as an integer, but the actual assign- ment statement is ParameterTestWrap- ing, it is the one we will use. • Open your basTesting module from per = True. This is because in Access/ VBA, the constants True and False are Tutorial 12. • Create a new function called ParameterTest- defined as integers (-1 and 0 respectively). Wrapper defined as follows: 15.3.1.2 Using the RunCode action Function • Leave the module open (you may have to resize ParameterTestWrapper(intStart As and/or move the debug window) and create a Integer, intStop As Integer) As new macro called mcrRunCodeTest. Integer Home Previous 2 o f 33 Next
  • 128. 15. Advanced Triggers Tutorial exercises FIGURE 15.1: Create a function that calls the ParameterTest subroutine. the ParameterTest Create a function to call subroutine. Since ParameterTest invoke the function (do notto Use the Print statement forget does not return a value, its the parameters). arguments are not in brackets. The return value of ParameterTestWrapper() is True, so this is printed when the function ends. Home Previous 3 o f 33 Next 15. Advanced Triggers Tutorial exercises • Add the RunCode action and use the expression • Select Run Start to execute the macro as builder to select the correct function to execute, shown in Figure 15.3. as shown in Figure 15.2. 15.3.2 Using activity information to The expression builder includes two parame- determine the number of credits ter place holders (intStart and In this section, you will create triggers attached to the intStop) in the function name. These After Update event of bound controls. are to remind you that you must pass two parameters to the ParameterTestWrap- 15.3.2.1 Scenario per() function. If you leave the place holders Assume that each type of course activity is generally where they are, the macro will fail because associated with a specific number of credits, as Access has not idea what intStart shown below: and intStop refer to. Activity Credits • Replace the parameter place holders with two lecture 3.0 numeric parameters (e.g. 3 and 6). Note that in lab 3.0 general, the parameters could be field names or tutorial 1.0 any other references to Access objects contain- seminar 6.0 ing (in this case) integers. Home Previous 4 o f 33 Next
  • 129. 15. Advanced Triggers Tutorial exercises FIGURE 15.2: Use the expression builder to select the function to execute. action to the macro. Add a RunCode Note the intStart and intStop parameter place holders. These must be replaced with expressions that Access understands. downthe expression builder to drill in Use to the user-defined functions your database file. Home Previous 5 o f 33 Next 15. Advanced Triggers Tutorial exercises Assume as well that the number of credits for a par- FIGURE 15.3: Execute the RunCode macro. ticular type of course is not cast in stone. As such, the numbers given above are merely “default” val- ues. You want to use the default credit values when you create a new course or modify an existing course. However, the user may override this default if neces- sary for a particular course. The basic requirement is illustrated in Figure 15.4. 15.3.2.2 Designing the trigger Based on the foregoing, the answer to the “what” parameter place Replace the question is the following: 1. Look up the default number of credits associated holders. with the course activity showing in the form’s Activity field. the toolRun toStart (or press the ! icon in Select bar) execute the macro. 2. Copy this number into the Courses.Credits field. Home Previous 6 o f 33 Next
  • 130. 15. Advanced Triggers Tutorial exercises FIGURE 15.4: Inserting a default value into a new record. Create a new record for a lecture-based of creditsmacro to find the default number Create a and copy the value it into the course: COMM 437: Database Technology Credits field. Select “Lecture” from the list of list of course activities created in Tutorial 8. Since this is a new record, the default value of Credits (like any numeric field) is zero. You want to use the information you just specified in the macrothe Activityvalue in the the Once executes. The field is updated, Activity field to automatically Credits field can be changed by the look up the correct default number of user. credits for a lecture course and insert it in the Credits field. Home Previous 7 o f 33 Next 15. Advanced Triggers Tutorial exercises There are several possible answers to the “when” • Ensure that you have a courses form (e.g., frm- question (although some are better than others). For Courses) and that the form has a combo box for example: the Activity field. You may wish to order the 1. When the user enters the Credits field (the On fields such that Activity precedes Credits in Enter event for Credits) — The problem with the tab order (as shown in Figure 15.4). this choice is that the user could modify the If your move fields around, remember to course’s activity without moving the focus to the adjust the tab order accordingly (recall Activity field. In such a case, the trigger would Section 8.3.4). not execute. 2. When the user changes the Activity field (the 15.3.2.4 Looking up the default value After Update event for Activity) — This choice As you discovered in Section 14.3.5, Access has a guarantees that whenever the value of Activ- DLookUp() function that allows you to go to the ity is changed, the default value will be copied Activities table and find the value of Credits into the Credits field. As such, it is a better for a particular value of Activity. A different choice. approach is to join the Activities table with the 15.3.2.3 Preliminary activities Courses table in a query so that the default value of • Modify the Activities table to include a single- credits is always available in the form. This is the precision numeric field called Credits. Add the approach we will use here. values shown in the table in Section 15.3.2.1. Home Previous 8 o f 33 Next
  • 131. 15. Advanced Triggers Tutorial exercises • Ensure you have a relationship (in the main rela- FIGURE 15.5: Use a join to make the default tionship window) between Courses.Activity value available. and Activities.Activity. • Create a new query called qryCoursesAnd- Credits based on the Courses and Activi- ties tables (see Figure 15.5). Notice that you have two credits fields: Courses.Credits (the actual number of credits for the course) and Activi- ties.Credits (the “default” or “suggested” number of credits based on the value of Activity). Access uses the table name.field name notation whenever a query contains more than one field with the same name. Since you already have forms based on the Courses table that expect a field called Credits (rather than one called Courses.Credits), it is a Home Previous 9 o f 33 Next 15. Advanced Triggers Tutorial exercises good idea to rename the Activities.Credits FIGURE 15.6: Rename one of the Credits fields. field in the query. You do this by creating a calculated field. • Rename Activities.Credits to Default- Credits as shown in Figure 15.6. Note that this eliminates the need for the table name.field name notation. 15.3.2.5 Changing the Record Source of the form Rather than create a new form based on the qry- CoursesAndCredits query, you can modify the Record Source property of the existing frmCourses form so it is bound to the query rather than the Courses table. • Bring up the property sheet for the frmCourses form and change the Record Source property to qryCoursesAndCredits as shown in Figure 15.7. table to DefaultCredits.Activities Rename Credits form the Home Previous 10 o f 33 Next
  • 132. 15. Advanced Triggers Tutorial exercises The advantage of using a join query in this manner is FIGURE 15.7: Change the Record Source that DefaultCredits is now available for use property of an existing form. within the form and within any macros or VBA mod- changeup the form’sSource property. Bring its Record property list and ules that run when the form is open. 15.3.2.6 Creating the SetValue macro The SetValue macro you require here is extremely simple once you have DefaultCredits available within the scope of the form. • Create the mcrCourses.SetCredits macro as shown in Figure 15.8. 15.3.2.7 Attaching a procedure to the After Update event The On Click event of a button is fairly simple to understand: the event occurs when the button is clicked. The events associated with non-button objects operate in exactly the same way. For exam- ple, the After Update event for controls (text box, The field list now contains all the fields in the new query. combo box, check box, etc.) occurs when the value Home Previous 11 o f 33 Next 15. Advanced Triggers Tutorial exercises • Attach the mcrCourses.SetCredits macro to FIGURE 15.8: Create the SetValue macro. the After Update event of the Activity field. • Verify that the trigger works properly. and a named macro called SetCredits. Create a macro group called mcrCourses 15.3.3 Use an unbound combo box to automate search As mentioned in Tutorial 8, a combo box has no intrinsic search capability. However, the idea of scan- ning a short list of key values, selecting a value, and having all the information associated with that record pop on to the screen is so basic that in Access ver- sion 7.0 and above, this capability is included in the combo box wizard. In this tutorial, we will look at a or simplyuse the builder to set the arguments You can type in the names of the fields. couple of different means of creating a combo boxes for search from scratch. of the control is changed by the user. As a result, the 15.3.3.1 Manual search in Access After Update event is often used to trigger data verifi- To see how Access searches for records, do the fol- cation procedures and “auto-fill” procedures like the lowing: one you are creating here. • Open your frmDepartments form. Home Previous 12 o f 33 Next
  • 133. 15. Advanced Triggers Tutorial exercises • Move to the field on which you want to search • Set the Enabled property of DeptCode to No (the (e.g., DeptCode); user should never be able to change the key val- • Select Edit Find (or press Control-F); ues of existing records). • Fill out the search dialog box as shown in 15.3.3.3 Creating the unbound combo box Figure 15.9. The key thing to remember about the combo box In the dialog box, you specify what to search for used to specify the search criterion is that it has (usually a key value) and specify how Access should nothing to do with the other fields or the underlying conduct its search. When you press Find First, table. As such, it should be unbound. Access finds the first record that matches your • Create an unbound combo box in the form search value and makes it the current record (note header, as shown in Figure 15.10. that if you are searching on a key field, the first • Change the Name property of the combo box to matching record is also the only matching record). cboDeptCode. 15.3.3.2 Preliminaries • The resulting combo box should resemble that To make this more interesting, assume that the frm- shown in Figure 15.11. Departments form is for viewing editing existing When you create an unbound combo box, departmental information (rather than adding new Access gives it a default name (e.g., departments). To enforce this limitation, do the fol- Combo5). You should do is change this to lowing: something more descriptive (e.g., cboDept- • Set the form’s Allow Additions property to No. Home Previous 13 o f 33 Next 15. Advanced Triggers Tutorial exercises FIGURE 15.9: Search for a record using the “find” dialog box. the field you wishtoto Move the cursor search and invoke the search box using Control-F. and setthe value you wish to find Enter the other search parameters as required. Limit the search to the current field (i.e., the field with the focus when the search box was opened). (or only) record that matches the Press Find First to move to the first search condition. Home Previous 14 o f 33 Next
  • 134. 15. Advanced Triggers Tutorial exercises FIGURE 15.10: Create an unbound combo box. down themake roomfor the detail Drag to separator in the form header selecting the combocombo boxand Create an unbound box tool by clicking in the header area. Use the wizard in the usual way to get a list of valid DeptCode values and descriptions. The bound column for the combo box should be DeptCode. its value has to bebox is unbound, Since the combo stored for later use rather than stored in a field. Home Previous 15 o f 33 Next 15. Advanced Triggers Tutorial exercises 15.3.3.4 Automating the search procedure FIGURE 15.11: An unbound combo box. using a macro When we implement search functionality with a combo box, only two things are different from the manual search in Figure 15.9: 1. the search dialog box does not show up, and 2. the user selects the search value from the combo box rather than typing it in. The basic sequence of actions, however, remains Although the DeptCode column has been the same. As a result, the answer to the “what” ques- hidden, it is the “bound” column. As a result, the value of the combo box as it appears here tion is the following: is “COMM”, not “Commerce and ...” 1. Move the cursor to the DeptCode field (this allows the “Search Only Current Field” option to Code). The advantage of the prefix cbo is be used, thereby drastically cutting the search that it allows you to differentiate between the time). bound field DeptCode and the unbound 2. Invoke the search feature using the current value combo box. of cboDeptCode as the search value. Home Previous 16 o f 33 Next
  • 135. 15. Advanced Triggers Tutorial exercises 3. Move the cursor back to cboDeptCode or some FIGURE 15.13: Fill in the arguments for the other field. FindRecord action. The only problem with this procedure is that the DeptCode text box is disabled. As a result, you must include an extra step at the beginning of the macro mcrSearch.FindDepartment. Create a named macro called to set its Enabled property to Yes and another at the end of the macro to return it to its original state. • Create a new macro called mcrSearch.Find- Department. • Use the SetValue action to set the Dept- Code.Enabled property to Yes. This can be done using the expression builder, as shown in Figure 15.12. • Use the GotoControl action to move the cursor Since Value is the default to the DeptCode text box. Note that this action property, its use will fail if the destination control is disabled. is optional. • Use the FindRecord action to implement the search as shown in Figure 15.13. equalsthe action arguments. Dothe combo box. Enter sign before the name of not forget the Home Previous 17 o f 33 Next 15. Advanced Triggers Tutorial exercises FIGURE 15.12: Use the builder to specify the name of the property to set. expressionItem argument, down To set the builder to drill use the to the correct form. The middle pane shows all the objects on the form including labels and buttons (hence the need for a good naming convention). (cboDeptCode) from thebox Select the unbound combo middle pane. A list of properties for the selected object is displayed in the pane on the right. Home Previous 18 o f 33 Next
  • 136. 15. Advanced Triggers Tutorial exercises Access interprets any text in the Find What 15.3.4 Using Visual Basic code instead of argument as a literal string (i.e., quotation a macro marks would not be required to find COMM). To Instead of attaching a macro to the After Update use an expression (including the contents of a event, you can attach a VBA procedure. The VBA control) in the Find What argument, you must procedure is much shorter than its macro counter- precede it with an equals sign (e.g., part: =[cboDeptCode]. 1. a copy (clone) of the recordset underlying the • You cannot disable a control if it has the focus. form is created, Therefore, include another GotoControl action 2. the FindFirst method of this recordset is used to move the cursor to cboDeptCode before set- to find the record of interest. ting DeptCode.Enabled = No. 3. the “bookmark” property of the clone is used to • Attach the macro mcrSearch.FindDepart- move to the corresponding bookmark for the ment to the After Update event of the cboDept- form. Code combo box. To create a VBA search procedure, do the following: • Test the search feature. • Change the After Update event of cboDeptCode to “Event Procedure”. • Press the builder ( ) to create a VBA subrou- tine. Home Previous 19 o f 33 Next 15. Advanced Triggers Application to the assignment • Enter the two lines of code below, as shown in a non-human-readable data type and therefore is Figure 15.14. not of much use unless it is used in the manner Me.RecordsetClone.FindFirst shown here. Setting the Bookmark property of a “DeptCode = ‘” cboDeptCode “'” record makes the record with that bookmark the Me.Bookmark = current record. In the example above, the book- Me.RecordsetClone.Bookmark mark of the records underlying the form is set to This program consists of a number of interesting ele- equal the bookmark of the clone. Since the clone ments: had its bookmark set by the search procedure, • The property Me refers to the current form. You this is equivalent to searching the recordset can use the form's actual name, but Me is much underlying the form. faster to type. • A form’s RecordsetClone property provides a 15.4 Application to the assignment means of referencing a copy of the form's under- lying recordset. 15.4.1 Triggers to help the user • The FindFirst method is straightforward. It • Create a trigger on your order form that sets the acts, in this case, on the clone. actual selling price of a product to its default • Every recordset has a bookmark property that price. This allows the user to accept the default uniquely identifies each record. A bookmark is price or enter a new price for that particular trans- like a “record number”, except that it is stored as action (e.g., the item could be damaged). You will Home Previous 20 o f 33 Next
  • 137. 15. Advanced Triggers Application to the assignment FIGURE 15.14: Implement the search feature using a short VBA procedure. referencethe After Update event to Change an event procedure. editor.the builder button to invoke the VBA Press Access automatically names the subroutine. Enter the two lines of code. Home Previous 21 o f 33 Next 15. Advanced Triggers Application to the assignment have to think carefully about which event to Section 10.4). The problem is updating the Back- attach this macro to. Orders table itself because two different situations • Create a trigger on your order form that calcu- have to be considered: lates a suggested quantity to ship and copies this 1. A record for the particular customer-product value into the quantity to ship field. The sug- combination exists in the BackOrders table -- gested value must take into account the amount If a backorder record exists for a particular cus- ordered by the customer, any outstanding backo- tomer and a particular product, the quantity field rders for that item by that customer, and the cur- of the record can be added-to or subtracted-from rent quantity on hand (you cannot ship what you as backorders are created and filled. do not have). The user should be able to override 2. A customer-product record does not exist in this suggested value. (Hint: use the MinValue() the BackOrders table -- If the particular cus- function you created in Section 12.5.) tomer has never had a backorder for the product • Provide you customer and products forms with in question, then there is no record in the Back- search capability. Orders table to update. If you attempt to update a nonexistent record, you will get an error. 15.4.2 Updating the BackOrders table What is required, therefore, is a means of determin- Once a sales order is entered into the order form, it ing whether a record already exists for a particular is a simple matter to calculate the amount of each customer-product combination. If a record does product that should be backordered (you did this in exist, then it has to be updated; if a record does not Home Previous 22 o f 33 Next
  • 138. 15. Advanced Triggers Application to the assignment exist, then one has to be created. This is simple (see Section 15.3.2.4 to review renaming enough to talk about, but more difficult to implement fields in queries). in VBA. As a result, you are being provided with a shortcut function called UpdateBackOrders() Note that if the backordered quantity is positive, that implements this logic. items are backordered. If the backordered quantity is negative, backorders are being filled. If the backor- The requirements for using the UpdateBackO- dered quantity is zero, no change is required and rders() function are outlined in the following sec- these records should no be included in the results of tions: the query. 15.4.2.1 Create the pqryItemsToBackOrder 15.4.2.2 Import the shortcut function query Import the Visual Basic for Applications (VBA) mod- If you have not already done so, create the pqry- ule containing the code for the ItemsToBackOrder query described in UpdateBackOrders() function. This module is Section 10.4. The UpdateBackOrders() proce- contained in an Access database called dure sets the parameter for the query and then cre- BOSC_Vx.mdb that you can download from the ates a recordset based on the results. course home page. If you did not use the field names OrderID, • BOSC_V2.mdb is for those running Access ver- and ProductID in your tables, you must use sion 2.0. To import the module, select File the calculated field syntax to rename them Home Previous 23 o f 33 Next 15. Advanced Triggers Application to the assignment Import, choose BOSC_V2.mdb, and select Mod- ers, and Products. If any of your tables or fields ule as the object type to import. are named differently, an error occurs. To eliminate • BOSC_V7.mdb is for those running Access ver- these errors, you can do one of two of things: sion 7.0 or higher. To import the module, select 1. Edit the VBA code. Use the search-and-replace File Get External Data Import, choose feature of the module editor to replace all BOSC_V7.mdb, and select Module as the object instances of field names in the supplied proce- type to import. dures with your own field names. This is the rec- 15.4.2.3 Use the function in your application ommended approach, although you need an adequate understanding of how the code works The general syntax of the function call is: UpdateBackOrders(OrderID, CustomerID). in order to know which names to change. 2. Change the field names in your tables (and all The OrderID and CustomerID are arguments and queries and forms that reference these field they both must be of the type Long Integer. If this names). This approach is not recommended. function is called properly, it will update all the backo- rdered items returned by the parameter query. 15.4.3 Understanding the 15.4.2.4 Modifying the UpdateBackOrders() UpdateBackOrders() function function The flowchart for the UpdateBackOrders() func- The UpdateBackOrders() function looks for spe- tion is shown in Figure 15.15. This function repeat- cific fields in three tables: BackOrders, Custom- edly calls a subroutine, BackOrderItem, which Home Previous 24 o f 33 Next
  • 139. 15. Advanced Triggers Application to the assignment updates or adds the individual items to the BackO- FIGURE 15.15: Flowchart for rders table. The flowchart for the BackOrderItem UpdateBackOrders(). subroutine is shown in Figure 15.16. There are easier and more efficient ways of imple- start menting routines to update the BackOrders table. Although some amount of VBA code is virtually inev- run pqryItemsToBackOrder to get list of items to backorder itable, a great deal of programming can be elimi- nated by using parameter queries and action queries. Since queries run faster than code in is yes the list Access, the more code you replace with queries, the empty? error message stop better. no To get full marks for the backorders aspect of the assignment, you have to create a more do until end of list elegant alternative to the shortcut supplied here. call BackOrderItems (CustID,ProductID,Qty) stop Home Previous 25 o f 33 Next 15. Advanced Triggers Application to the assignment FIGURE 15.16: Flowchart for the BackOrderItem subroutine. start search BackOrders table for matching CustID ProductID yes yes check Products table to ensure valid ProductID found? update Qty stop no no check Customer table to valid? error message stop ensure valid CustID yes no add new record with CustID, ProductID Qty valid? error message stop stop Home Previous 26 o f 33 Next
  • 140. 15. Advanced Triggers Application to the assignment 15.4.4 Annotated source code for the MsgBox “Back order cannot be processed: backorders shortcut module. order contains no items” Exit Sub In the following sections, the two procedures in the End If shortcut module are examined. In each case, the Do Until rsBOItems.EOF code for the procedure is presented followed by Call BackOrderItem(lngCustID, comments on specific lines of code. rsBOItems!ProductID, rsBOItems!Qty) 15.4.4.1 The UpdateBackOrders() function rsBOItems.MoveNext Function UpdateBackOrders(ByVal Loop lngOrdID As Long, ByVal lngCustID As rsBOItems.Close Long) End Function Set dbCurr = CurrentDb 15.4.4.2 Explanation of the Dim rsBOItems As Recordset UpdateBackOrders() function dbCurr.QueryDefs!pqryItemsToBackOrder. Parameters!pOrderID = lngOrdID Function UpdateBackOrders(ByVal lngOr- Set rsBOItems = dID As Long, ByVal lngCustID As Long) — dbCurr.QueryDefs!pqryItemsToBackOrder This statement declares the function and its parame- .OpenRecordset() ters. Each item in the parameter list contains three If rsBOItems.RecordCount = 0 Then elements: ByVal or ByRef (optional), the variable's name, and the variable's type (optional). The ByVal Home Previous 27 o f 33 Next 15. Advanced Triggers Application to the assignment keyword simply means that a copy of the variables Dim rsBOItems As Recordset — In this decla- value is passed the subroutine, not the variable ration statement, a pointer to a Recordset object is itself. As a result, variables passed by value cannot declared. This recordset contains a list of all the be changed by the sub-procedure. In contrast, if a items to add to the BackOrders table. variable is passed by reference (the default), its dbCurr.QueryDefs!pqryItemsToBackOrder value can be changed by the sub-procedure. .Parameters!pOrderID = lngOrdID — This Set dbCurr = CurrentDb — Declaring a vari- one is a bit tricky: the current database (dbCurr) able and setting it to be equal to something are dis- contains a collection of objects called QueryDefs tinct activities. In this case, the variable dbCurr (these are what you create when you use the QBE (which is declared in the declarations section) is set query designer). Within the collection of QueryDefs, to point to a database object. Note that the database there is one called pqryItemsToBackOrder object is not created, it already exists. (which you created in Section 15.4.2.1). CurrentDb is a function supported in Access ver- Within every QueryDef, there is a collection of zero sion 7.0 and higher that returns a reference to the or more Parameters. In this case, there is one called current database. In Access version 2.0, this function pOrderID and this sets the value of the parameter does not exist and thus the current database must to the value of the variable lngOrderID (which was be found by starting at the top level object in the passed to the function as a parameter). Access DAO hierarchy, as discussed in Set rsBOItems = dbCurr.QueryDefs!pqry- Section 14.3.1. ItemsToBackOrder.OpenRecordset() — Here Home Previous 28 o f 33 Next
  • 141. 15. Advanced Triggers Application to the assignment is another set statement. In this one, the variable MsgBox “Back order cannot be processed: rsBOItems is set to point at a recordset object. order contains no items” — The MsgBox Unlike the current database object above, however, statement pops up a standard message box with an this recordset does not yet exist and must be created Okay button in the middle. by running the pqryItemsToBackOrder parame- Exit Sub — If this line is reached, the list contains ter query. no items. As such, there is no need to go any further OpenRecordset is a method that is defined for in this subroutine. objects of type TableDef or QueryDef that creates an End If — The syntax for If… Then… Else… state- image of the data in the table or query. Since the ments requires an End If statement at the end of query in question is a parameter query, and since the the conditional code. That is, everything between the parameter query is set in the previous statement, the If and the End If executes if the condition is true; resulting recordset consists of a list of backordered otherwise, the whole block of code is ignored. items with an order number equal to the value of Do Until rsBOItems.EOF — The EOF property pOrderID. of a recordset is set to true when the “end of file” is If rsBOItems.RecordCount = 0 Then — The encountered. only thing you need to know at this point about the Call BackOrderItem(lngCustID, rsBOI- RecordCount property of a recordset is that it returns tems!ProductID, rsBOItems!Qty) — A sub- zero if the recordset is empty. routine is used to increase the modularity and Home Previous 29 o f 33 Next 15. Advanced Triggers Application to the assignment readability of this function. Note the way in which the 15.4.4.3 The BackOrderItem() subroutine current values of ProductID and Qty from the Sub BackOrderItem(ByVal lngCustID As rsBOItems Recordset are accessed. Long, ByVal strProdID As String, ByVal rsBOItems.MoveNext — MoveNext is a method intQty As Integer) Set dbCurr = CurrentDb defined for recordset objects. If this is forgotten, the EOF condition will never be reached and an infinite Dim strSearch As String Dim rsBackOrders As Recordset loop will be created. In VBA, the Escape key is usu- Set rsBackOrders = ally sufficient to stop an infinite loop. dbCurr.OpenRecordset(“BackOrders”, Loop — All Do While/Do Until loops must end dbOpenDynaset) with the Loop statement. strSearch = “CustID = “ lngCustID “ rsBOItems.Close — When you create a new AND ProductID = ' strProdID “'” object (such as a Recordset using the Open- rsBackOrders.FindFirst strSearch Recordset method), you should close it before exit- If rsBackOrders.NoMatch Then ing the procedure. Note that you do not close Dim rsCustomers As Recordset dbCurr because you did not open it. Set rsCustomers = dbCurr.OpenRecordset(“Customers”, End Function — All functions/subroutines need dbOpenDynaset) an End Function/End Sub statement. strSearch = “CustID = “ lngCustID rsCustomers.FindFirst strSearch Home Previous 30 o f 33 Next
  • 142. 15. Advanced Triggers Application to the assignment If rsCustomers.NoMatch Then rsBackOrders!Qty = intQty MsgBox “An invalid Customer ID number rsBackOrders.Update has been passed to BackOrderItem” Else Exit Sub rsBackOrders.Edit End If rsBackOrders!Qty = rsBackOrders!Qty + Dim rsProducts As Recordset intQty Set rsProducts = rsBackOrders.Update dbCurr.OpenRecordset(“Products”, End If dbOpenDynaset) End Sub strSearch = “ProductID = ' strProdID “'” 15.4.4.4 Explanation of the BackOrderItem() rsProducts.FindFirst strSearch subroutine If rsProducts.NoMatch Then Since many aspects of the language are covered in MsgBox “An invalid Product ID number the previous subroutine, only those that are unique has been passed to BackOrderItem” to this subroutine are explained. Exit Sub Set rsBackOrders = dbCurr.OpenRecord- End If set(“BackOrders”, dbOpenDynaset) — The rsBackOrders.AddNew OpenRecordset method used here is the one rsBackOrders!CustID = lngCustID defined for a Database object. The most important rsBackOrders!ProductID = strProdID argument is the source of the records, which can be Home Previous 31 o f 33 Next 15. Advanced Triggers Application to the assignment a table name, a query name, or an SQL statement. do this, single quotes are used within the search The dbOpenDynaset argument is a predefined con- string. stant that tells Access to open the recordset as a rsBackOrders.FindFirst strSearch — dynaset. You don't need to know much about this FindFirst is a method defined for Recordset except that the format of these predefined constants objects that finds the first record that meets the crite- is different between Access version 2.0 and version ria specified in the method's argument. Its argument 7.0 and higher. In version 2.0, constants are of the is the text string stored in strSearch. form: DB_OPEN_DYNASET. If rsBackOrders.NoMatch Then — The strSearch = “CustID = ” lngCustID “ NoMatch property should always be checked after AND ProductID = ’” strProdID “'” — searching a record set. Since it is a Boolean variable A string variable has been used to break the search (True / False) it can be used without an comparison process into two steps. First, the search string is operator. constructed; then the string is used as the parameter rsBackOrders.AddNew — Before information can for the FindFirst method. The only tricky part here be added to a table, a new blank record must be cre- is that lngCustID is a long integer and strProdID ated. The AddNew method creates a new empty is a string. The difference is that the value of str- record, makes it the active record, and enables it for ProdID has to be enclosed in quotation marks when editing. the parameter is passed to the FindFirst method. To Home Previous 32 o f 33 Next
  • 143. 15. Advanced Triggers Application to the assignment rsBackOrders!CustID = lngCustID — Note the syntax for changing a variable’s value. In this case, the null value of the new empty record is replaced with the value of a variable passed to the subroutine. rsBackOrders.Update — After any changes are made to a record, the Update method must be invoked to “commit” the changes. The AddNew / Edit and Update methods are like bookends around changes made to records. rsBackOrders.Edit — The Edit method allows the values in a record to be changed. Note that these changes are not saved to the underlying table until the Update method is used. Home Previous 33 o f 33 Next