+ All Categories
Home > Documents > Access and SQL

Access and SQL

Date post: 03-Jun-2018
Category:
Upload: sirupsegar
View: 224 times
Download: 0 times
Share this document with a friend

of 58

Transcript
  • 8/12/2019 Access and SQL

    1/58

    Access and SQLPart 1: Setting the SQL Scene

    This is the first in a series of tutorials demonstrating how you can use SQLto build a betterdatabase. The tutorials are not intended to be a course on SQL. There are many excellentbooks and online tutorials on the subject, some of which are listed below.

    In this tutorial I review the various tasks that SQL is used for in ccess and answer some of the!uestions that I asked when I started to ex"lore the language.

    #hat is SQL$

    #hat is SQL for$

    %an SQL do things that the Query &esign tool can't$

    &o I need to know SQL$

    (nline resources for SQL.

    )ooks on SQL.

    What is SQL?

    SQL is Structured Query Language. Some "eo"le say *+ss Queue +ll* and others "refer*Se!uel*. SQL has been around for a while. It started life in the late -/s when com"uterdatabase designers needed a language they could use to talk to the first relational databases0ones in which the data was stored in multi"le, linked tables 1 ccess is a relational database2.The first SQL standard was "ublished by 3SIin -45 and it has been u"dated several times

    since then. lthough it is intended to be a standard language, many *dialects* exist. 6icrosoftccess uses a dialect called 7et SQL whereas its cousin 6icrosoft SQL Server uses T1SQL.)ut the core language is su""orted by many "rograms and is essentially sim"le and easy tolearn.

    n SQL statement might look something like this8

    S+L+%T tblStaff.9 :;(6 tblStaff #*6*?

    This statement says *show me all the fields from the tblStaff table for record where the =enderfield is '6'.* This is a sim"le exam"le but it illustrates how easy the SQL language is to

    understand.

    @ to"

    What is SQL for?

    SQL is used to interact with your database's data. ccess uses SQL for many tasks8 whenevera !uery is run it uses SQL to filter the data? whenever a re"ort is dis"layed SQL is used togather the data to be dis"layed? SQL "rovides the data dis"layed on an ccess form.

    Running Queries

    ccess "rovides the user with a friendly interface, the !uery &esign Aiew, for building !ueries.This view offers a gra"hical re"resentation of the !uery and the user re!uires no knowledge ofSQL to use it. #hen the user *runs* the !uery ccess translates the gra"hical re"resentationinto an SQL statement which it "asses to its 7et &atabase +ngine. 7et returns the a""ro"riatedata which ccess dis"lays in the !uery &atasheet Aiew.

    http://www.fontstuff.com/access/acctut14.htm#whatissqlhttp://www.fontstuff.com/access/acctut14.htm#whatssqlforhttp://www.fontstuff.com/access/acctut14.htm#cantdohttp://www.fontstuff.com/access/acctut14.htm#needtoknowhttp://www.fontstuff.com/access/acctut14.htm#sqlonlinehttp://www.fontstuff.com/access/acctut14.htm#sqlbookshttp://www.fontstuff.com/access/acctut14.htm#sqlbookshttp://www.fontstuff.com/access/acctut14.htm#tophttp://www.fontstuff.com/access/acctut14.htm#whatissqlhttp://www.fontstuff.com/access/acctut14.htm#whatssqlforhttp://www.fontstuff.com/access/acctut14.htm#cantdohttp://www.fontstuff.com/access/acctut14.htm#needtoknowhttp://www.fontstuff.com/access/acctut14.htm#sqlonlinehttp://www.fontstuff.com/access/acctut14.htm#sqlbookshttp://www.fontstuff.com/access/acctut14.htm#top
  • 8/12/2019 Access and SQL

    2/58

  • 8/12/2019 Access and SQL

    3/58

    Specifying the Recordset %isplayed by a !or" or Report

    #hen you build a form or re"ort, the "ur"ose of which is to dis"lay data, you have to s"ecifythe recordset on which it is based. This information is stored as the object'sRecordset"ro"erty. (nce set, this "ro"erty can not be changed by the user without going into the object's

    design view, which re!uires knowledge of form or re"ort design and is time1consuming.

    lthough you are unlikely to want to change the recordset "ro"erty of a form it is common fordatabase users to want a standardised re"ort design. 6any "eo"le deal with this by creatingmulti"le co"ies of the re"ort, but with A) you can use just one re"ort and change its recordsetas many times as you want, sim"ly by creating an SQL statement for each re"ort you want todis"lay.

    These are just some of the things that SQL is be used for in an ccess database.

    @ to"

    &an SQL do things that the Query %esign tool can't?

    ccess uses SQL to "erform all the data functions of its Query &esign tool, including thevarious *action* !ueries 06ake Table, ""end, D"date and &elete2. ll these functions can beachieved using very sim"le A) statements combined with SQL without the need to use the!uery design tool or to maintain any stored !ueries.

    There a number of functions that can be "erformed using SQL that can not be re"resented bythe Q)+grid 0Q)+ > Query$y(xam"le2 and can only be executed by creating the SQL

    manually, either by entering it into the SQL view window or by using A). ccess refers tothese functions as SQL Specific Queries. ccess lists these on the Querymenu8

    There are three kinds of SQL S"ecific !ueries8 the Union Query, the Pass-Through Queryandthe Data Definition Query.

  • 8/12/2019 Access and SQL

    4/58

    running on a network server. The !uery is designed in the SQL view of ccess 0or with A)2but when run it is sent direct to the server where it is executed, by"assing the ccess 7etengine. The result is returned to ccess and dis"layed in the normal way, and the need to havea linked table in the ccess database is eliminated.

    )he %ata %efinition Query

    &ata &efinition !ueries o"en u" a com"letely different range of "ossibilities. They are used tocreate and modify tables. :ields can be defined and their "ro"erties s"ecified. :ields and tablescan be deleted. ;elationshi"s and indexes can be created and defined.

    &ata &efinition !ueries are a very "owerful tool in the SQL language and can "erform manytasks on the structure of a database without recourse to A) "rogramming.

    SQL &an ,a-e Query %esign (asier.

    The Q)+ grid of the Query design window is a very useful tool, but sometimes it is easier towrite SQL directly into the SQL Aiew than to try to re"resent it on the grid. n exam"le of this iss"ecifying the sort order of a !uery.

  • 8/12/2019 Access and SQL

    5/58

    To get this result in using the Q)+ grid you have to enteradditional columns 0remembering to uncheck their *show*o"tion2. This is a very sim"le exam"le. #ith multi"lecolumns and a com"lex sort order there is a lot more todo.

    #hatever way you do it the result is the same. The data isdis"layed in the order Firstname, Lastnamebut the sortorder is Lastname, Firstname.

    3(T+8 #hen you make changes the !uery's SQL viewccess modifies the Q)+ grid to re"resent the new SQLstatement gra"hically.

    @ to"

    %o / need to -now SQL?

    6ost database users don't need to know SQL. nyone who has built a anything but the mostbasic of !ueries using the ccess !uery design window has already been using SQL withoutknowing it. %riteria like8 Between #0!0!"00# $%D #0!0&!"00#or %ot'(Lon)on(*or+n'(Lon)on(, (Paris(, (%ewor.(*are all "hrases from the SQL language.

    ccess contains many tools and wiGards that he" the user create a "owerful database withouthaving to learn SQL. )ut if you are at all serious about database building 0and the fact that youare reading this suggests that you areF2 a knowledge of SQL will hel" you build better, more

    "owerful databases. So my answer is an em"hatic *C+SF*.

    )ut don't "anic... this doesn't mean that you have to go on an SQL course right away, or evenbuy a book 0although there are "lenty of excellent books and online resources on the subject2. Istarted learning SQL by building !ueries in the ccess !uery design window, then looking atthe SQL that was ccess generated in the SQL Aiew. It's an excellent way to learn the basics.nd if you follow this series of tutorials you should learn enough to hel" you figure out the restyourself.

    @ to"

    #nline Resources for SQL

    There is "lenty of SQL reference material available free on the web. 7ust go to your favouritesearch engine and ty"e in *SQL tutorial* for a 0large2 selection. I had "lanned to include aselection here but most of them are "retty turgid and don't make easy reading. #hilst I su""oseit isn't fair to com"lain when it's free, it is often difficult to find the SQL amongst the "lethora ofadverts and "o"1u"s. nyway, you've found me so you're in the best "laceF

    :or an overview of SQL try W0 Schools + Learn SQLwhich has introductory and advancedSQL tutorials athtt"8HHwww.wschools.comHs!lH

    Access and SQLPart : Putting 2$A and SQL )ogether

    http://www.fontstuff.com/access/acctut14.htm#tophttp://www.fontstuff.com/access/acctut14.htm#tophttp://www.w3schools.com/sql/http://www.w3schools.com/sql/http://www.w3schools.com/sql/http://www.fontstuff.com/access/acctut14.htm#tophttp://www.fontstuff.com/access/acctut14.htm#tophttp://www.w3schools.com/sql/http://www.w3schools.com/sql/
  • 8/12/2019 Access and SQL

    6/58

    In the first tutorial in this series on ccess and SQLI ex"lained where SQL fitted into theoverall ccess "icture. This second tutorial introduces some SQL basics, those essential rulesyou really need to know when working with SQL in your ccess databases. This series oftutorials concentrates on combining SQL with A)to hel" build more "owerful, flexible anduser1friendly databases.

  • 8/12/2019 Access and SQL

    7/58

    %on't S-i"p on /nfor"ation

    #henever a field is s"ecified you have the o"tion to a""end the table name, se"arating the twowith a dot.

    S1L1CT Firstname, Lastname F259 t3lStaff 52D12 B Lastname

    is the same as8

    S1L1CT t3lStaff4Firstname, t3lStaff4Lastname F259 t3lStaff 52D12 B t3lStaff4Lastname

    "roviding that the fields belong to the data source s"ecified in the :;(6 clause. If your !ueryrefers to more than one table you must include the table name along with the field name.

    %ata )ype Qualifiers

    #hen su""lying values to an SQL statement, for exam"le as !uery criteria, their data ty"emust be correctly defined by a *!ualifier*. This is done by enclosing the value between a "air ofa""ro"riate characters.

    )e4tmust be enclosed in either single !uotes 0'2 or double !uotes 052, for exam"le8

    /121 t3lStaff4Department 7 (9ar.eting8

    or

    /121 t3lStaff4Department 7 :9ar.eting;

    %ateshould be enclosed in hash marks 062 also called "ound or number signs, for exam"le8

    /121 t3lStaff4BirthDate 7 #0

    /121 t3l+n>oi6es4+n>oi6e%um3er ? =00

    7et the %ate !or"at Right

    &ates in SQL must be written in the DS date format 0"onth8day8year 2. This is im"erativeregardless of the default date format settings on your com"uter. The ccess !uery design

    window acce"ts dates in your local default format but it converts the date you ty"e to thecorrect format when it builds the SQL statement.

    Re"e"ber the Se"icolon.

    n SQL statement must finish with a semicolon 092. If you omit the semicolon when writing anSQL statement in the SQL view of the ccess !uery design window your !uery will still work

    because ccess corrects the error for youF Cou must remember to include it when writing SQLin A) and elsewhere.

    @ to"

    7etting 2$A to Spea- SQL

    http://www.fontstuff.com/access/acctut15.htm#tophttp://www.fontstuff.com/access/acctut15.htm#top
  • 8/12/2019 Access and SQL

    8/58

    A) and SQL are different things. A) is a full1blown "rogramming language that you can useto get ccess 0and other 6icrosoft (ffice "rograms2 to do just about anything you want. SQL isa language used exclusively to mani"ulate the data and structure of a database.

    A) calls on a vast range of objects, "ro"erties, methods, functions and constants to construct

    the sometimes com"lex statements used to control the "rogram. SQL uses a limited range of*keywords* combined with information you su""ly, such as table names, field names andcriteria, to construct essentially sim"le 0although sometimes long2 statements detailing whatyou want the "rogram to do with your data.

    SQL can often be used alone, for exam"le when setting the 2e6or)Sour6e"ro"erty of a formor re"ort in design view, or when working in the SQL @iewof the ccess !uery design window.)ut this tutorial is about how to combine SQL with A). Its aim is ex"lain the rules of SQL andto encourage you to use good code1writing "ractice and to avoid the "itfalls and "roblems thatcan occur. The way you write your code is a very "ersonal thing so I'm going to show you how Ido things, using some techni!ues I have learnt from others and some I've figured out myself.

    Cou don't have to do it my way, but it works for me so it's what I teachF

    A) is a very flexible language and there are often many different ways in which A) canachieve the same task. SQL on the other hand is a very "recise and inflexible language.+verything has to be just so, but it has the advantage of also being very sim"le. s I ex"lainedin Eart 8 Setting the SQL Scenethere are several dialects of SQL.

  • 8/12/2019 Access and SQL

    9/58

    Sele6t t3lStaff4Firstname, t3lStaff4Lastname from t3lStaff where t3lStaff45ffi6e7(Paris8A

    S1L1CT t3lStaff4Firstname, t3lStaff4Lastname F259 t3lStaff /121 t3lStaff45ffi6e7(Paris8A

    I am using sim"le exam"les here but imagine trying to read an SQL statement that was ten

    times as long as these 03(T+8 the maximum length of an SQL statement in A) is K,54charactersF2.

    (nclose !ield

  • 8/12/2019 Access and SQL

    10/58

    There is a "roblem with nested !uotes in the #

  • 8/12/2019 Access and SQL

    11/58

    Cou want to allow the user to choose a value for the 5ffi6ecriteria each time the !uery is run,so you build a dialog box in which there is a combo box containing a list of (ffices. The combobox is named 63o5ffi6e. Cou can insert a reference to the value of the combo box directly intothe SQL statement8

    lternatively, you can "lace the value of the combo box into a variable and then insert thevariable into the SQL statement8

    Dsing a variable can make the SQL statement code easier to read and understand, es"ecially

    when there are several variable criteria to consider. It is sometimes essential to use thismethod when the value has to be examined or mani"ulated in some way before it is "assed tothe SQL.

    #hatever method you choose, you must remember to include any necessary data ty"e!ualifiers in the SQL string. In the illustration below, a single !uote mark is included in the SQLstring either side of the text variable 0marked with red arrows28

    lternatively, the S%II character code for the double !uote mark 0Chr'E*2 can be insertedeither side of the text variable, but outside the SQL string. This method re!uires more ty"ingbut avoids conflicts and confusion arising from nesting !uotes.

    ;emember that as with *hard1coded* criteria, variables re!uire the correct !ualifiers for theirdata ty"e8 !uotes for text, hash1marks 0"ound signs2 for dates, and nothing for numbers.

    @ to"

    %ebugging >our SQL &ode

    s with any other sort of "rogramming, you SQL code can fail to work "ro"erly. It might bebecause you made a logic error, or got the SQL syntax wrong, or "erha"s you just made aty"o. If this results in workable code it might not "roduce the result you were ex"ecting. 6ostoften though the result is code that won't run and ccess throws u" an error. Cour job is tofigure out what went wrong and "ut it right.

    http://www.fontstuff.com/access/acctut15.htm#tophttp://www.fontstuff.com/access/acctut15.htm#top
  • 8/12/2019 Access and SQL

    12/58

    If you are running an SQL statement from within a A) "rocedure you will see the regularAisual )asic error message. Sometimes these are !uite difficult to inter"ret.

    trick used by many ccess develo"ers is to test their SQL in the SQL Aiew of the ccess!uery design window. If there is a "roblem ccess will dis"lay an error message. The error

    messages you get from the SQL Aiew of the ccess !uery tool are often far more hel"ful anddescri"tive that those you get from A)F

    SQL (rror ,essages

    It "ays to familiarise yourself with the different sorts of message so that you can !uickly tracethe source of code errors. 6ost SQL errors are syntax errors. The 7et database engine can'tinter"ret the SQL statement because it doesn't make sense. These often arise from sim"lety"ogra"hical errors or omissions so it is im"ortant, as with most com"uter "rogramming, totake care when ty"ingF

  • 8/12/2019 Access and SQL

    13/58

    3ot really an error message, but a res"onse to an error in the SQL statement. If you ty"e thename of a field incorrectly, the 7et database engine sometimes inter"rets your SQL as a"arameter !uery and dis"lays the familiar "arameter dialog. lthough this might seemconfusing at first, it is usually !uite easy to diagnose and correct because the offending name isdis"layed on the dialog. Cou just need to find it in your code and correct it8

    2$A (rror ,essages

    #hen you try to run a faulty SQL statement from A) it will usually generate a run1time errorresulting in a error A) message like this one8

    The error messages are delivered in the usual way using the Aisual )asic error message dialogand don't ex"licitly state that the "roblem with your code lies in your SQL statement, althoughthis is usually evident from the message itself. Eressing the%ebugbutton will take you to the

    offending line of code but this may not be the SQL statement itself.

  • 8/12/2019 Access and SQL

    14/58

    In the exam"le above the code crashed when it tried to a""ly the SQL statement to a stored!uery. ccess checked the SQL statement before a""lying it to the !uery and found a syntaxerror 0*(;&+;* should be *(;&+; )C*2 and highlighted the code line that it could notexecute, rather than the one that contained the error.

    In the next exam"le, it is clear that there is a s"elling error somewhere but it might take a whileto find8

  • 8/12/2019 Access and SQL

    15/58

  • 8/12/2019 Access and SQL

    16/58

    Last%ame T1HT'0*, BirthDate D$T1T+91*A(

    . Switch to the ccess database window 0"ress !112 and move to the )ablestab.03(T+8 if the Tables tab was already dis"layed, refresh the view by switching to adifferent tab then back to the Tables tab again2. Cou should see that a new table

    0t3lTest2has been created.

    Take a look at the table. Cou will see that it contains the four fields s"ecified in the SQLstatement8

    Switch it into design view and see that the data ty"es are as s"ecified, with the text field of as"ecified siGe, and that the Staff+Dfield is an autonumber field and also the primary .ey field8

    If you try to run the same line of code again an error occurs because a table with the s"ecified

    name already exists8

    method for dealing with this eventuality will feature in a later tutorial in this series.

    Add Records to a )able

    Lets add some data to the table. %lose the table if it is o"en, and return to the +mme)iate/in)ow.

    . +nter the following line of code as a single line, then "ress (nter 0feel free to insertyour own detailsF28

    DoCm)42unSQL (+%S12T +%T5 t3lTest 'First%ame, Last%ame, BirthDate*@$LU1S ':9artin:, :Ireen:, #0

    K. Switch to the ccess database window and o"en the table. Cou will see your newrecord. )ecause the Staff+Dfield is an autonum3erfield its value is assignedautomatically. It does not need to be s"ecified in the SQL.

  • 8/12/2019 Access and SQL

    17/58

    )efore the SQL is executed, ccess dis"lays a message asking "ermission to add a record tothe table. This is usual when ccess "erforms any action !uery, and can be su""ressed withA) code if you don't want your users to see it8

    If the user decides not to a""end the record they can click the

  • 8/12/2019 Access and SQL

    18/58

    In addition to working with the structure of a table, SQL can be used to modify existing data.Cou may have used an ccess D"date Query. This exam"le uses the same method from A).#e have added a new field to the table, now we can enter some data.

    :irst, an exam"le of u"dating s"ecific records by adding a #

  • 8/12/2019 Access and SQL

    19/58

    . +nter the following line of code as a single line into the +mme)iate /in)ow, then "ress(nter8

    DoCm)42unSQL (D25P T$BL1 t3lTestA(

    Cou won't see any warning message, but you will find that the table has gone 0a bit too easy forcomfortF2. Cou might need to refresh the database window as described earlier before thetable's entry is removed.

    Su""ary

    These "ractical exam"les have demonstrated how you can mani"ulate a database's structureand its data by im"lementing SQL statements with A), working inde"endently of the ccess!uery tool. They show the "otential of working directly with SQL from your A) "rocedures tobuild, modify and "o"ulate tables with ease.

    I have shown only a few exam"les of what can be done. SQL is ca"able of a great deal more.:uture tutorials in this series will ex"lore "ractical uses for these techni!ues, as well as themore familiar uses of SQL to interrogate data and su""ly the user with information.

    Access and SQLPart @: $uilding Queries 5#n the !ly5

    This tutorial is about using SQL to build !ueries *on the fly* 0or as we "ro"ellorheads say8 *at

    run1time*2. This means that you build the !ueries when you need them, rather than trying toantici"ate the user's needs and "re"aring them in advance.

    The tutorial will deal with regular *select* !ueries, ones which filter the source data and showthe result to the user 0as o""osed to *action* !ueries which mani"ulate the data in some way2.

    Cou can download a co"y of the database used in this tutorial. It contains com"leted exam"lesof the forms, !ueries and code described in the tutorial. :ollow the link at the bottom of this"age. The database contains a table listing the details of the staff of a fictional multinationalcom"any. It contains the sort of "ersonal details you might ex"ect such as First%ame,Last%ame,BirthDateand Ien)ertogether with business details such as 5ffi6e, Department,

    Ko3Titleand 1mail.

    This tutorial is in two "arts. This first "art will show you how to create a fully working multi1"ur"ose !uery. The second "art will ex"lain how to add some refinements to create a really"rofessional !uery tool. Cou will find a link to the second "art of the tutorial at the bottom of this"age.

    Why $uild Queries on the !ly?

    Like many ccess develo"ers, I tend to create very few stored !ueries. Instead I try to create a

    small number of general "ur"ose !ueries that can be changed on demand to suit the user'sre!uirements. This allows my databases to be much more flexible and I don't have to guess

    what the users might want to know. I can then use switchboards and dialog boxes to gather theinformation from the user which is used to create the !uery's SQL statement. The user is reallybuilding a !uery themselves but they don't need to know anything about ccess to do it.

    nother im"ortant reason for working this way is that in!uisitive 0or carelessF2 users mightdelete or change stored !ueries, and not know how to re"lace them.

    http://www.fontstuff.com/access/acctut17.htm#donehttp://www.fontstuff.com/access/acctut17.htm#donehttp://www.fontstuff.com/access/acctut17.htm#donehttp://www.fontstuff.com/access/acctut17.htm#done
  • 8/12/2019 Access and SQL

    20/58

    $uilding a ,ulti+Purpose Query

    )he Plan

    The aim of this "roject is to create a single stored !uery whose criteria can be changed to suitthe user's re!uirements. The !uery will be o"ened when the user clicks a button on a dialogbox. The dialog box will also be used to gather the criteria from the user.

    )he Stored Query

    Cou need a !uery that can be used as the basis of our multi1"ur"ose !uery. Its design iscom"letely irrelevant because it is going to be changed each time it is used, but ccess doesn'tlet you create an *em"ty* !uery so you'll have to make something u" 0anything will do2.

    sk ccess for a new !uery in design view, add a table, "ut a field into the grid and then close

    and save the !uery. =ive it a sensible name 1 in this exam"le I am calling the !ueryryStaffListQuery.

    )he %ialog $o4

    I have decided that my users will "robably want to !uery on three different criteria8 5ffi6e,Departmentand Ien)er. So, the first ste" is to build a dialog box to hel" the users s"ecify theircriteria. It's u" to you what your dialog box looks like and what it contains. I have chosen to usecombo boxes showing lists of all the "ossible criteria choices. :uture tutorials in this series willshow exam"les of other design methods.

    If you are not ex"erienced in building dialog forms like this one, take a look at my tutorial%ustomiGing ccess Earameter Querieswhich contains detailed ste"1by1ste" instructions.

    Eoint at the labels next to the combo boxes in the illustration below to see what is contained ontheir lists...

    So, now we have the re!uired com"onents of the multi1"ur"ose !uery. The next ste" is to writethe code to make them work together.

    Writing the 2$A and SQL &ode#hen the user clicks the dialog's #;button several things must ha""en8

    =ather the user's choices from the combo boxes and write them into an SQL

    statement. ""ly the SQL statement to the stored !uery.

    ("en the stored !uery.

    %lose the dialog box.

    http://www.fontstuff.com/access/acctut08.htmhttp://www.fontstuff.com/access/acctut08.htmhttp://www.fontstuff.com/access/acctut08.htm
  • 8/12/2019 Access and SQL

    21/58

    The code to carry out these o"erations will run on the #n &lic-event of the #;button.

    In form design view right1click the #;button and choose Propertiesto o"en its "ro"ertieswindow and locate #n &lic-on the (ventstab. %lick in the white bar then click the $uildbutton8 . In the &hoose $uilderdialog select &ode $uilderand click #;. Cou are now

    ready to write the code...

    %eclare and !ill the 2ariables

    The first few lines of code establish contact with the database, telling ccess that we arereferring to the current database 0i.e. the one containing the code2 and identifying the !uerythat we are going to work on. In addition, a string 0i.e. text2 variable is declared, which I havecalled strSQL. It will hold the SQL statement that will be a""lied to the !uery8

    Dim )3 $s D$54Data3ase Dim )f $s D$54QueryDef Dim strSQL $s String Set )3 7 CurrentD3 Set )f 7 )34QueryDefs'(ryStaffListQuery8*

    3(T+8 I am using &(language here because I think it is sim"ler for this sort of work. &( isthe default for ccess -, but the default for ccess K///HK//K is &(. ccess - users needdo nothing 0you can omit the *%A#* bits if you want but it doesn't really matter2 but ccessK///HK//K users need to set a reference to &( so that their database understands the code.In the Aisual )asic +ditor go to )ools References. In the dialog box scroll down to *9i6rosoftD$5 4 53Me6t Li3rary* 0whereis the highest number if you have more than one2 and "ut a

    tick in the box. %lick #;to set the reference. Cou only need to do this once for the databaseand any code you "ut in it will be able to use the reference.

    $uild the SQL State"ent

    3ext comes a A) statement which "laces a text string into the strSQLvariable. There was adetailed ex"lanation of how I like to write my A)HSQL and the rules you need to know in thesecond tutorial in this series8 ccess and SQL Eart K8 Eutting A) and SQL Together.

    This code combines SQL keywords and clauses into which have been "laced references to thecombo boxes that contain the user's criteria choices8

    strSQL 7 (S1L1CT t3lStaff4 8 N O (F259 t3lStaff 8 N O (/121 t3lStaff45ffi6e7:( N 9e463o5ffi6e4@alue N (; 8 N O ($%D t3lStaff4Department7:( N 9e463oDepartment4@alue N (; 8 N O ($%D t3lStaff4Ien)er7:( N 9e463oIen)er4@alue N (; 8 N O (52D12 B t3lStaff4Last%ame,t3lStaff4First%ameA8

    lthough it doesn't seem to make a readable SQL statement as it is, when ccess reads thecode and substitutes, for exam"le, 9e463o5ffi6e4@aluewith Lon)ona sensible SQL statementresults.

  • 8/12/2019 Access and SQL

    22/58

    3ow is a good time to test the code you have written so far and there are a cou"le of ways youcan do this. Cou can *"rint* the SQL to the +mme)iate /in)owor you can dis"lay it in amessage box 0or you can do bothF2.

  • 8/12/2019 Access and SQL

    23/58

    choosing 2iew SQL 2iew. &elete any entry that is already there 0it usually shows S1L1CTA2and "aste in your SQL statement. ;un the !uery and check the result.

    If you see an error message when you try to run your SQL you can trace the error and correctit. ;ead the section on*&ebugging Cour SQL %ode* in Eart K of this series. #hen you aresatisfied that this "art of your code is working "ro"erly, you can remove the line0s2 De3ug4PrintstrSQLor 9sgBo strSQL.

    *pdate and #pen the Query

    ll that remains is to a""ly the SQL statement to the stored !uery that you saved earlier, and toclose the dialog box.

    +nter the line8

    )f4SQL 7 strSQL

    to a""ly your new SQL statement to the stored !uery. There is no need to give a command tosave this change to the !uery because this ha""ens automatically. 3ext add the lines8

    DoCm)45penQuery (ryStaffListQuery( DoCm)4Close a6Form, 9e4%ame

    to o"en the !uery dis"laying the results of the user's criteria choices, and to close the dialog.:inally add the lines8

    Set )f 7 %othing Set )3 7 %othing

    which em"ty the variables used to identify the !uery and the database. ll variables normallylose their values when a "rocedure finishes, and the memory that was allocated to them isfreed. )ut sometimes ccess forgetsto clear *object* variables 0those with which you have touse the *Set* keyword2 so it is good coding "ractice to clear them manually like this, just to

    make sure. Cour finished code should look like this Nclick the thumbnail to see a full1siGedimageO8

    ;eturn to the ccess database window and save the dialog box form 0to save your codechanges2.

    Bob %one.

    Cour 6ulti1Eur"ose Query is now ready to run. ;emember that the !uery should be run fromthe dialog box. If you o"en the stored !uery it will dis"lay records using the same criteria as thelast time it was run.

    The 6ulti1Eur"ose Query will work fine as it is, but you can make it even more user1friendlywith the addition of a few refinements. The second "art of this tutorial shows you how to turnyour multi1"ur"ose !uery into a really "rofessional tool.

    http://www.fontstuff.com/access/acctut15.htm#debugSQLhttp://www.fontstuff.com/access/acctut15.htm#debugSQLhttp://www.fontstuff.com/images/acctut17g.gifhttp://www.fontstuff.com/images/acctut17f.gifhttp://www.fontstuff.com/access/acctut15.htm#debugSQL
  • 8/12/2019 Access and SQL

    24/58

    Access and SQLPart @: $uilding Queries 5#n the !ly5

    CcontinuedDAdding So"e Refine"ents to the ProEect

    The 6ulti1Eur"ose Query will work fine as it is, but you can make it even more user1friendlywith the addition of a few refinements. The second "art of this tutorial shows you how to turnyour multi1"ur"ose !uery into a really "rofessional tool.

    These refinements deal with the "otential "roblems that could occur if the user doesn't use the!uery in the way that you ex"ected, and offers additional functionality8

    Let the user leave one or more combo boxes blank.

  • 8/12/2019 Access and SQL

    25/58

    )ecause of the way the code was written, the criteria for the Ien)erfield goes into the SQLstatement as8 t3lStaff4Ien)er7:; . The user left the combo box em"ty so when its value wasinserted into the SQL statement it a""eared as a "air of !uote marks with nothing in between0i.e. a Gero length string2 which gets inter"reted as *3othing*. Since everyone in the list has agender there are no records to dis"lay.

    3(T+8 when a field in a record is left em"ty its value is %ull0which is different from '' whichre"resents a Gero length string2. Cour user may be looking for records with null values. If this islikely you should take this into consideration when building your code.

    The user was "robably ex"ecting to see records for both genders. Similarly, if they left theDepartmentcombo box em"ty, s"ecifying no criteria for the Departmentfield suggests that they

    want to see records for all the de"artments. Cou can extend the argument to assume that ifthey leave all the combo boxes em"ty they want to see all the records.

    If you were creating the !uery manually you would not s"ecify any criteria at all for the field in!uestion but, since we are using a method which 0in order to be flexible2 is ex"ecting criteria for

    each of the fields, we must find a way to say (show me all the re6or)s for this fiel)8when theuser leaves a combo box em"ty.

    The way I do this is to use the asterisk 092 wildcard. It is a sim"le matter to construct an +fStatementwhich examines the user's in"ut and if it finds that they have left a combo box em"tyit inserts the criteria8 Li.e (8

    )ut it isn't !uite as sim"le as that. #e also have to modify the *skeleton* SQL statementbecause at the moment there is an e!uals sign following each field name, and the insertedvalue is enclosed in !uotes. If we did not alter this the result would be something like this 0theunnecessary characters are marked in red28

    t3lStaff4Department7:Li.e (8;

    when it should be8

    t3lStaff4Department Li.e (8

    To achieve this the code needs three sets of modifications. :irst of all three new stringvariables are declared 0str5ffi6e,strDepartmentand strIen)er2to hold the user in"ut for eachof the three fields.

    3ext, If Statements are written to examine the user in"ut for each field and construct ana""ro"riate criteria string.

  • 8/12/2019 Access and SQL

    26/58

    The first "art of the If Statement a""lies if the user left the combo box em"ty and adds thevalue8 Li.e :; to the variable. 3ote that there is a s"ace before the word Li.ebecause this isneeded in the final SQL string. 3ote also that I have used single !uotes 0: ; 2 around theasterisk. This is because this "iece of code has !uotes inside !uotes. 3either SQL nor A)care if you use single or double !uotes 0as long as o"ening and closing !uotes are of the same

    kind2, but you must alternate the ty"es if they are nested like this.

    The second "art of the If Statement comes into effect if the user made a choice from the combobox. Instead of "lacing the combo box value directly into the SQL string 0as in the originalexam"le2 an e!uals sign and !uotes are added to it. In the original exam"le these wereincluded in the skeleton SQL statement. The result is something like8 7:Lon)on;

    :inally, the SQL string is modified to receive the newly formatted criteria. The finished codelooks like this Nclick the thumbnail to see a full1siGed imageO8

    Leaving the %ialog $o4 #pen

    Cou might find it useful to leave the dialog box o"en instead of closing it after the user clicks#;. This will allow the user to run more !ueries without having to reo"en the dialog box eachtime. The dialog box can be made to remain o"en by sim"ly removing the line8

    DoCm)4Close a6Form, 9e4%ame

  • 8/12/2019 Access and SQL

    27/58

    )ut this isn't enoughF lthough choosing a different combination of criteria and clicking #;again will a""ly the new SQL statement to the !uery, the !uery datasheet will not change 0i.e.the user will not see the new results2 until the !uery is run again. This means closing the !uery

    window and reo"ening it. Cou could instruct the user to close the !uery window 3eforechoosing new criteria, but we can do it easily with code.

    #e need to include some code to detect if the !uery window is o"en, and if so close it beforea""lying the new SQL statement and reo"ening the !uery. To make this ha""en seamlessly

    we can turn of screen u"dating 0called 16hoin ccess A)2 before closing the !uery and turnit on again after reo"ening it.

    This code will re"lace the lines that a""ly the SQL string to the !uery and then o"en it.

    The SysCm)'a6SysCm)Iet53Me6tState444*method can be used to detect whether or not the!uery is o"en. It returns a value of 1 0orac#bEectState#pen2 if the object referred to is o"en,or F0Gero2 if it is closed or doesn't exist.

  • 8/12/2019 Access and SQL

    28/58

    A !unction to &hec- for the (4istence of a Query

    It is !uite likely that you will want to check for the existence of a !uery more that once in yourdatabase so, rather than include the necessary "rocedure in the form's own code, I suggestthat you use it to create a function that can be used from anywhere.

    It is a good idea to kee" your custom functions in a se"arate module, so go to the ,odulestabof the database window and create a new module. Save it with a meaningful name 0I havecalled mine mo)Fun6tions2.

    The code for the custom function is !uite sim"le. s with the "revious code for this "roject Ihave used &(. #e have already set a reference to &( in this database but remember to doso if you want to use this function in another database 0ccess - users need not do this2.

  • 8/12/2019 Access and SQL

    29/58

    Add an (rror+andling Routine

    ery"rocedure you write should include an errorhandler.

    Cou error handler could be written to co"e with certain "roblems that you know might arise. :orexam"le, if we had not included the code to allow the user to leave combo boxes em"ty, anerror would occur. There would be an error if someone had deleted the our !uery and we hadnot included the code to establish its existence. Cou could write error handling code to deal

    with these s"ecific events. )ut if you think you have all the bases covered a *generic* errorhandler will suffice.

    The reason for including an error handler in your "rocedure is to give you control over whatha""ens if something goes wrong. If you don't do this ccess dis"lays the standard A) errormessage, which "robably means nothing to the user, with a button "rom"ting them to *&ebug*.If they click the button they find themselves in the A) code window, with their database inA) break mode, and "anic ensuesF

    Cour error handler can take charge of the situation, return the database to a state of stability byclosing the "rocedure and tidying u" any unfinished jobs, and dis"lay a friendly and reassuringmessage to the user.

    The very first line of your code should be a statement "ointing to the error handler, so enter the

    following line immediately below the line Pri>ate Su3 6m)5GOCli6.'* 8

    5n 1rror IoTo 6m)5GOCli6.Oerr

    Then go to the end of the "rocedure, above the line 1n) Su3, and enter8

    1it Su3 6m)5GOCli6.Oerr

    3ote that there is a colon 082 at the end of the last line. This denotes that the line is a *label*.#hen you finish ty"ing and move out of the line it jum"s to the left margin of the code window.

    %ode labels act like a bookmark and are not executed as code.

    The line you ty"ed at the beginning of the "rocedure tells the code that, if there is an error, itshould jum" straight to this label and continue from there. The "ur"ose of the 1it Su3 beforethe label is to terminate the "rocedure if it reaches that "oint without an error occurring.

    )elow the label, enter the following code. It will deal with any error that might occur bydis"laying an ex"lanatory message8

    9sgBo ($n unepe6te) error has o66urre)4( N O

    >3CrLf N (Please note of the following )etails( N O >3CrLf N (1rror %um3er ( N 1rr4%um3er N O >3CrLf N (Des6ription ( N 1rr4Des6ription O , >3Criti6al, (1rror( 2esume 6m)5GOCli6.Oeit

    :inally, enter another label above the line 1it Su3 that you ty"ed earlier 0see 3ote below28

    6m)5GOCli6.Oeit

  • 8/12/2019 Access and SQL

    30/58

    3ote8 The last line of the error handler sends the code execution back 0i.e. 2esume4442 to a"oint in the main "rocedure from which it can continue and tie u" any loose ends. *Tidying1u"*code usually occurs at the end of a "rocedure so, the 6m)5GOCli6.Oeitlabel should really bebefore the lines that clear the object variables and, if you have included the code that checksfor the existence of the !uery 0in which screen u"dating, or 16ho, is switched off2 it should also

    be before the line that switches screen u"dating on again, like this8

    6m)5GOCli6.Oeit DoCm)416ho True Set )f 7 %othing Set )3 7 %othing 1it Su3

    )he !inished Procedure

    Cou can view the com"leted code "rocedure containing all the enhancements describedabove byNfollowing this linkO. The code is in the form of "lain text so it can be "asted directlyinto your "rocedure.

    %ownload the !ile

    Cou can download a fully1working database file containing this tutorial's com"leted "roject ineither ccess - or ccess K/// format. The database contains two forms8 a basic form0without enhancements2 as created in the first "art of the tutorial, and an enhanced formincluding all of the enhancements described above. The files are "rovided in ccess - andccess K/// format, and also as Ri" files for faster download 0you will need a co"y of #inRi"or a similar "rogram to extract the Gi""ed files2.

    Access and SQLPart 3: ,ore /nstant Queries

    In the last "art of this tutorial I showed how you could build an all1"ur"ose !uery by su""lyingthe user with a dialog box from which they could choose their !uery criteria. The dialog box hadcombo boxes dis"laying criteria choices and when the user clicked a command button their

    choices were used to construct an SQL statement. The SQL statement was then a""lied to astored !uery and the user saw the result of their choices without having to get involved with!uery design. This tutorial takes the idea a stage further.

    #ffering ,ore &hoices

    Instead of combo boxes I am going to use list boxes. List boxes can offer the user the ability tochoose more than one item, a "ro"erty known as 9ulti Sele6t. I am also going to allow the userto s"ecify either *nd* or *(r* conditions.

  • 8/12/2019 Access and SQL

    31/58

    The user makes their choices from the list boxes and o"tion buttons and clicks the ( button tosee the result. In the exam"le below the user has asked for a list of all the Femalestaff workingin the Designde"artments of the %i6eand Parisoffices Nclick the thumbnail to see a full1siGedimageO8

    $uilding the %ialog $o4The first job is to build the dialog box. I have decided to allow the user to !uery three fields85ffi6e, Departmentand Ien)er. Cou will see that the code that "owers the dialog box is easilymodified to suit any number of fields.

    I am not going to describe the form building "rocess in detail so, if you are not ex"erienced inbuilding dialog forms like this one, take a look at my tutorial %ustomiGing ccess EarameterQuerieswhich contains detailed ste"1by1ste" instructions.

    This illustration shows the names I have given to the various objects on the dialog box...

    http://www.fontstuff.com/access/acctut08.htmhttp://www.fontstuff.com/access/acctut08.htmhttp://www.fontstuff.com/access/acctut08.htmhttp://www.fontstuff.com/access/acctut08.htmhttp://www.fontstuff.com/access/acctut08.htm
  • 8/12/2019 Access and SQL

    32/58

    There are three list boxes, one for each field, and two "airs of o"tion buttons. The o"tionbuttons allow the user to choose whether the$%Do"erator or the 52o"erator is used whencombining the criteria.

    Setting *p the List $o4es

    $uilding the Lists

    The 2ow Sour6e"ro"erty of a list box 0likewise a combo box2 defines what makes u" the list ofitems dis"layed. Cou can s"ecify the name of a table containing the list of items, or a !uery

    which creates a suitable list, or you can sim"ly ty"e the list directly into the "ro"erties sheet of

    the list box 0this is called a @alue List2.

    :or the first two fields I decided to use a !uery. Cou can create a stored !uery for this and enterits name into the 2ow Sour6e"ro"erty textbox but, unless you "lan to use the !uery forsomething else, it is a better idea to enter an SQL statement directly into the 2ow Sour6e.0#hy$ There's always a chance that the stored !uery will get changed or deleted by someone,then your dialog won't work. It's neater too, we access1heads like neat1and1tidyF2.

    Since this tutorial is about SQL we might as well take a look at the SQL statement I used.

    S+L+%T &ISTI3%T tblStaff.(ffice :;(6 tblStaff (;&+; )CtblStaff.(ffice?

    The SQL statement !ueries the same table that contains the data I am !uerying with my dialogbox. The *S+L+%T &ISTI3%T* clause instructs ccess to return only one of each of the items itfinds. #ithout this a sim"le *S+L+%T* clause would return an 5ffi6ename for each record inthe table. The *(;&+; )C* clause tells ccess to return the values sorted into al"habeticalorder.

    This method gives me the advantage that should any new (ffices or &e"artments be createdas data is added to the table, the SQL statement 0which is run each time the dialog o"ens2 will

  • 8/12/2019 Access and SQL

    33/58

    ensure that the list box always dis"lays an u"1to1date list. There is a "ossible disadvantage tousing this method. If the table on which the SQL statement is based contains a very largenumber of rows, or if you are using a large number of list boxes, this could seriously slow downthe o"ening of the dialog box as it waits for the !ueries to be "rocessed. In this case I wouldo"t for using a "ur"ose made table for the 2ow Sour6eof each list box.

    TIE8 Cou don't need to write the SQL statement into the 2ow Sour6e yourself. %lick on the 2owSour6etextbox and the "ro"erties window will dis"lay a build button to the right of thetextbox. %lick the build button to o"en the Query )uilder tool. This works just like the familiarccess !uery tool. Dse it to construct and test your 2ow Sour6e!uery. #hen you close theQuery )uilder it returns a ready1made SQL statement to the 2ow Sour6etextbox.

    Since the Ien)erlist box will contain only two items 0*6ale* and *:emale*2 there is little "oint inusing an SQL statement so instead I have used a@alue Listas the2ow Sour6e. To do thisty"e the values directly into the textbox, se"arating the items with a semicolon 0?2. The actualvalues in the Ien)erfield are *6* and *:* so, to hel" the user, I have created a list containing

    two columns. #hen creating a multi1list column using this method enter the values for each rowof the list together, e.g. ,9,ale9!9!e"ale .

  • 8/12/2019 Access and SQL

    34/58

    Dnlike combo boxes, list boxes can offer the facility to select more that one item from the list.)ut you must enable the 6ulti Select feature for this to be "ossible. The 9ulti Sele6t"ro"erty islocated on the 5thertab of the list box "ro"erty sheet.

    I have chosen to enable *Sim"le* multi select. In this mode the user clicks an item to select it,whilst clicking a selected item deselects it. They can select as many items as they want byclicking on each in turn. Cou can also choose *+xtended* multi select, which allows you to dragdown the list to select a grou" of items, or use click and shift1click to select a continuous grou",or click and control1click to select a non1continuous grou".

    Preparing the #ption $uttons

    I have used o"tion buttons to offer the user the choice of *3&* or *(;* when com"osing the!uery. I want each "air of o"tion buttons to work as an o"tion grou", so that only one memberof the grou" is selected at a time. #hen one button is selected the other gets deselected.

    3ormally this is achieved on an ccess form by "lacing the o"tion buttons inside a frame.&oing this automatically forces them to work as an o"tion grou". )ut I didn't want to drawframes on my dialog so I'm relying on code to take care of the *grou"* activity. I did considerusing a frame formatted in such a way as not to be visible but sometimes I just like doing thingsthe hard wayF

    If you don't s"ecify default values for o"tion buttons they start with a *3ull* value 0neither Truenor :alse2. This can confuse the user, and will confound my code if they don't change thesituation by making a choice. :or this reason I have set the Default @alue"ro"erty of each*nd* button to Trueand that of each *(r* button to False.

    )he Stored Query

    %reate and save a !uery. nything will do because the dialog box code is going to change itanyway. I have called my !uery ryStaffListQuery.

    Writing the 2$A and SQL &ode

    The following section ex"lains ste"1by1ste" what code is needed and how it works. Cou canwrite the code yourself, or co"y it from the code listing belowand "aste it directly into theccess code window.

    &oding the #ption $uttons

    n o"tion button can have the valueTrueorFalse4 +ach o"tion button needs some A)

    attached to its 5nCli6. event that says8 *If my value is Truemake my "artner's value False, butif my value is Falsemake my "artner's value True.* sim"le A) If Statement will do it. "rocedure like this is needed for each o"tion button8

    Erivate Sub o"tnd&e"artment%lick02 If 6e.o"tnd&e"artment.Aalue > True Then 6e.o"t(r&e"artment.Aalue > :alse +lse 6e.o"t(r&e"artment.Aalue > True

    http://www.fontstuff.com/access/acctut18.htm#codelistingshttp://www.fontstuff.com/access/acctut18.htm#codelistings
  • 8/12/2019 Access and SQL

    35/58

    +nd If+nd Sub

    TIE8 #hen you have to re"eat blocks of code like this, it makes sense to co"y and "aste thenchange the a""ro"riate bits, but sometimes this can be !uite fiddly. Instead, make use of the

    Aisual )asic +ditor's 2epla6etool 0(dit Replaceor eys8 &trl2. Easte a co"y of theoriginal "rocedure then select it and o"en the 2epla6etool. 6ake sure that Selected )e4tischosen and enter the original text item into the !ind Whattextbox and the new item in theReplace Withtextbox. %lick the Replace Allbutton and your new "rocedure is written foryou...

    &oding the #; $utton

    +verything else runs on the 5nCli6.event of the #;button. #hen the user clicks the #;button the code must assemble an SQL statement based on the user's choices from the listboxes and o"tion buttons. It must then a""ly the SQL statement to the stored !uery and o"enthe !uery so that the user can see the result.

    Start by declaring the string variables that are going to hold the information collected from thedialog box. In my exam"le they are as follows8

    This variable will be used to collect the selections from the list boxes8

    &im varItem s Aariant

    These variables will hold the collected choices from each list box8

    &im str(ffice s String&im str&e"artment s String&im str=ender s String

    These variables will hold the ndH(r choices from the o"tion grou"s8

    &im str&e"artment%ondition s String&im str=ender%ondition s String

    This variable will hold the com"leted SQL statement8

    &im strSQL s String

  • 8/12/2019 Access and SQL

    36/58

    7etting the &hoices fro" the List $o4es

    The code must look at each list box in turn and find out which items have been selected by theuser. It's "ossible that the user might not select anything at all. If this ha""ens I will assumethat they want to see everything 0i.e. selecting nothing will have the same effect as selecting

    everything2.

    3(T+8 I'm assuming that the data being !ueried is text. If the data is non1text such as numbersor dates, some small but im"ortant modifications have to be made. ;ead the note about dataty"esnear the bottom of the "age.

    The following code uses a For444%etloo" to gather all the selections from the lst5ffi6elist boxand join them together, se"arated by commas, into a text string. The text string is stored in avariable called str5ffi6e...

    :or +ach varItem In 6e.lst(ffice.ItemsSelected

    str(ffice > str(ffice M *,'* M 6e.lst(ffice.Item&ata0varItem2 M *'*3ext varItem

    The next ste" is to check the length of the resulting string. If its length is Gero, it means that theuser didn't select anything. So the next section of code takes the form of an If Statement whichbuilds a suitable criteria string re"resenting the users choice...

    If Len0str(ffice2 > / Then str(ffice > *Like '9'*

    +lse str(ffice > ;ight0str(ffice, Len0str(ffice2 1 2 str(ffice > *I30* M str(ffice M *2*+nd If

    If the user selects nothing the code inserts a wildcard into the criteria clause, resulting insomething like this8

    /121 t3lStaff45ffi6e Li.e :;

    )ut if the user selects one or more items the code creates an I3 clause 0after removing the

    leading comma from the string2 like this8

    /121 t3lStaff45ffi6e +%':$mster)am;,:Lon)on;,:Paris;*

    This com"lete "rocess is re"eated for each list box and the resulting criteria are stored inse"arate variables. I called my variables str5ffi6e, strDepartmentand strIen)er.

    7etting the &hoices fro" the #ption $uttons

    The code needs to find out whether the user chose$n)or 5rfrom each "air of o"tion buttons.It is only necessary to look at the value of one button from each "air since I know that if one's

    value is Truethen the other must be False, and vice versa. gain an If Statement does thejob...

    If 6e.o"tnd&e"artment.Aalue > True Then str&e"artment%ondition > * 3& *+lse str&e"artment%ondition > * (; *+nd If

    http://www.fontstuff.com/access/acctut18.htm#datatypeshttp://www.fontstuff.com/access/acctut18.htm#datatypeshttp://www.fontstuff.com/access/acctut18.htm#datatypeshttp://www.fontstuff.com/access/acctut18.htm#datatypeshttp://www.fontstuff.com/access/acctut18.htm#datatypes
  • 8/12/2019 Access and SQL

    37/58

    +ach set of o"tion buttons re!uires an if statement like this. 6y dialog has two sets. The IfStatements create suitable strings re"resenting the s"ecified conditions and stores them inse"arate variables. 6ine are called strDepartmentCon)ition and strIen)erCon)ition.

    3(T+8 3otice that there are s"aces each side of the text in the condition strings * 3& * and *

    (; *. The following section of code also includes s"aces as "art of the string. It is veryim"ortant when combining hard1coded text and variables that you remember to include s"aces

    where they will be needed in your finished SQL string.

    $uilding the Query's SQL State"ent

    *S+L+%T tblStaff.9 :;(6 tblStaff * M *#

  • 8/12/2019 Access and SQL

    38/58

    This gives you the o""ortunity to make sure that your code is working correctly before

    "roceeding to the next ste".

    Apply the SQL State"ent to the Stored Query

    ll that remains is to a""ly the SQL statement to the stored !uery and o"en the !uery for theuser to view the results. There are two ways to write the code for this, de"ending on whetheryou want to use &(or &(. If you use ccess - you must use the &( method. If you useccess K/// or later you can use either.

    *sing %A# CAccess GHD:

    If you are using ccess - you have to write the code this way, but if you use ccess K/// orlater you can use &( instead of the default &( if you "refer 0many ccess develo"ers"refer &( because of its sim"ler coding style2. If you are not using ccess - you need to seta reference to &(. To do this, in the Aisual )asic +ditor go to )ools Referencesand scrolldown the list until you find ,icrosoft %A# 0I #bEect Library0if you can't find .5 use thehighest number available2. Elace a tick in the check box and click #;.

    Two additional variables must be declared 03ote8 ccess - users can omit the %A#"refixes,but the code will work fine if they are left in "lace.28

    &im db s &(.&atabase&im !df s &(.Query&ef

    %urrent&bSet !df > db.Query&efs0*!ryStaffListQuery*2!df.SQL > strSQLSet !df > 3othingSet db > 3othing

    The first two lines tell ccess that we are talking about the current database, and name the!uery we are concerned with. The third line a""lies the new SQL statement to the !uery. Thelast two lines em"ty the )3and )fvariables to clear the memory.

    *sing A%# CAccess FFF onwardsD:

    )ecause this code deals with database structure, you need to set a reference to &(. To dothis, in the Aisual )asic +ditor go to )ools Referencesand scroll down the list until you find

  • 8/12/2019 Access and SQL

    39/58

    ,icrosoft A%# (4t 4 for %%L and Security0where 4is the highest number you have2.Elace a tick in the check box and click #;.

    Two additional variables must be declared8

    &im cat s 3ew &(.%atalog&im cmd s &(&).%ommand

    In &( the information about the structure of a database is stored in its Catalog. TheComman) object in &( is similar to the QueryDef object in &(. %urrentEroject.%onnectionSet cmd > cat.Aiews0*!ryStaffListQuery*2.%ommandcmd.%ommandText > strSQLSet cat.Aiews0*!ryStaffListQuery*2.%ommand > cmd

    Set cat > 3othing

    The first line tells ccess that we are talking about the current database, and the second lineidentifies our stored !uery 0in &( a !uery is a @iewor a Pro6e)urede"ending on its ty"e2.The third line a""lies the new SQL statement and the fourth line saves the changes back to thecatalog. :inally, the catalog variable is set to %othingto clear the item from the memory.

    #pen the Query and &lose the %ialog $o4

    The code to o"en the !uery and close the dialog box is the same for &( ad &(8

    &o%md.("enQuery *!ryStaffListQuery*&o%md.%lose ac:orm, 6e.3ame

    Cou can consider the "roject finished at this "oint, but it can be made a little more user1friendlywith the addition of a few refinements...

    Refine"ents: Leave the !or" and Query #pen

    3ow that you have made it really easy for the user to !uery their data, they are sure to want torun lots of !ueriesF Cou can save them the trouble of reo"ening the dialog box each time by

    omitting the line %o&"d&lose ac!or"J ,e

  • 8/12/2019 Access and SQL

    40/58

    the user will see !uery close then o"en. To make this "rocess invisible turn off screen u"datingby "lacing this line 3eforethe code above8

    &o%md.+cho :alse

    ...and add the following line to the very end of the "rocedure before the 1n) Su3line to restorescreen u"dating8

    &o%md.+cho True

    TIE8 #hen testing your code it's a good idea to tem"orarily remove or disable the line that turnsoff screen u"dating 0%o&"d(cho !alse2 in case anything goes wrong and you're left with afroGen window. The line which restores screen u"dating 0%o&"d(cho )rue2 usually comesnear the end of the "rocedure. If there is an error somewhere which "revents the "rocedurereaching this line then screen u"dating will not be restored and you will be left with a blank orfroGen screen. +ven after several years as a A) develo"er I still forget to do this, and

    sometimes I find myself staring at a blank screen wondering what the heck has ha""enedF If itha""ens to you, don't "anic 1 instead switch to the Aisual )asic +ditor and o"en the Immediate#indow 0&trl72. Ty"e %o&"d(cho )rueinto the Immediate #indow and "ress (nterand

    when you return to the ccess window you will find that Screen D"dating has been restored. Ifyou have a "rocedure that switches off screen u"dating, remember always to include a line inyour error handler to restore screen u"dating in the event of an error.

    Refine"ents: Restore a ,issing Query

    Dsers 0that includes you and meF2 have the annoying habit of deleting things if they don't know

    what they are. If the code can't find the !uery because someone has deleted or renamed itthere will be an error. In the last tutorial in this series I ex"lained how to create a function to testfor the existence of a !uery. This time, I'll ex"lain how to include the code in the c"d#;K&lic-"rocedure. The method is slightly different for &( and &( so I'll outline both.

    *sing %A# CAccess GHD

    If you haven't already added the )3 and)fvariables 0as described above2 you should addthem now, together with a third variable 3lnQuery1ists.

    &im db s &(.&atabase

    &im !df s &(.Query&ef&im blnQuery+xists s )oolean

    The code is in two "arts, and should be "laced right at the beginning of the c"d#;K&lic-"rocedure, after the variable declarations. The first "art uses a For444%etloo" to searchthrough the database's !ueries looking for one with the name s"ecified. If it finds the named!uery it sets the value of the 3lnQuery1ists variable to Trueand exits the loo" 0it must exit theloo" now because any other !uery it finds will set the variable's value back to False2...

    Set db > %urrent&bblnQuery+xists > :alse

    :or +ach !df In db.Query&efs If !df.3ame > *!ryStaffListQuery* Then blnQuery+xists > True +xit :or +nd If3ext !df

    The second "art looks at the value of the 3lnQuery1istsvariable and if it is Falseit creates anew co"y of the !uery...

    http://www.fontstuff.com/access/acctut17a.htm#queryexistshttp://www.fontstuff.com/access/acctut17a.htm#queryexistshttp://www.fontstuff.com/access/acctut18.htm#daohttp://www.fontstuff.com/access/acctut17a.htm#queryexistshttp://www.fontstuff.com/access/acctut17a.htm#queryexistshttp://www.fontstuff.com/access/acctut18.htm#dao
  • 8/12/2019 Access and SQL

    41/58

    If blnQuery+xists > :alse Then Set !df > db.%reateQuery&ef0*!ryStaffListQuery*2+nd If""lication.;efresh&atabase#indow

    The last line is not usually necessary because the new !uery will be o"ened later in the"rocedure. )ut, in case something unforeseen ha""ens, this makes sure that the new !uerya""ears without the user having to refresh the window themselves.

    *sing A%# CAccess FFF onwardsD

    If you haven't already added the 6at and6m)variables 0as described above2 you should addthem now, together with the variablesryand3lnQuery1ists.

    &im cat s 3ew &(.%atalog&im cmd s 3ew &(&).%ommand

    &im !ry s &(.Aiew&im blnQuery+xists s )oolean

    The code is in two "arts, and should be "laced right at the beginning of the c"d#;K&lic-"rocedure, after the variable declarations. The first "art uses a For444%etloo" to searchthrough the database's !ueries 0a !uery in &( is called a @iew2looking for one with the names"ecified. If it finds the named !uery it sets the value of the 3lnQuery1ists variable to Trueandexits the loo" 0it must exit the loo" now because any other !uery it finds will set the variable'svalue back to False2...

    Set cat.ctive%onnection > %urrentEroject.%onnectionblnQuery+xists > :alse:or +ach !ry In cat.Aiews If !ry.3ame > *!ryStaffListQuery* Then blnQuery+xists > True +xit :or +nd If3ext !ry

    The second "art looks at the value of the 3lnQuery1istsvariable and if it is Falseit creates anew co"y of the !uery...

    If blnQuery+xists > :alse Then cmd.%ommandText > *S+L+%T 9 :;(6 tblStaff* cat.Aiews.""end *!ryStaffListQuery*, cmd+nd If""lication.;efresh&atabase#indow

    3ote that when using A) to create a new !uery, &( insists that I "rovide the !uery with anSQL statement. nything will do, but it won't acce"t an em"ty string 0**2. #ith &( I can createan *em"ty* !uery definition 0the "rocedure su""lies the SQL later anyway2.

    )he &o"pleted &ode Procedures

  • 8/12/2019 Access and SQL

    42/58

    str)irthdate M *,U* M6e.lst)irth&ate.Item&ata0varItem2 M *U*

    3ext varItem

    3ote that the single !uotes have been re"laces by hash marks 0marked in red2. The resultingI302 clause looking something like this8

    #

  • 8/12/2019 Access and SQL

    43/58

    So"e Additional !eatures

    If you want to add extra functionality to your dialog box take a look at "art two of this tutorial. Itshows you how to build list box lists with code, how to let the user choose how the data issorted by add an (;&+; )C clause to the !uery, and how to add a Clear $llbutton to resetthe list boxes...

    Access and SQLPart I: %yna"ic Reports

    n ccess ;e"ort is similar to an ccess :orm. It dis"lays data from a record source yous"ecify 0a table or !uery2 and you can customiGe the way the data is dis"layed through itsdesign. In fact designing a re"ort uses the many of the same techni!ues as designing a form.

    :orms are chiefly used for entering and editing data whereas re"orts are used for viewing and"rinting data.

    ;e"orts are often seen as inflexible, with the decisions about which data is to be dis"layedbeing made at design time. ccess users often think that if they want to see a different set ofdata they need to build a new re"ort, or change the !uery on which the re"ort is based. 3ottrueF

    #hen you look at data in a table or form ccess "rovides you with tools for filtering andsorting...

    )ut when you view a re"ort in Erint Ereview these tools are absent, so you could be forgivenfor thinking that it's too late to change what's on dis"lay.

    This tutorial will show you how to make use of a re"ort's Filterand 5r)erBy"ro"erties to createdynamic re"orts which the user can filter and sort using a sim"le dialog, and see the result

    a""ear immediately in the re"ort's Erint Ereview window. To see a different set of data all theyhave to do is s"ecify a different filter, click the button, and the re"ort will change to dis"lay thenew data.

    In the exam"le below the user filtered the re"ort for a list of all the Femalestaff working in thePro)u6tion andShippingde"artments of the Birminghamand Car)iffoffices Nclick thethumbnail to see a demonstration in a new windowO8

    Cou can download a fully working sam"le filecontaining all the exam"les described here fromthe link at the bottom of this "age.

    $uilding the Report

    3othing s"ecial here, and no code re!uiredF Cou can use an existing re"ort or create a newone for this "roject. Cou should bear in mind that the tool you are going to build will filter the

    http://www.fontstuff.com/access/acctut19.htm#downloadhttp://www.fontstuff.com/access/acctut19.htm#download
  • 8/12/2019 Access and SQL

    44/58

    re"ort's data so it might be a""ro"riate for you to base your re"ort on an unfiltered table ratherthan on a !uery where the data is already filtered by the time it reaches the re"ort. It's u" toyou. :amiliariGe yourself with the names of the fields dis"layed in the re"ort and their dataty"es.

    $uilding the %ialog $o4

    The job of the dialog box is to allow the user to s"ecify criteria for filtering and, in the moreso"histicated exam"les sorting, the records dis"layed by the re"ort. This means that you mustchoose which fields you want to offer the user and, in most of these exam"les, be able to"rovide a list of suitable search criteria to "o"ulate a combo box or list box for each field.

    To turn an ccess form into a dialog box only re!uires you to change a few settings on theform's "ro"erties sheet. If you haven't built an ccess form as a dialog box before click here tofind out what you need to do.

    I have created several different dialog boxes, offering different levels of com"lexity. Cou canchoose from sim"le exam"les using combo boxes, or more com"lex ones using multi1select listboxes8

    $ simple )ialog using

    6om3o 3oes4 Com3o 3oes an) anoption group4 9ulti-sele6t list 3oes4

    List 3oes an) sortingoptions4

    (r free1text filtering where the user can search on any text string8

    In my combo box and list box exam"les, the fields that I have chosen for filtering contain aknown range of entries. (ne is a list of com"any 5ffi6esand another is a list of Departments.6y database has tables containing lists of these entries and I am using these tables for the2ow Sour6eof the combo boxes and list boxes. Later in this tutorial I will show how to use

    wildcards to allow users to filter records using string fragments 0such as records starting with a"articular letter, or containing a "articular grou" of letters2.

    The im"ortant "arts of the A) code for each dialog box are described and ex"lained below.To see the full code module for each dialog box follow the links marked 5&ode Listing 15etc.These will dis"lay all the code used in the dialog box in a form that you can co"y and "aste intoyour own code window if you wish.

    A Si"ple %ialog *sing &o"bo $o4es

    http://www.fontstuff.com/access/acctut19.htm#dialog5http://www.fontstuff.com/access/acctut19.htm#dialog4http://www.fontstuff.com/access/acctut19.htm#dialog3http://www.fontstuff.com/access/acctut19.htm#dialog2http://www.fontstuff.com/access/acctut19.htm#dialog1
  • 8/12/2019 Access and SQL

    45/58

  • 8/12/2019 Access and SQL

    46/58

    str&e"artment > *>'* M 6e.cbo&e"artment.Aalue M *'* +nd If

    3ext comes a line which combines the criteria to form a # *N(fficeO * M str(ffice M * 3& N&e"artmentO *M str&e"artment

    nd finally the filter is a""lied to the re"ort and switched on8

    #ith;e"ortsFNr"tStaffO .:ilter > str:ilter .:ilter(n > True +nd#ith+nd Sub

    Anticipating (rrors

    )efore com"leting any "roject like this you should consider what might go wrong. ll but themost basic of your A) "rocedures should contain a sim"le error handler, but you can hel"things a great deal by antici"ating what "roblems might arise. %hanges in the design of there"ort or the fields included might result in an error, but if you are fairly confident that this won'tha""en you can leave it for the error handler to take care of. This "roject re!uires the re"ort tobe o"en before the filter is a""lied. If it isn't then you get an error8

    3otice that the error doesn't distinguish between the re"ort not being o"en and not existing atall. It can only *see* an object if it is o"en. It may be that the user sim"ly forgot to o"en there"ort, or "erha"s its name has been changed or someone might have deleted it.

    Cou could have the re"ort o"en automatically when the dialog o"ens 0or vice versa2 byincluding the "rocedure8

    ErivateSub:ormLoad02 &o%md.("en;e"ort *r"tStaff*, acAiewEreview+ndSub

    )ut this would still need to take account of a missing or renamed re"ort. 6y "referred methodof dealing with this "ossibility is to check whether or not the re"ort is o"en and advise the useraccordingly. This code goes at the beginning of the c"dApply!ilterK&lic-"rocedure after thevariable declarations8

    IfSys%md0acSys%md=et(bjectState, ac;e"ort, *r"tStaff*2 PBac(bjState("en Then

    6sg)ox *Cou must o"en the re"ort first.*

  • 8/12/2019 Access and SQL

    47/58

    +xitSub+ndIf

    If a re"ort with the name s"ecified is not found in an *("en* state the If Statement dis"lays amessage to the user then terminates the "rocedure to "revent an error occurring.

    &oding the 5Re"ove !ilter5 $utton

    ll that is re!uired to remove the filter is a line which sets the Filter5n"ro"erty of the re"ort toFalse8

    ErivateSubcmd;emove:ilter%lick02 (n +rror ;esume 3ext ;e"ortsFNr"tStaffO.:ilter(n > :alse+ndSub

    The line 5n 1rror 2esume %ettells ccess to ignore any error which might occur if, forexam"le, the re"ort has already been closed by the user.

    >ou can review the co"plete code for the dialog bo4 in &ode Listing 1

    @ to"

    Adding an #ption 7roup

    %ombo boxes are not the only way to offer the user a choice of "redefined o"tions. This dialog

    box, otherwise exactly the same as the "revious exam"le, makes use of an option grouptoallow the user to filter the records by gender.

    ("tion grou"s are useful when there are just a few items to choose from.

  • 8/12/2019 Access and SQL

    48/58

    #hen o"tion buttons are used as a grou" like this, only one member of the grou" can beselected at a time. The selected button "asses its value to the grou" itself. It is a good idea toset a starting value for the grou" by s"ecifying the frame's Default @alue"ro"erty. In myexam"le the default value is , so that when the dialog box o"ens the Bothbutton is alreadyselected.

    &etecting and "rogramming the user's choice is sim"le and is best done with a %aseStatement. :irst it is necessary to declare an additional variable to hold the Ien)ercriteria8

    &imstr=ender sString

    Then the %ase Statement can "lace the a""ro"riate criteria string into the variable de"endingon the value of the o"tion grou"8

    Select%ase6e.fra=ender.Aalue %ase

    str=ender > *>':'* %aseK str=ender > *>'6'* %ase str=ender > *Like '9'*+ndSelect

    The only other change to the code is the addition of the criteria for the Ien)er field to the filterstring8

    str:ilter > *N(fficeO * M str(ffice M * 3& N&e"artmentO *M str&e"artment M * 3& N=enderO * M str=ender

    >ou can review the co"plete code for the dialog bo4 in &ode Listing

    @ to"

    *sing ,ulti+Select List $o4es

    The combo boxes used in the "revious exam"les have the disadvantage that the user canselect only one item from each. This dialog box uses list boxes. These offer a multi1select

    facility so that the user can make several choices from each if they wish.

    &esigning a list box is similar to designing a combo box in that is needs a 2ow Sour6efromwhich to make its list. s before I have used tables for this. Cou must enable the multi1selectfeature by choosing a suitable mode for the 9ulti Sele6t"ro"erty of the list box. %hoose Simpleor 1ten)e)de"ending on how you want the user to make their choices.

    http://www.fontstuff.com/access/acctut19code2.htmhttp://www.fontstuff.com/access/acctut19.htm#tophttp://www.fontstuff.com/access/acctut19code2.htmhttp://www.fontstuff.com/access/acctut19.htm#top
  • 8/12/2019 Access and SQL

    49/58

    If you want to know more about list box basics read my tutorial 6aking Sense of List )oxes.

    In this exam"le the code has the job of creating a criteria string from the user's choices in eachof the list boxes. If, for exam"le, the user chooses Lon)on, Brusselsand Parisfrom the 5ffi6elist box it means that they want to see records for the Lon)on(;Brussels(; Parisoffices.

    There are different ways this can be re"resented in SQL. (ne way is to use the keyword *(;*like this8

    N(fficeO > 'London' (; N(fficeO > ')russels' (; N(fficeO > 'Earis'

    but this can result in very long criteria strings, so I "refer to use an SQL *I3* clause like this8

    N(fficeO I30'London',')russels','Earis'2

    To do this I use a code statement that loo"s through the selected items in the list box and

    strings them together, se"arated by commas8

    &imvarItem sAariant:or+achvarItem In6e.lst(ffice.ItemsSelected str(ffice > str(ffice M *,'* M 6e.lst(ffice.Item&ata0varItem2 M *'*3extvarItem

    If the resulting string has no length 0i.e. it is em"ty because the user didn't select anything2 thecode creates criteria which shows all records. )ut if the user did make a selection my code

    creates an I3 clause listing the selections, after first removing the leading comma from the frontof the string8

    IfLen0str(ffice2 > / Then str(ffice > *Like '9'*+lse str(ffice > ;ight0str(ffice, Len0str(ffice2 1 2 str(ffice > *I30* M str(ffice M *2*+ndIf

    +ach list box re!uires a similar set of code statements. The code for the Ien)ero"tion grou"

    and the code that creates the filter string are exactly the same as in the "revious exam"le4

    >ou can review the co"plete code for the dialog bo4 in &ode Listing 0

    @ to"

    #ffering the #ption to Sort the Records

    In many cases sorting the records in a re"ort is just as im"ortant as filtering them. If you don'twant to offer a sorting o"tion to the user, you can "redefine the sort order by basing the re"orton a !uery or use an SQL statement incor"orating an (;&+; )C clause as the re"ort's

    ;ecord Source. :or exam"le8

    S+L+%T 9 :;(6 tblStaff (;&+; )C N(fficeO, N&e"artmentO?

    will dis"lay the records sorted first by the 5ffi6efield then by the Departmentfield, both inascending order.

    http://www.fontstuff.com/access/acctut11.htmhttp://www.fontstuff.com/access/acctut11.htmhttp://www.fontstuff.com/access/acctut19code3.htmhttp://www.fontstuff.com/access/acctut19.htm#tophttp://www.fontstuff.com/access/acctut11.htmhttp://www.fontstuff.com/access/acctut19code3.htmhttp://www.fontstuff.com/access/acctut19.htm#top
  • 8/12/2019 Access and SQL

    50/58

  • 8/12/2019 Access and SQL

    51/58

    Se"arated by semicolons, each item becomes an o"tion on the combo box list8

    &oding the &o"bo $o4es

    +ach combo box has three jobs to do when the user makes a choice8

    . It has to check that the choice is not the same as a choice that has already beenmade.

    K. It has to disable the combo boxes below it in the hierarchy if the user chose *3otSorted* and set their values to *3ot Sorted*.

    . If the user chose *3ot Sorted* it has to disable its own sort direction command buttonand any below it in the hierarchy and set their ca"tions to *scending*.

    The first job is best handled by the combo box's Before Up)ateevent. This is because, if theuser's choice is not acce"table, the u"date can be cancelled easily. The$fter Up)ate eventdoesn't offer this facility.

  • 8/12/2019 Access and SQL

    52/58

    :ori > K To #ith6e.%ontrols0*cboSort(rder* M i2 .+nabled > :alse .Aalue > *3ot Sorted* +nd#ith

    3exti :ori > To #ith6e.%ontrols0*cmdSort&irection* M i2 .+nabled > :alse .%a"tion > *scending* +nd#ith 3exti +lse 6e.cboSort(rderK.+nabled > True 6e.cmdSort&irection.+nabled > True +ndIf

    +ndSub

    #hen the user changes the value of the combo box an If Statement checks the new value tosee if it is *3ot Sorted*. If it is, a For444%etloo" disables the other combo boxes and sets theirvalues to *3ot Sorted*. Then anotherFor444%etloo" disables the command buttons and setstheir ca"tions to *scending*.

    If the user made a choice other than *3ot Sorted* then its own sort direction command button isenabled and the combo box below is enabled.

    s before, the code is similar for the remaining combo boxes. +ach one referring to thea""ro"riate controls.

    3(T+8 (ne of the aims of writing good code is to make it as brief as "ossible, and in the aboveexam"le I have demonstrated this with the use of loo"s and #ith Statements. Dsing loo"savoids having to re"eat chunks of code. The variable *i* not only tells ccess how many timesto run the loo" but also serves to identify which control is being mani"ulated each time. I cando this because I gave the controls names which included numbers. In the first loo", the firsttime it runs the value of *i* is K so 9e4Controls'(63oSort5r)er8 N i*means the same as9e463oSort5r)er"and so on. lthough there are only three combo boxes in this exam"le theloo" would re!uire no additional code for any number of combo boxes. I would just have to

    change the u""er limit of the value of *i*. #ith Statements also hel" by removing the need tore"eat the first "art of a long code line when writing several consecutive statements all referringto the same thing.

    &oding the Sort %irection &o""and $uttons

    I want to make the selection of a sort direction 0i.e. ascending or descending2 as easy as"ossible. Since there are only two choices it isn't worth using combo boxes, and an o"tionbuttons would take u" too much room. So I borrowed 6icrosoft's idea 0take a look at the Query#iGardF2 and used command buttons. %licking one of the command buttons doesn't doanything other than change it's ca"tion. The code which later builds the SQL statement for the

    re"ort filter will read the button's ca"tion to determine which way to sort the records. The codeis sim"le and the same for each button 0with the a""ro"riate control names inserted28

    ErivateSubcmdSort&irection%lick02 If6e.cmdSort&irection.%a"tion > *scending* Then 6e.cmdSort&irection.%a"tion > *&escending* +lse 6e.cmdSort&irection.%a"tion > *scending*

  • 8/12/2019 Access and SQL

    53/58

    +ndIf+ndSub

    &oding the Apply !ilter &o""and $utton

    The code used to create the filter string is exactly the same as in the "revious exam"le, but thistime there is an additional task8 to create an (rder )y string that will be a""lied to the 5r)erBy"ro"erty of the re"ort.

    In the same way that the code generates a criteria string, a""lies it to the Filter"ro"erty of there"ort and then activates it by setting the Filter5n"ro"erty to True,it now has to generate asort string, a""ly it to the 5r)erBy"ro"erty of the re"ort and activate it by setting the5r)erBy5n "ro"erty to True.

    If the user chose to sort the data by Last%amethen by First%ame, here's what a com"leted(rder)y string should look like8

    NLast3ameO, N:irst3ameO

    :ields are sim"ly listed in the desired order, se"arated by commas. I am in the habit ofenclosing field names in s!uare brackets as shown here but this is only absolutely necessary

    when the names contain s"aces.

    Dnless s"ecified otherwise, each field is sorted in ascending order 01R, 1-2 but if a field is tobe sorted in descending order 0R1, -12 the keyword &+S% is used. The sort direction must bes"ecified for each field. if it is omitted it is assumed that the field is to be sorted in ascending

    order. So, if the user chose to sort the data by Last%amethen by First%ameboth indescending order the string should look like8

    NLast3ameO &+S%, N:irst3ameO &+S%

    *N* M 6e.cboSort(rder.Aalue M *O* If6e.cmdSort&irection.%a"tion > *&escending* Then strSort(rder > strSort(rder M * &+S%*

    +ndIf If6e.cboSort(rderK.Aalue PB *3ot Sorted* Then strSort(rder > strSort(rder M *,N* M

    6e.cboSort(rderK.Aalue M *O* If6e.cmdSort&irectionK.%a"tion > *&escending* Then strSort(rder > strSort(rder M * &+S%* +ndIf If6e.cboSort(rder.Aalue PB *3ot Sorted* Then strSort(rder > strSort(rder M *,N* M

    6e.cboSort(rder.Aalue M *O* If6e.cmdSort&irection.%a"tion > *&escending* Then

    strSort(rder > strSort(rder M * &+S%* +ndIf +ndIf +ndIf+ndIf

    The code consists of a series of nested If Statements, each one de"ending on the result of the"revious one. :irst of all, an If Statement checks to see if the value of the first combo box issomething other than *3ot Sorted*. If the value is *3ot Sorted* the If Statement finishes and the

  • 8/12/2019 Access and SQL

    54/58

    (rder)y string remains em"ty. )ut if the first combo box contains a field name then it is "laced,surrounded by s!uare brackets, into a variable named strSort5r)er. second If Statementthen looks at the ca"tion of the first command button and if it reads *&escending* the keyword&+S% is added to the string in the strSort5r)ervariable.

    The "rocess is re"eated for each combo box and finishes if the value *3ot Sorted* is found, butif a field name is found its name and the sort direction is noted and the code moves to the nextcombo box.

    The last section of the code a""lies and activates both the filter string and the sort string8

    #ith;e"ortsFNr"tStaffO .:ilter > str:ilter .:ilter(n > True .(rder)y > strSort(rder .(rder)y(n > True

    +nd#ith

    &oding the Re"ove !ilter &o""and $utton

    In the earlier exam"les the this button has sim"ly set the Filter5n"ro"erty of the re"ort toFalse. 3ow it has to do the same for the 5r)erBy5n"ro"erty8

    #ith;e"ortsFNr"tStaffO .:ilter(n > :alse .(rder)y(n > :alse

    +nd#ith

    )ut this time I have added some extra functionality. The following statement removes theselections from the5ffi6e list box 0there is a similar one for the Departmentlist box28

    :or+achvarItem In6e.lst(ffice.ItemsSelected 6e.lst(ffice.Selected0varItem2 > :alse3extvarItem

    The o"tion grou" is reset to its original value 0Ien)er 7 Both28

    6e.fra=ender.Aalue >

    :inally the following loo" sets the value of each combo box to *3ot Sorted* and disables it, thensets the ca"tion of each sort direction command button to *scending* and disables it. The lastline enables the first combo box ready for the user to make their next choice.

    :ori > To 6e.%ontrols0*cboSort(rder* M i2.Aalue > *3ot Sorted* 6e.%ontrols0*cboSort(rder* M i2.+nabled > :alse 6e.%ontrols0*cmdSort&irection* M i2.+nabled > :alse 6e.%ontrols0*cmdSort&irection* M i2.%a"tion > *scending*

    3exti6e.cboSort(rder.+nabled > True

    >ou can review the co"plete code for the dialog bo4 in &ode Listing @

    @ to"

    !iltering with !ree )e4t

    http://www.fontstuff.com/access/acctut19code4.htmhttp://www.fontstuff.com/access/acctut19.htm#tophttp://www.fontstuff.com/access/acctut19code4.htmhttp://www.fontstuff.com/access/acctut19.htm#top
  • 8/12/2019 Access and SQL

    55/58

    +ach exam"le so far has offered the user a fixed range of choices for filtering the re"ort'srecords. That is fine if the fields that are being filtered contain a known range of items. )ut youmight need to offer the facility to filter using free text, i.e. allowing the user to enter anythingthey want.

    This final exam"le shows how you can allow the user to enter any string of text into a text boxand choose how that string is used to filter the records...

    :or each available field the dialog box has a text box and a set of o"tion buttons. The user canenter a letter or a string of text in the text box and make a choice from the o"tion grou" tos"ecify how the string is used in the filter. If the user leaves a text box em"ty then all recordsare returned for that field.

    Su""osing the user might enter the string "arinto the First%ametextbox. The results they getwill de"end u"on the choices they make from the o"tion buttons8

    %hoosing Starts with444would return8 ,artin, ,ark, ,argaret, ,ariana etc.%hoosing Contains444would return8 ,artin, nne1,arie, ,arlon, ("aretc.%hoosing 1n)s with444would return8 ("ar, &ag"ar, Aalde"aretc.%hoosing 1uals444would return only8 ,ar

    The method used by the filter is to combine the string with one or more asterisk wildcards. InSQL the asterisk 092 combined with a string and the keyword LI+ re"resents any string of text8

    Like *g9* re"resents the letter gfollowed by any string of text.Like *9g9* re"resents any string of text containing the letter g.Like *9g* re"resents any string of text ending with the letter g.

    The code used to create the filter string is !uite sim"le8

    IfIs3ull06e.txt:irst3ame.Aalue2 Then str:irst3ame > *Like '9'*+lse

    Select%ase6e.fra:irst3ame.Aalue %ase str:irst3ame > *Like '* M 6e.txt:irst3ame.Aalue M *9'* %aseK str:irst3ame > *Like '9* M 6e.txt:irst3ame.Aalue M *9'* %ase str:irst3ame > *Like '9* M 6e.txt:irst3ame.Aalue M *'* %ase str:irst3ame > *> '* M 6e.txt:irst3ame.Aalue M *'*

  • 8/12/2019 Access and SQL

    56/58

    +ndSelect+ndIf

    n If Statement looks for an entry in the text box. If the text box is em"ty 0i.e. its value is %ull2 afilter ex"ression is created that will return all the records. If there is an entry in the text box a

    %ase Statement creates the re!uired filter ex"ression de"ending on the value of the o"tiongrou".

    This is re"eated for each field and the filter ex"ressions are combined to create a filter string8

    str:ilter > *N:irst3ameO * M str:irst3ame M * 3& NLast3ameO * M strLast3ame

    The filter string is a""lied to the re"ort and activated in the same way as in the "reviousexam"les.

    >ou can review the co"plete code for the dialog bo4 in &ode Listing 3

    @ to"

    /deas for !urther /"prove"ents

    The exam"les I have shown are each designed to illustrate "articular techni!ues. ;ememberyou can mix and match as many of the different tools as you need but remember to alwaysthink about the user. These tools are meant to make their lives easier 1 so kee" it sim"leF

    #pening the Report Auto"atically

    The above exam"les include


Recommended