SlideShare uma empresa Scribd logo
1 de 5
Baixar para ler offline
9/8/2014 Access Tips: Access and SQL Part 4: Building Select Queries On-the-Fly 
| Home | Excel | Access | Word | Outlook | FrontPage | VBA | Downloads | Index | 
Access & SQL 4 
Access Home 
C ontinue the 
tutorial: 
Part 1: 
Introduction 
Part 2: VBA & 
SQL 
Part 3: Examples 
Part 4: Building 
Queries 
Part 5: More 
Instant Queries 
Part 6: Dynamic 
Reports 
Printer Friendly 
Version 
Download the File 
Coding Note 
Sometimes lines of code 
can be very long! Where I 
have had to break a line of 
code to fit it on the page I 
have used the symbol 
to indicate that the line 
below is a continuation and 
that the code should be 
written as a single line 
<Blah blah blah 
blah> 
should be written: 
<Blah blah blah blah> 
Access and SQL 
Part 4: Building Queries "On the Fly" 
This tutorial is about using SQL to build queries "on the fly" (or as we propellorheads 
say: "at run-time"). This means that you build the queries when you need them, 
rather than trying to anticipate the user's needs and preparing them in advance. 
The tutorial will deal with regular "select" queries, ones which filter the source data 
and show the result to the user (as opposed to "action" queries which manipulate the 
data in some way). 
You can download a copy of the database used in this tutorial. It contains completed 
examples of the forms, queries and code described in the tutorial. Follow the link at 
the bottom of this page. The database contains a table listing the details of the staff of 
a fictional multinational company. It contains the sort of personal details you might 
expect such as FirstName, LastName, BirthDate and Gender together with business 
details such as Office, Department, JobTitle and Email. 
This tutorial is in two parts. This first part will show you how to create a fully working 
multi-purpose query. The second part will explain how to add some refinements to 
create a really professional query tool. You will find a link to the second part of the 
tutorial at the bottom of this page. 
Why Build Queries on the Fly? 
Like many Access developers, I tend to create very few stored queries. Instead I try 
to create a small number of general purpose queries that can be changed on demand 
to suit the user's requirements. 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 the information from the user which is used 
to create the query's SQL statement. The user is really building a query themselves 
but they don't need to know anything about Access to do it. 
Another important reason for working this way is that inquisitive (or careless!) users 
might delete or change stored queries, and not know how to replace them. 
Building a Multi-Purpose Query 
The Plan... 
The aim of this project is to create a single stored query whose criteria can be 
changed to suit the user's requirements. The query will be opened when the user 
clicks a button on a dialog box. The dialog box will also be used to gather the criteria 
from the user. 
The Stored Query 
You need a query that can be used as the basis of our multi-purpose query. Its design 
is completely irrelevant because it is going to be changed each time it is used, but 
Access doesn't let you create an "empty" query so you'll have to make something up 
(anything will do). 
Ask Access for a new query in design view, add a table, put a field into the grid and 
then close and save the query. Give it a sensible name - in this example I am calling 
the query qryStaffListQuery. 
http://www.fontstuff.com/access/acctut17.htm 1/5
9/8/2014 Access Tips: Access and SQL Part 4: Building Select Queries On-the-Fly 
The Dialog Box 
I have decided that my users will probably want to query on three different criteria: 
Office, Department and Gender. So, the first step is to build a dialog box to help the 
users specify their criteria. It's up to you what your dialog box looks like and what it 
contains. I have chosen to use combo boxes showing lists of all the possible criteria 
choices. Future tutorials in this series will show examples of other design methods. 
If you are not experienced in building dialog forms like this one, take a look at my 
tutorial C ustomizing Access Parameter Queries which contains detailed step-by-step 
instructions. 
Point at the labels next to the combo boxes in the illustration below to see what is 
contained on their lists... 
So, now we have the required components of the multi-purpose query. The next step 
is to write the code to make them work together. 
Writing the VBA and SQL Code 
When the user clicks the dialog's OK button several things must happen: 
Gather the user's choices from the combo boxes and write them into an 
SQL statement. 
Apply the SQL statement to the stored query. 
Open the stored query. 
C lose the dialog box. 
The code to carry out these operations will run on the On Click event of the OK 
button. 
In form design view right-click the OK button and choose Properties to open its 
properties window and locate On Click on the Events tab. C lick in the white bar then 
click the Build button: . In the Choose Builder dialog select Code Builder and 
click OK. You are now ready to write the code... 
Declare and Fill the Variables 
The first few lines of code establish contact with the database, telling Access that we 
are referring to the current database (i.e. the one containing the code) and identifying 
the query that we are going to work on. In addition, a string (i.e. text) variable is 
declared, which I have called strSQL. It will hold the SQL statement that will be applied 
to the query: 
Dim db As DAO.Database 
Dim qdf As DAO.QueryDef 
Dim strSQL As String 
Set db = CurrentDb 
http://www.fontstuff.com/access/acctut17.htm 2/5
9/8/2014 Access Tips: Access and SQL Part 4: Building Select Queries On-the-Fly 
Set qdf = db.QueryDefs("qryStaffListQuery”) 
NOTE: I am using DAO language here because I think it is simpler 
for this sort of work. DAO is the default for Access 97, but the default 
for Access 2000/2002 is ADO. Access 97 users need do nothing (you 
can omit the "DAO." bits if you want but it doesn't really matter) but 
Access 2000/2002 users need to set a reference to DAO so that their 
database understands the code. In the Visual Basic Editor go to 
Tools > References. In the dialog box scroll down to "Microsoft 
DAO 3.x Object Library" (where x is the highest number if you have 
more than one) and put a tick in the box. C lick OK to set the 
reference. You only need to do this once for the database and any 
code you put in it will be able to use the reference. 
Build the SQL Statement 
Next comes a VBA statement which places a text string into the strSQL variable. There 
was a detailed explanation of how I like to write my VBA/SQL and the rules you need 
to know in the second tutorial in this series: Access and SQL Part 2: Putting VBA and 
SQL Together. 
This code combines SQL keywords and clauses into which have been placed 
references to the combo boxes that contain the user's criteria choices: 
strSQL = "SELECT tblStaff.* ” & _ 
"FROM tblStaff ” & _ 
"WHERE tblStaff.Office='" & Me.cboOffice.Value & "’ ” & _ 
"AND tblStaff.Department='" & Me.cboDepartment.Value & "’ ” & _ 
"AND tblStaff.Gender='" & Me.cboGender.Value & "’ ” & _ 
"ORDER BY tblStaff.LastName,tblStaff.FirstName;” 
Although it doesn't seem to make a readable SQL statement as it is, when Access 
reads the code and substitutes, for example, Me.cboOffice.Value with London a 
sensible SQL statement results. 
Here is what your code should look like so far [click the thumbnail to see a full-sized 
image]: 
Test the Code 
Now is a good time to test the code you have written so far and there are a couple of 
ways you can do this. You can "print" the SQL to the Immediate Window or you can 
display it in a message box (or you can do both!). Here's what to do: 
Using the Immediate Window: 
In Access 97 the Immediate Window is called the Immediate (lower) pane of the 
Debug Window. In all versions the window can be displayed by pressing Ctrl+G from 
the VBA code window. First, add the following line of code before the End Sub line of 
your cmdOK_Click procedure: 
Debug.Print strSQL 
Using a Message Box: 
Add the following line of code before the End Sub line of your cmdOK_Click procedure: 
MsgBox strSQL 
Now you are ready to run a test. Switch to Access and open your dialog box in Form 
View (now is a good time to save the form!). Make some choices from the combo 
http://www.fontstuff.com/access/acctut17.htm 3/5
9/8/2014 Access Tips: Access and SQL Part 4: Building Select Queries On-the-Fly 
boxes and click the OK button... 
If you chose to use a message box it will open displaying the SQL string that your 
code created from the choices in the dialog box. Read the SQL statement to check that 
it makes sense: 
If you chose to use the Immediate Window, switch to the VBA code window and press 
Ctrl+G to open the Immediate Window where the SQL string will be displayed (it is 
written in a single line): 
The message box method is quick and, because I am familiar with SQL, it is my 
preferred method. Using the Immediate Window has the advantage that you can 
select and copy from it the SQL statement that your code generated and paste it into a 
query to test it. To do this first select and copy the SQL statement then return to the 
Access database window and choose Create query in design view. C lose the 
Show Table box and open the SQL window by choosing View > SQL View. Delete 
any entry that is already there (it usually shows SELECT;) and paste in your SQL 
statement. Run the query and check the result. 
If you see an error message when you try to run your SQL you can trace the error 
and correct it. Read the section on "Debugging Your SQL C ode" in Part 2 of this series. 
When you are satisfied that this part of your code is working properly, you can 
remove the line(s) Debug.Print strSQL or MsgBox strSQL. 
Update and Open the Query 
All that remains is to apply the SQL statement to the stored query that you saved 
earlier, and to close the dialog box. 
Enter the line: 
qdf.SQL = strSQL 
http://www.fontstuff.com/access/acctut17.htm 4/5
9/8/2014 Access Tips: Access and SQL Part 4: Building Select Queries On-the-Fly 
to apply your new SQL statement to the stored query. There is no need to give a 
command to save this change to the query because this happens automatically. Next 
add the lines: 
DoCmd.OpenQuery "qryStaffListQuery" 
DoCmd.Close acForm, Me.Name 
to open the query displaying the results of the user's criteria choices, and to close the 
dialog. Finally add the lines: 
Set qdf = Nothing 
Set db = Nothing 
which empty the variables used to identify the query and the database. All variables 
normally lose their values when a procedure finishes, and the memory that was 
allocated to them is freed. But sometimes Access forgets to clear "object" variables 
(those with which you have to use the "Set" keyword) so it is good coding practice to 
clear them manually like this, just to make sure. Your finished code should look like 
this [click the thumbnail to see a full-sized image]: 
Return to the Access database window and save the dialog box form (to save your 
code changes). 
Job Done! 
Your Multi-Purpose Query is now ready to run. Remember that the query should be 
run from the dialog box. If you open the stored query it will display records using the 
same criteria as the last time it was run. 
The Multi-Purpose Query will work fine as it is, but you can make it even more user-friendly 
with the addition of a few refinements. The second part of this tutorial shows 
you how to turn your multi-purpose query into a really professional tool. 
Go to the next part of the tutorial >>> 
^ top 
http://www.fontstuff.com/access/acctut17.htm 5/5

Mais conteúdo relacionado

Mais procurados

Transforming Power Point Show with VBA
Transforming Power Point Show with VBATransforming Power Point Show with VBA
Transforming Power Point Show with VBADCPS
 
Advisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScriptAdvisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScriptdominion
 
E learning excel vba programming lesson 2
E learning excel vba programming  lesson 2E learning excel vba programming  lesson 2
E learning excel vba programming lesson 2Vijay Perepa
 
A Lap Around Visual Studio 2010
A Lap Around Visual Studio 2010A Lap Around Visual Studio 2010
A Lap Around Visual Studio 2010Abram John Limpin
 
How to build accessible UI components
How to build accessible UI componentsHow to build accessible UI components
How to build accessible UI componentsRuss Weakley
 
Html advanced-reference-guide for creating web forms
Html advanced-reference-guide for creating web formsHtml advanced-reference-guide for creating web forms
Html advanced-reference-guide for creating web formssatish 486
 
20 Office 365 Productivity Tips that you've probably never used (but should)
20 Office 365 Productivity Tips that you've probably never used (but should)20 Office 365 Productivity Tips that you've probably never used (but should)
20 Office 365 Productivity Tips that you've probably never used (but should)Christian Buckley
 
Cis 407 i lab 2 of 7
Cis 407 i lab 2 of 7Cis 407 i lab 2 of 7
Cis 407 i lab 2 of 7helpido9
 
Handling errors in t sql code (1)
Handling errors in t sql code (1)Handling errors in t sql code (1)
Handling errors in t sql code (1)Ris Fernandez
 
Diving into VS 2015 Day1
Diving into VS 2015 Day1Diving into VS 2015 Day1
Diving into VS 2015 Day1Akhil Mittal
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010vchircu
 
Cis407 a ilab 2 web application development devry university
Cis407 a ilab 2 web application development devry universityCis407 a ilab 2 web application development devry university
Cis407 a ilab 2 web application development devry universitylhkslkdh89009
 

Mais procurados (20)

ASP.NET MVC3 RAD
ASP.NET MVC3 RADASP.NET MVC3 RAD
ASP.NET MVC3 RAD
 
Web I - 04 - Forms
Web I - 04 - FormsWeb I - 04 - Forms
Web I - 04 - Forms
 
Excel vba
Excel vbaExcel vba
Excel vba
 
Transforming Power Point Show with VBA
Transforming Power Point Show with VBATransforming Power Point Show with VBA
Transforming Power Point Show with VBA
 
Advisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScriptAdvisor Jumpstart: JavaScript
Advisor Jumpstart: JavaScript
 
E learning excel vba programming lesson 2
E learning excel vba programming  lesson 2E learning excel vba programming  lesson 2
E learning excel vba programming lesson 2
 
A Lap Around Visual Studio 2010
A Lap Around Visual Studio 2010A Lap Around Visual Studio 2010
A Lap Around Visual Studio 2010
 
VBA
VBAVBA
VBA
 
How to build accessible UI components
How to build accessible UI componentsHow to build accessible UI components
How to build accessible UI components
 
Html advanced-reference-guide for creating web forms
Html advanced-reference-guide for creating web formsHtml advanced-reference-guide for creating web forms
Html advanced-reference-guide for creating web forms
 
Angular
AngularAngular
Angular
 
Walkthrough asp.net
Walkthrough asp.netWalkthrough asp.net
Walkthrough asp.net
 
20 Office 365 Productivity Tips that you've probably never used (but should)
20 Office 365 Productivity Tips that you've probably never used (but should)20 Office 365 Productivity Tips that you've probably never used (but should)
20 Office 365 Productivity Tips that you've probably never used (but should)
 
Cis 407 i lab 2 of 7
Cis 407 i lab 2 of 7Cis 407 i lab 2 of 7
Cis 407 i lab 2 of 7
 
Handling errors in t sql code (1)
Handling errors in t sql code (1)Handling errors in t sql code (1)
Handling errors in t sql code (1)
 
Vba introduction
Vba introductionVba introduction
Vba introduction
 
Diving into VS 2015 Day1
Diving into VS 2015 Day1Diving into VS 2015 Day1
Diving into VS 2015 Day1
 
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
ChircuVictor StefircaMadalin rad_aspmvc3_wcf_vs2010
 
Vba
Vba Vba
Vba
 
Cis407 a ilab 2 web application development devry university
Cis407 a ilab 2 web application development devry universityCis407 a ilab 2 web application development devry university
Cis407 a ilab 2 web application development devry university
 

Semelhante a Access tips access and sql part 4 building select queries on-the-fly

Access tips access and sql part 6 dynamic reports
Access tips  access and sql part 6  dynamic reportsAccess tips  access and sql part 6  dynamic reports
Access tips access and sql part 6 dynamic reportsquest2900
 
Access tips access and sql part 3 practical examples
Access tips  access and sql part 3  practical examplesAccess tips  access and sql part 3  practical examples
Access tips access and sql part 3 practical examplesquest2900
 
Sww 2008 Automating Your Designs Excel, Vba And Beyond
Sww 2008   Automating Your Designs   Excel, Vba And BeyondSww 2008   Automating Your Designs   Excel, Vba And Beyond
Sww 2008 Automating Your Designs Excel, Vba And BeyondRazorleaf Corporation
 
BUSI 301 Book Review RubricScoreCommentsResearch 25.docx
BUSI 301 Book Review RubricScoreCommentsResearch 25.docxBUSI 301 Book Review RubricScoreCommentsResearch 25.docx
BUSI 301 Book Review RubricScoreCommentsResearch 25.docxhumphrieskalyn
 
Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web MahmoudOHassouna
 
Access tips access and sql part 5 more instant queries 1
Access tips  access and sql part 5  more instant queries 1Access tips  access and sql part 5  more instant queries 1
Access tips access and sql part 5 more instant queries 1quest2900
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S GuideAlicia Buske
 
Access tips access and sql part 1 setting the sql scene
Access tips  access and sql part 1  setting the sql sceneAccess tips  access and sql part 1  setting the sql scene
Access tips access and sql part 1 setting the sql scenequest2900
 
Sql interview question part 8
Sql interview question part 8Sql interview question part 8
Sql interview question part 8kaashiv1
 
Automation Of Reporting And Alerting
Automation Of Reporting And AlertingAutomation Of Reporting And Alerting
Automation Of Reporting And AlertingSean Durocher
 
Better User Experience with .NET
Better User Experience with .NETBetter User Experience with .NET
Better User Experience with .NETPeter Gfader
 
It203 class slides-unit5
It203 class slides-unit5It203 class slides-unit5
It203 class slides-unit5Matthew Moldvan
 
Oracle application express
Oracle application expressOracle application express
Oracle application expressAbhinaw Kumar
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Rich Helton
 
Oracle application express ppt
Oracle application express pptOracle application express ppt
Oracle application express pptAbhinaw Kumar
 

Semelhante a Access tips access and sql part 4 building select queries on-the-fly (20)

Access tips access and sql part 6 dynamic reports
Access tips  access and sql part 6  dynamic reportsAccess tips  access and sql part 6  dynamic reports
Access tips access and sql part 6 dynamic reports
 
Access tips access and sql part 3 practical examples
Access tips  access and sql part 3  practical examplesAccess tips  access and sql part 3  practical examples
Access tips access and sql part 3 practical examples
 
Sww 2008 Automating Your Designs Excel, Vba And Beyond
Sww 2008   Automating Your Designs   Excel, Vba And BeyondSww 2008   Automating Your Designs   Excel, Vba And Beyond
Sww 2008 Automating Your Designs Excel, Vba And Beyond
 
BUSI 301 Book Review RubricScoreCommentsResearch 25.docx
BUSI 301 Book Review RubricScoreCommentsResearch 25.docxBUSI 301 Book Review RubricScoreCommentsResearch 25.docx
BUSI 301 Book Review RubricScoreCommentsResearch 25.docx
 
Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web Murach : How to develop a single-page MVC web
Murach : How to develop a single-page MVC web
 
Access tips access and sql part 5 more instant queries 1
Access tips  access and sql part 5  more instant queries 1Access tips  access and sql part 5  more instant queries 1
Access tips access and sql part 5 more instant queries 1
 
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5  Building Your First Web Application (A Beginner S GuideASP.NET MVC 5  Building Your First Web Application (A Beginner S Guide
ASP.NET MVC 5 Building Your First Web Application (A Beginner S Guide
 
Access tips access and sql part 1 setting the sql scene
Access tips  access and sql part 1  setting the sql sceneAccess tips  access and sql part 1  setting the sql scene
Access tips access and sql part 1 setting the sql scene
 
Sql interview question part 8
Sql interview question part 8Sql interview question part 8
Sql interview question part 8
 
Ebook8
Ebook8Ebook8
Ebook8
 
Automation Of Reporting And Alerting
Automation Of Reporting And AlertingAutomation Of Reporting And Alerting
Automation Of Reporting And Alerting
 
Automating SolidWorks with Excel
Automating SolidWorks with ExcelAutomating SolidWorks with Excel
Automating SolidWorks with Excel
 
Knockout in action
Knockout in actionKnockout in action
Knockout in action
 
Better User Experience with .NET
Better User Experience with .NETBetter User Experience with .NET
Better User Experience with .NET
 
Mca 504 dotnet_unit5
Mca 504 dotnet_unit5Mca 504 dotnet_unit5
Mca 504 dotnet_unit5
 
It203 class slides-unit5
It203 class slides-unit5It203 class slides-unit5
It203 class slides-unit5
 
Oracle application express
Oracle application expressOracle application express
Oracle application express
 
Mule data bases
Mule data basesMule data bases
Mule data bases
 
Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4Overview of CSharp MVC3 and EF4
Overview of CSharp MVC3 and EF4
 
Oracle application express ppt
Oracle application express pptOracle application express ppt
Oracle application express ppt
 

Mais de quest2900

Storyboard pro 2_sp1_user_guide
Storyboard pro 2_sp1_user_guideStoryboard pro 2_sp1_user_guide
Storyboard pro 2_sp1_user_guidequest2900
 
Installing sap7
Installing sap7Installing sap7
Installing sap7quest2900
 
2nd examiners report
2nd examiners report2nd examiners report
2nd examiners reportquest2900
 
Shares course 01
Shares course 01Shares course 01
Shares course 01quest2900
 
Access tips access and sql part 2 putting vba and sql together
Access tips  access and sql part 2  putting vba and sql togetherAccess tips  access and sql part 2  putting vba and sql together
Access tips access and sql part 2 putting vba and sql togetherquest2900
 
Uae civil-code- english-translation-
Uae civil-code- english-translation-Uae civil-code- english-translation-
Uae civil-code- english-translation-quest2900
 
Uae civil procedure code2
Uae civil procedure code2Uae civil procedure code2
Uae civil procedure code2quest2900
 

Mais de quest2900 (7)

Storyboard pro 2_sp1_user_guide
Storyboard pro 2_sp1_user_guideStoryboard pro 2_sp1_user_guide
Storyboard pro 2_sp1_user_guide
 
Installing sap7
Installing sap7Installing sap7
Installing sap7
 
2nd examiners report
2nd examiners report2nd examiners report
2nd examiners report
 
Shares course 01
Shares course 01Shares course 01
Shares course 01
 
Access tips access and sql part 2 putting vba and sql together
Access tips  access and sql part 2  putting vba and sql togetherAccess tips  access and sql part 2  putting vba and sql together
Access tips access and sql part 2 putting vba and sql together
 
Uae civil-code- english-translation-
Uae civil-code- english-translation-Uae civil-code- english-translation-
Uae civil-code- english-translation-
 
Uae civil procedure code2
Uae civil procedure code2Uae civil procedure code2
Uae civil procedure code2
 

Último

➥🔝 7737669865 🔝▻ Sambalpur Call-girls in Women Seeking Men 🔝Sambalpur🔝 Esc...
➥🔝 7737669865 🔝▻ Sambalpur Call-girls in Women Seeking Men  🔝Sambalpur🔝   Esc...➥🔝 7737669865 🔝▻ Sambalpur Call-girls in Women Seeking Men  🔝Sambalpur🔝   Esc...
➥🔝 7737669865 🔝▻ Sambalpur Call-girls in Women Seeking Men 🔝Sambalpur🔝 Esc...amitlee9823
 
Just Call Vip call girls kakinada Escorts ☎️9352988975 Two shot with one girl...
Just Call Vip call girls kakinada Escorts ☎️9352988975 Two shot with one girl...Just Call Vip call girls kakinada Escorts ☎️9352988975 Two shot with one girl...
Just Call Vip call girls kakinada Escorts ☎️9352988975 Two shot with one girl...gajnagarg
 
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...amitlee9823
 
Just Call Vip call girls Bellary Escorts ☎️9352988975 Two shot with one girl ...
Just Call Vip call girls Bellary Escorts ☎️9352988975 Two shot with one girl ...Just Call Vip call girls Bellary Escorts ☎️9352988975 Two shot with one girl ...
Just Call Vip call girls Bellary Escorts ☎️9352988975 Two shot with one girl ...gajnagarg
 
➥🔝 7737669865 🔝▻ Bangalore Call-girls in Women Seeking Men 🔝Bangalore🔝 Esc...
➥🔝 7737669865 🔝▻ Bangalore Call-girls in Women Seeking Men  🔝Bangalore🔝   Esc...➥🔝 7737669865 🔝▻ Bangalore Call-girls in Women Seeking Men  🔝Bangalore🔝   Esc...
➥🔝 7737669865 🔝▻ Bangalore Call-girls in Women Seeking Men 🔝Bangalore🔝 Esc...amitlee9823
 
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...SUHANI PANDEY
 
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...ZurliaSoop
 
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...amitlee9823
 
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangaloreamitlee9823
 
Detecting Credit Card Fraud: A Machine Learning Approach
Detecting Credit Card Fraud: A Machine Learning ApproachDetecting Credit Card Fraud: A Machine Learning Approach
Detecting Credit Card Fraud: A Machine Learning ApproachBoston Institute of Analytics
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...amitlee9823
 
➥🔝 7737669865 🔝▻ malwa Call-girls in Women Seeking Men 🔝malwa🔝 Escorts Ser...
➥🔝 7737669865 🔝▻ malwa Call-girls in Women Seeking Men  🔝malwa🔝   Escorts Ser...➥🔝 7737669865 🔝▻ malwa Call-girls in Women Seeking Men  🔝malwa🔝   Escorts Ser...
➥🔝 7737669865 🔝▻ malwa Call-girls in Women Seeking Men 🔝malwa🔝 Escorts Ser...amitlee9823
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...amitlee9823
 
Call Girls In Hsr Layout ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Hsr Layout ☎ 7737669865 🥵 Book Your One night StandCall Girls In Hsr Layout ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Hsr Layout ☎ 7737669865 🥵 Book Your One night Standamitlee9823
 
➥🔝 7737669865 🔝▻ Ongole Call-girls in Women Seeking Men 🔝Ongole🔝 Escorts S...
➥🔝 7737669865 🔝▻ Ongole Call-girls in Women Seeking Men  🔝Ongole🔝   Escorts S...➥🔝 7737669865 🔝▻ Ongole Call-girls in Women Seeking Men  🔝Ongole🔝   Escorts S...
➥🔝 7737669865 🔝▻ Ongole Call-girls in Women Seeking Men 🔝Ongole🔝 Escorts S...amitlee9823
 

Último (20)

Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts ServiceCall Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
Call Girls In Shalimar Bagh ( Delhi) 9953330565 Escorts Service
 
➥🔝 7737669865 🔝▻ Sambalpur Call-girls in Women Seeking Men 🔝Sambalpur🔝 Esc...
➥🔝 7737669865 🔝▻ Sambalpur Call-girls in Women Seeking Men  🔝Sambalpur🔝   Esc...➥🔝 7737669865 🔝▻ Sambalpur Call-girls in Women Seeking Men  🔝Sambalpur🔝   Esc...
➥🔝 7737669865 🔝▻ Sambalpur Call-girls in Women Seeking Men 🔝Sambalpur🔝 Esc...
 
Just Call Vip call girls kakinada Escorts ☎️9352988975 Two shot with one girl...
Just Call Vip call girls kakinada Escorts ☎️9352988975 Two shot with one girl...Just Call Vip call girls kakinada Escorts ☎️9352988975 Two shot with one girl...
Just Call Vip call girls kakinada Escorts ☎️9352988975 Two shot with one girl...
 
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
Escorts Service Kumaraswamy Layout ☎ 7737669865☎ Book Your One night Stand (B...
 
Just Call Vip call girls Bellary Escorts ☎️9352988975 Two shot with one girl ...
Just Call Vip call girls Bellary Escorts ☎️9352988975 Two shot with one girl ...Just Call Vip call girls Bellary Escorts ☎️9352988975 Two shot with one girl ...
Just Call Vip call girls Bellary Escorts ☎️9352988975 Two shot with one girl ...
 
➥🔝 7737669865 🔝▻ Bangalore Call-girls in Women Seeking Men 🔝Bangalore🔝 Esc...
➥🔝 7737669865 🔝▻ Bangalore Call-girls in Women Seeking Men  🔝Bangalore🔝   Esc...➥🔝 7737669865 🔝▻ Bangalore Call-girls in Women Seeking Men  🔝Bangalore🔝   Esc...
➥🔝 7737669865 🔝▻ Bangalore Call-girls in Women Seeking Men 🔝Bangalore🔝 Esc...
 
Abortion pills in Jeddah | +966572737505 | Get Cytotec
Abortion pills in Jeddah | +966572737505 | Get CytotecAbortion pills in Jeddah | +966572737505 | Get Cytotec
Abortion pills in Jeddah | +966572737505 | Get Cytotec
 
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
VIP Model Call Girls Hinjewadi ( Pune ) Call ON 8005736733 Starting From 5K t...
 
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Surabaya ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
Call Girls Bannerghatta Road Just Call 👗 7737669865 👗 Top Class Call Girl Ser...
 
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service BangaloreCall Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
Call Girls Begur Just Call 👗 7737669865 👗 Top Class Call Girl Service Bangalore
 
Detecting Credit Card Fraud: A Machine Learning Approach
Detecting Credit Card Fraud: A Machine Learning ApproachDetecting Credit Card Fraud: A Machine Learning Approach
Detecting Credit Card Fraud: A Machine Learning Approach
 
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
Junnasandra Call Girls: 🍓 7737669865 🍓 High Profile Model Escorts | Bangalore...
 
CHEAP Call Girls in Rabindra Nagar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Rabindra Nagar  (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Rabindra Nagar  (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Rabindra Nagar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
➥🔝 7737669865 🔝▻ malwa Call-girls in Women Seeking Men 🔝malwa🔝 Escorts Ser...
➥🔝 7737669865 🔝▻ malwa Call-girls in Women Seeking Men  🔝malwa🔝   Escorts Ser...➥🔝 7737669865 🔝▻ malwa Call-girls in Women Seeking Men  🔝malwa🔝   Escorts Ser...
➥🔝 7737669865 🔝▻ malwa Call-girls in Women Seeking Men 🔝malwa🔝 Escorts Ser...
 
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
Call Girls Hsr Layout Just Call 👗 7737669865 👗 Top Class Call Girl Service Ba...
 
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Saket (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Call Girls In Hsr Layout ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Hsr Layout ☎ 7737669865 🥵 Book Your One night StandCall Girls In Hsr Layout ☎ 7737669865 🥵 Book Your One night Stand
Call Girls In Hsr Layout ☎ 7737669865 🥵 Book Your One night Stand
 
➥🔝 7737669865 🔝▻ Ongole Call-girls in Women Seeking Men 🔝Ongole🔝 Escorts S...
➥🔝 7737669865 🔝▻ Ongole Call-girls in Women Seeking Men  🔝Ongole🔝   Escorts S...➥🔝 7737669865 🔝▻ Ongole Call-girls in Women Seeking Men  🔝Ongole🔝   Escorts S...
➥🔝 7737669865 🔝▻ Ongole Call-girls in Women Seeking Men 🔝Ongole🔝 Escorts S...
 
Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get CytotecAbortion pills in Doha Qatar (+966572737505 ! Get Cytotec
Abortion pills in Doha Qatar (+966572737505 ! Get Cytotec
 

Access tips access and sql part 4 building select queries on-the-fly

  • 1. 9/8/2014 Access Tips: Access and SQL Part 4: Building Select Queries On-the-Fly | Home | Excel | Access | Word | Outlook | FrontPage | VBA | Downloads | Index | Access & SQL 4 Access Home C ontinue the tutorial: Part 1: Introduction Part 2: VBA & SQL Part 3: Examples Part 4: Building Queries Part 5: More Instant Queries Part 6: Dynamic Reports Printer Friendly Version Download the File Coding Note Sometimes lines of code can be very long! Where I have had to break a line of code to fit it on the page I have used the symbol to indicate that the line below is a continuation and that the code should be written as a single line <Blah blah blah blah> should be written: <Blah blah blah blah> Access and SQL Part 4: Building Queries "On the Fly" This tutorial is about using SQL to build queries "on the fly" (or as we propellorheads say: "at run-time"). This means that you build the queries when you need them, rather than trying to anticipate the user's needs and preparing them in advance. The tutorial will deal with regular "select" queries, ones which filter the source data and show the result to the user (as opposed to "action" queries which manipulate the data in some way). You can download a copy of the database used in this tutorial. It contains completed examples of the forms, queries and code described in the tutorial. Follow the link at the bottom of this page. The database contains a table listing the details of the staff of a fictional multinational company. It contains the sort of personal details you might expect such as FirstName, LastName, BirthDate and Gender together with business details such as Office, Department, JobTitle and Email. This tutorial is in two parts. This first part will show you how to create a fully working multi-purpose query. The second part will explain how to add some refinements to create a really professional query tool. You will find a link to the second part of the tutorial at the bottom of this page. Why Build Queries on the Fly? Like many Access developers, I tend to create very few stored queries. Instead I try to create a small number of general purpose queries that can be changed on demand to suit the user's requirements. 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 the information from the user which is used to create the query's SQL statement. The user is really building a query themselves but they don't need to know anything about Access to do it. Another important reason for working this way is that inquisitive (or careless!) users might delete or change stored queries, and not know how to replace them. Building a Multi-Purpose Query The Plan... The aim of this project is to create a single stored query whose criteria can be changed to suit the user's requirements. The query will be opened when the user clicks a button on a dialog box. The dialog box will also be used to gather the criteria from the user. The Stored Query You need a query that can be used as the basis of our multi-purpose query. Its design is completely irrelevant because it is going to be changed each time it is used, but Access doesn't let you create an "empty" query so you'll have to make something up (anything will do). Ask Access for a new query in design view, add a table, put a field into the grid and then close and save the query. Give it a sensible name - in this example I am calling the query qryStaffListQuery. http://www.fontstuff.com/access/acctut17.htm 1/5
  • 2. 9/8/2014 Access Tips: Access and SQL Part 4: Building Select Queries On-the-Fly The Dialog Box I have decided that my users will probably want to query on three different criteria: Office, Department and Gender. So, the first step is to build a dialog box to help the users specify their criteria. It's up to you what your dialog box looks like and what it contains. I have chosen to use combo boxes showing lists of all the possible criteria choices. Future tutorials in this series will show examples of other design methods. If you are not experienced in building dialog forms like this one, take a look at my tutorial C ustomizing Access Parameter Queries which contains detailed step-by-step instructions. Point at the labels next to the combo boxes in the illustration below to see what is contained on their lists... So, now we have the required components of the multi-purpose query. The next step is to write the code to make them work together. Writing the VBA and SQL Code When the user clicks the dialog's OK button several things must happen: Gather the user's choices from the combo boxes and write them into an SQL statement. Apply the SQL statement to the stored query. Open the stored query. C lose the dialog box. The code to carry out these operations will run on the On Click event of the OK button. In form design view right-click the OK button and choose Properties to open its properties window and locate On Click on the Events tab. C lick in the white bar then click the Build button: . In the Choose Builder dialog select Code Builder and click OK. You are now ready to write the code... Declare and Fill the Variables The first few lines of code establish contact with the database, telling Access that we are referring to the current database (i.e. the one containing the code) and identifying the query that we are going to work on. In addition, a string (i.e. text) variable is declared, which I have called strSQL. It will hold the SQL statement that will be applied to the query: Dim db As DAO.Database Dim qdf As DAO.QueryDef Dim strSQL As String Set db = CurrentDb http://www.fontstuff.com/access/acctut17.htm 2/5
  • 3. 9/8/2014 Access Tips: Access and SQL Part 4: Building Select Queries On-the-Fly Set qdf = db.QueryDefs("qryStaffListQuery”) NOTE: I am using DAO language here because I think it is simpler for this sort of work. DAO is the default for Access 97, but the default for Access 2000/2002 is ADO. Access 97 users need do nothing (you can omit the "DAO." bits if you want but it doesn't really matter) but Access 2000/2002 users need to set a reference to DAO so that their database understands the code. In the Visual Basic Editor go to Tools > References. In the dialog box scroll down to "Microsoft DAO 3.x Object Library" (where x is the highest number if you have more than one) and put a tick in the box. C lick OK to set the reference. You only need to do this once for the database and any code you put in it will be able to use the reference. Build the SQL Statement Next comes a VBA statement which places a text string into the strSQL variable. There was a detailed explanation of how I like to write my VBA/SQL and the rules you need to know in the second tutorial in this series: Access and SQL Part 2: Putting VBA and SQL Together. This code combines SQL keywords and clauses into which have been placed references to the combo boxes that contain the user's criteria choices: strSQL = "SELECT tblStaff.* ” & _ "FROM tblStaff ” & _ "WHERE tblStaff.Office='" & Me.cboOffice.Value & "’ ” & _ "AND tblStaff.Department='" & Me.cboDepartment.Value & "’ ” & _ "AND tblStaff.Gender='" & Me.cboGender.Value & "’ ” & _ "ORDER BY tblStaff.LastName,tblStaff.FirstName;” Although it doesn't seem to make a readable SQL statement as it is, when Access reads the code and substitutes, for example, Me.cboOffice.Value with London a sensible SQL statement results. Here is what your code should look like so far [click the thumbnail to see a full-sized image]: Test the Code Now is a good time to test the code you have written so far and there are a couple of ways you can do this. You can "print" the SQL to the Immediate Window or you can display it in a message box (or you can do both!). Here's what to do: Using the Immediate Window: In Access 97 the Immediate Window is called the Immediate (lower) pane of the Debug Window. In all versions the window can be displayed by pressing Ctrl+G from the VBA code window. First, add the following line of code before the End Sub line of your cmdOK_Click procedure: Debug.Print strSQL Using a Message Box: Add the following line of code before the End Sub line of your cmdOK_Click procedure: MsgBox strSQL Now you are ready to run a test. Switch to Access and open your dialog box in Form View (now is a good time to save the form!). Make some choices from the combo http://www.fontstuff.com/access/acctut17.htm 3/5
  • 4. 9/8/2014 Access Tips: Access and SQL Part 4: Building Select Queries On-the-Fly boxes and click the OK button... If you chose to use a message box it will open displaying the SQL string that your code created from the choices in the dialog box. Read the SQL statement to check that it makes sense: If you chose to use the Immediate Window, switch to the VBA code window and press Ctrl+G to open the Immediate Window where the SQL string will be displayed (it is written in a single line): The message box method is quick and, because I am familiar with SQL, it is my preferred method. Using the Immediate Window has the advantage that you can select and copy from it the SQL statement that your code generated and paste it into a query to test it. To do this first select and copy the SQL statement then return to the Access database window and choose Create query in design view. C lose the Show Table box and open the SQL window by choosing View > SQL View. Delete any entry that is already there (it usually shows SELECT;) and paste in your SQL statement. Run the query and check the result. If you see an error message when you try to run your SQL you can trace the error and correct it. Read the section on "Debugging Your SQL C ode" in Part 2 of this series. When you are satisfied that this part of your code is working properly, you can remove the line(s) Debug.Print strSQL or MsgBox strSQL. Update and Open the Query All that remains is to apply the SQL statement to the stored query that you saved earlier, and to close the dialog box. Enter the line: qdf.SQL = strSQL http://www.fontstuff.com/access/acctut17.htm 4/5
  • 5. 9/8/2014 Access Tips: Access and SQL Part 4: Building Select Queries On-the-Fly to apply your new SQL statement to the stored query. There is no need to give a command to save this change to the query because this happens automatically. Next add the lines: DoCmd.OpenQuery "qryStaffListQuery" DoCmd.Close acForm, Me.Name to open the query displaying the results of the user's criteria choices, and to close the dialog. Finally add the lines: Set qdf = Nothing Set db = Nothing which empty the variables used to identify the query and the database. All variables normally lose their values when a procedure finishes, and the memory that was allocated to them is freed. But sometimes Access forgets to clear "object" variables (those with which you have to use the "Set" keyword) so it is good coding practice to clear them manually like this, just to make sure. Your finished code should look like this [click the thumbnail to see a full-sized image]: Return to the Access database window and save the dialog box form (to save your code changes). Job Done! Your Multi-Purpose Query is now ready to run. Remember that the query should be run from the dialog box. If you open the stored query it will display records using the same criteria as the last time it was run. The Multi-Purpose Query will work fine as it is, but you can make it even more user-friendly with the addition of a few refinements. The second part of this tutorial shows you how to turn your multi-purpose query into a really professional tool. Go to the next part of the tutorial >>> ^ top http://www.fontstuff.com/access/acctut17.htm 5/5