473,769 Members | 4,591 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Dynamic Query via User-Specified Fields

Hello,

I have a user request to build a form in an Access database where the user
can check off specific fields to pull in a query. For example, let's say I
have 10 fields in a table. The user wants to be able to check off anywhere
between 1 and all 10 fields in a form and have it return a select query with
just the fields that were checked off. There are multiple users, so not all
users will be checking off the same fields. Some users will want 3 fields,
others will want 2 and they could all be different.

Thanks,
Jim
Feb 5 '06 #1
9 2904
Look up QueryDef in the Help file. You can use a multiselect listbox to
select the fields. From the fields selected in the listbox, build a dynamic
SQL string. Using the QueryDef object, associate the SQL string with the
stored query that is the recordsource for the form.

--
PC Datasheet
Your Resource For Help With Access, Excel And Word Applications
Over 1100 users have come to me from the newsgroups requesting help
re******@pcdata sheet.com
"Jimbo" <jp******@hotma il.com> wrote in message
news:gU******** *********@twist er.nyroc.rr.com ...
Hello,

I have a user request to build a form in an Access database where the user
can check off specific fields to pull in a query. For example, let's say
I
have 10 fields in a table. The user wants to be able to check off
anywhere
between 1 and all 10 fields in a form and have it return a select query
with
just the fields that were checked off. There are multiple users, so not
all
users will be checking off the same fields. Some users will want 3
fields,
others will want 2 and they could all be different.

Thanks,
Jim

Feb 5 '06 #2

"PC Datasheet" <no****@nospam. spam> schreef in bericht news:zl******** **********@news read3.news.atl. earthlink.net.. .
--
PC Datasheet
Your Resource For Help With Access, Excel And Word Applications
Over 1100 users have come to me from the newsgroups requesting help
re******@pcdata sheet.com


--
To Steve:
Over 350 users from the newsgroups have visited the website to read what kind of a 'resource' you are...

To the original poster:

Most people here have a common belief that the newsgroups are for *free exchange of information*.
But Steve is a notorious job hunter in these groups, always trying to sell his services.

Before you intend to do business with him look at:
http://home.tiscali.nl/arracom/whoissteve.html (updated)

Arno R
Feb 5 '06 #3
Jim

I've taken it a little further. You can select a table then select the
fields to display as follows:

Create a form with two List Boxes
TableList (Row Source Type - Value List, Multi Select - None)
FieldList (Row Source Type - Field List, Multi Select -
Simple)
A Command Button, btnOpenQuery

Create a Query - DynamicQ "SELECT ID FROM Table1;" and save it. The VBA
code will modify this with each usage.

===Code behind the form===
Private Sub Form_Open(Cance l As Integer)
' Populate the TableList List Box with all table names
Dim db As Database, tbl As TableDef
Dim s As String
Set db = CurrentDb
s = ""
For Each tbl In db.TableDefs
With tbl
If Left$(.Name, 4) = "MSys" Then
' Skip system tables
Else
s = s & .Name & ";"
End If
End With
Next tbl
Me!TableList.Ro wSource = s
End Sub

Private Sub TableList_After Update()
' Populate the FieldList List Box with all field names from the selected
table
Me!FieldList.Ro wSource = Me!TableList
End Sub

Private Sub btnOpenQuery_Cl ick()
' Build the SQL to display the selected fields

Dim db As Database, qd As QueryDef, ctl As Control, s As String, Item As
Variant
Set db = CurrentDb
Set qd = db.QueryDefs("D ynamicQ")

s = "SELECT "
Set ctl = Me!FieldList
For Each Item In ctl.ItemsSelect ed
s = s & "[" & ctl.ItemData(It em) & "], "
Next Item

qd.SQL = Left$(s, Len(s) - 2) & " FROM " & Me!TableList & ";"
DoCmd.OpenQuery "DynamicQ"
End Sub

Jimbo wrote:

Hello,

I have a user request to build a form in an Access database where the user can check off specific fields to pull in a query. For example, let's say I have 10 fields in a table. The user wants to be able to check off anywhere between 1 and all 10 fields in a form and have it return a select query with just the fields that were checked off. There are multiple users, so not all users will be checking off the same fields. Some users will want 3 fields, others will want 2 and they could all be different. Thanks,
Jim

*** Sent via Developersdex http://www.developersdex.com ***
Feb 5 '06 #4
Thank you Steve! I will give this a try at work tomorrow.
"steve.minn aar" <st*****@concis e.com> wrote in message
news:PZ******** *******@news.us west.net...
Jim

I've taken it a little further. You can select a table then select the
fields to display as follows:

Create a form with two List Boxes
TableList (Row Source Type - Value List, Multi Select - None)
FieldList (Row Source Type - Field List, Multi Select -
Simple)
A Command Button, btnOpenQuery

Create a Query - DynamicQ "SELECT ID FROM Table1;" and save it. The VBA
code will modify this with each usage.

===Code behind the form===
Private Sub Form_Open(Cance l As Integer)
' Populate the TableList List Box with all table names
Dim db As Database, tbl As TableDef
Dim s As String
Set db = CurrentDb
s = ""
For Each tbl In db.TableDefs
With tbl
If Left$(.Name, 4) = "MSys" Then
' Skip system tables
Else
s = s & .Name & ";"
End If
End With
Next tbl
Me!TableList.Ro wSource = s
End Sub

Private Sub TableList_After Update()
' Populate the FieldList List Box with all field names from the selected
table
Me!FieldList.Ro wSource = Me!TableList
End Sub

Private Sub btnOpenQuery_Cl ick()
' Build the SQL to display the selected fields

Dim db As Database, qd As QueryDef, ctl As Control, s As String, Item As
Variant
Set db = CurrentDb
Set qd = db.QueryDefs("D ynamicQ")

s = "SELECT "
Set ctl = Me!FieldList
For Each Item In ctl.ItemsSelect ed
s = s & "[" & ctl.ItemData(It em) & "], "
Next Item

qd.SQL = Left$(s, Len(s) - 2) & " FROM " & Me!TableList & ";"
DoCmd.OpenQuery "DynamicQ"
End Sub

Jimbo wrote:

Hello,

I have a user request to build a form in an Access database where the

user
can check off specific fields to pull in a query. For example, let's

say I
have 10 fields in a table. The user wants to be able to check off

anywhere
between 1 and all 10 fields in a form and have it return a select

query with
just the fields that were checked off. There are multiple users, so

not all
users will be checking off the same fields. Some users will want 3

fields,
others will want 2 and they could all be different.

Thanks,
Jim

*** Sent via Developersdex http://www.developersdex.com ***

Feb 5 '06 #5
Steve, THANK YOU!!!!! This worked exceptionally well! I built the form and
the query, then copied your code into the VB editor for the form. It worked
immediately! Thanks very much again!

I actually modified it very slightly. I really only need one table to be
shown, so I put the name of the table into the code and removed the
instances for all tables where necessary.

One last question for you - is it possible to do this with a 'group by'
query instead of a 'select' query? The sales folks would like their sales
units and gross sales in every query and summed up (the dynamic parts would
still be dynamic - sales by customer, territory, product, etc.)
"steve.minn aar" <st*****@concis e.com> wrote in message
news:PZ******** *******@news.us west.net...
Jim

I've taken it a little further. You can select a table then select the
fields to display as follows:

Create a form with two List Boxes
TableList (Row Source Type - Value List, Multi Select - None)
FieldList (Row Source Type - Field List, Multi Select -
Simple)
A Command Button, btnOpenQuery

Create a Query - DynamicQ "SELECT ID FROM Table1;" and save it. The VBA
code will modify this with each usage.

===Code behind the form===
Private Sub Form_Open(Cance l As Integer)
' Populate the TableList List Box with all table names
Dim db As Database, tbl As TableDef
Dim s As String
Set db = CurrentDb
s = ""
For Each tbl In db.TableDefs
With tbl
If Left$(.Name, 4) = "MSys" Then
' Skip system tables
Else
s = s & .Name & ";"
End If
End With
Next tbl
Me!TableList.Ro wSource = s
End Sub

Private Sub TableList_After Update()
' Populate the FieldList List Box with all field names from the selected
table
Me!FieldList.Ro wSource = Me!TableList
End Sub

Private Sub btnOpenQuery_Cl ick()
' Build the SQL to display the selected fields

Dim db As Database, qd As QueryDef, ctl As Control, s As String, Item As
Variant
Set db = CurrentDb
Set qd = db.QueryDefs("D ynamicQ")

s = "SELECT "
Set ctl = Me!FieldList
For Each Item In ctl.ItemsSelect ed
s = s & "[" & ctl.ItemData(It em) & "], "
Next Item

qd.SQL = Left$(s, Len(s) - 2) & " FROM " & Me!TableList & ";"
DoCmd.OpenQuery "DynamicQ"
End Sub

Jimbo wrote:

Hello,

I have a user request to build a form in an Access database where the

user
can check off specific fields to pull in a query. For example, let's

say I
have 10 fields in a table. The user wants to be able to check off

anywhere
between 1 and all 10 fields in a form and have it return a select

query with
just the fields that were checked off. There are multiple users, so

not all
users will be checking off the same fields. Some users will want 3

fields,
others will want 2 and they could all be different.

Thanks,
Jim

*** Sent via Developersdex http://www.developersdex.com ***

Feb 7 '06 #6

Jimbo Wrote:
One last question for you - is it possible to do this
with a 'group by' query instead of a 'select' query?
The sales folks would like their sales units and gross
sales in every query and summed up (the dynamic parts
would still be dynamic - sales by customer, territory,
product, etc.)


I'm not sure what you need. If your sales table was like the simple
example below:

SalesPerson Region Grade Amount
John North A 10
John North B 11
John South A 12
John South B 13
John West A 14
John West B 15
Mary North A 10
Mary North B 11
Mary South A 12
Mary South B 13
Mary West A 14
Mary West B 15

Should SalesPerson by Grade produce?

SalesPerson Grade Amount Total
John A 36
John B 39
Mary A 36
Mary B 39

This would require distinguishing fields which can be Summed, Averaged
etc. from those which cannot like text fields. A Check Box on the form
would indicate whether the query should return detailed or summary
values. I can do this.

If the requirement is more complex then the simple solution might be to
teach your sales staff enough Access to build their own queries.

*** Sent via Developersdex http://www.developersdex.com ***
Feb 7 '06 #7
Your example is exactly right Steve. If it's too complex or too much
trouble, I'll pursue the idea of teaching the sales staff some basic
querying. I actually considered that earlier as the form already returns a
query that they can edit, but figured I'd run it by you first in case it
wasn't too complex.

Thanks again for all of your help and advice!!
"steve.minn aar" <st*****@concis e.com> wrote in message
news:_V******** *********@news. uswest.net...

Jimbo Wrote:
One last question for you - is it possible to do this
with a 'group by' query instead of a 'select' query?
The sales folks would like their sales units and gross
sales in every query and summed up (the dynamic parts
would still be dynamic - sales by customer, territory,
product, etc.)


I'm not sure what you need. If your sales table was like the simple
example below:

SalesPerson Region Grade Amount
John North A 10
John North B 11
John South A 12
John South B 13
John West A 14
John West B 15
Mary North A 10
Mary North B 11
Mary South A 12
Mary South B 13
Mary West A 14
Mary West B 15

Should SalesPerson by Grade produce?

SalesPerson Grade Amount Total
John A 36
John B 39
Mary A 36
Mary B 39

This would require distinguishing fields which can be Summed, Averaged
etc. from those which cannot like text fields. A Check Box on the form
would indicate whether the query should return detailed or summary
values. I can do this.

If the requirement is more complex then the simple solution might be to
teach your sales staff enough Access to build their own queries.

*** Sent via Developersdex http://www.developersdex.com ***

Feb 7 '06 #8
Jimbo, I'll take it to the next stage. It's an interesting problem and
should be useful.

Jimbo Wrote:
Your example is exactly right Steve. If it's too complex
or too much trouble, I'll pursue the idea of teaching the
sales staff some basic querying. I actually considered
that earlier as the form already returns a query that
they can edit, but figured I'd run it by you first in
case it wasn't too complex.

*** Sent via Developersdex http://www.developersdex.com ***
Feb 7 '06 #9
Finally here's the grouping solution (work got in the way of play)

Option Compare Database
Option Explicit

Private Sub Form_Open(Cance l As Integer)
' Populate the TableList List Box with all table names
Dim db As Database, Tbl As TableDef
Dim s As String
Set db = CurrentDb
s = ""
For Each Tbl In db.TableDefs
With Tbl
If Left$(.Name, 4) = "MSys" Then
' Skip system tables
Else
s = s & .Name & ";"
End If
End With
Next Tbl
Me!TableList.Ro wSource = s
End Sub

Private Sub TableList_After Update()
' Populate the FieldList List Box with all field names from the selected
table
Me!FieldList.Ro wSource = Me!TableList
End Sub

Private Sub btnGroupQuery_C lick()
' Build the SQL to display the selected fields

' Create DynamicQ manually as, say, SELECT ID FROM Table1; and save it.
' This code will replace the SQL with each usage.
Dim db As Database, qd As QueryDef, ctl As Control, s As String, Item As
Variant
Dim Tbl As TableDef, Fld As Field, FieldName As String, Tail As String
Set db = CurrentDb
Set qd = db.QueryDefs("D ynamicQ")
If IsNull(Me!Table List) Then
MsgBox "No table selected"
Else
Set Tbl = db.TableDefs(Me !TableList)
' Field Data type values
' 1 dbBoolean Boolean
' 2 dbByte Byte
' 3 dbInteger Integer
' 4 dbLong Long
' 5 dbCurrency Currency
' 6 dbSingle Single
' 7 dbDouble Double
' 8 dbDate Date / Time
' 9 dbBinary Binary
' 10 dbText Text
' 11 dbLongBinary Long Binary (OLE Object)
' 12 dbMemo Memo
' 15 dbGUID Guid
' 16 dbBigInt Big Integer
' 17 dbVarBinary VarBinary
' 18 dbChar Char
' 19 dbNumeric Numeric
' 20 dbDecimal Decimal
' 21 dbFloat Float
' 22 dbTime Time
' 23 dbTimeStamp Time Stamp
' Note that numeric types range from 2 to 7
s = "SELECT "
Tail = " GROUP BY "
' SELECT SalesPerson, Region, Sum(Amount) AS SumOfAmount
' FROM Sales
' GROUP BY SalesPerson, Region;
Set ctl = Me!FieldList
For Each Item In ctl.ItemsSelect ed
FieldName = ctl.ItemData(It em)
If Tbl.Fields(Fiel dName).Type > 1 And Tbl.Fields(Fiel dName).Type
< 8 Then
s = s & "Sum([" & FieldName & "]) AS [SumOf" & FieldName &
"], "
Else
s = s & "[" & FieldName & "], "
Tail = Tail & "[" & FieldName & "], "
End If
Next Item
If s = "SELECT " Then
MsgBox "No fields selected"
Else
s = Left$(s, Len(s) - 2) & " FROM [" & Me!TableList & "]"
If Tail <> " GROUP BY " Then s = s & Left$(Tail, Len(Tail) - 2)
qd.SQL = s & ";"
DoCmd.OpenQuery "DynamicQ"
End If
End If
End Sub

Private Sub btnSelectQuery_ Click()
Dim db As Database, qd As QueryDef, ctl As Control, s As String, Item As
Variant
Set db = CurrentDb
Set qd = db.QueryDefs("D ynamicQ")

s = "SELECT "
Set ctl = Me!FieldList
For Each Item In ctl.ItemsSelect ed
s = s & "[" & ctl.ItemData(It em) & "], "
Next Item
If s = "SELECT " Then
MsgBox "No fields selected."
Else
qd.SQL = Left$(s, Len(s) - 2) & " FROM [" & Me!TableList & "];"
DoCmd.OpenQuery "DynamicQ"
End If
End Sub

Replace all the code in the original example with this.

Jimbo Wrote:
One last question for you - is it possible to do this
with a 'group by' query instead of a 'select' query?
The sales folks would like their sales units and gross
sales in every query and summed up (the dynamic parts
would still be dynamic - sales by customer, territory,
product, etc.)

*** Sent via Developersdex http://www.developersdex.com ***
Feb 16 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
3227
by: moondaddy | last post by:
I'm writing an ecommerce app in asp.net/vb.net and need to make the pages searchable and crawlable by spiders, particularly Google's. As far as I know, if my pages's contents are mostly populated by user controls on a single page and I call these different controls by passing one or more parameters like this: myweb.com/default.aspx?MenuID=44, then the spiders aren't going to be able do to anything with this. asp.net offers lots of great...
2
2560
by: Dave Williamson | last post by:
When a ASPX page is created with dynamic controls based on what the user is doing the programmer must recreate the dynamic controls again on PostBack in the Page_Load so that it's events are wired and are called like a static control. Here is the problem that I need to solve. The processing overhead that occurs to determine what dynamic controls need to be added involves business logic and a query or queries of data in a sql server...
1
2949
by: LilC | last post by:
I'm creating an application that has a standard layout for all pages. The information that is displayed in the layout will be dynamic based on the user that is logged in. Thus when a page is browsed to, I need to check to see if the user has logged in or not. Then if they have logged in, I need to pull their information from the database to display in the header. In previous applications, I made use of a base web page that all the...
3
1754
by: topmind | last post by:
I am generally new to dot.net, coming from "scriptish" web languages such as ColdFusion and Php. I have a few questions if you don't mind. First, how does one go about inserting dynamic SQL during run-time without lots of quotes? For example, adding "AND" clauses that may or may not be present based on the query criteria form. Some of the asp.net examples use the one-line append approach which
0
2301
by: cfaheybestpitch | last post by:
Hi There, I have designed a DTS package which extracts a query into an excel file. It uses a query that changes dynamically based on user preferences, so I have used the dynamic property SourceSQLStatement to feed the exact query into the DTS package. The issue, however, is that the query can be run a multitude of ways, and return a different number of columns each time. On one run, the query could return a 3 column record-set, on...
10
4936
by: jflash | last post by:
Hello all, I feel dumb having to ask this question in the first place, but I just can not figure it out. I am wanting to set my site up using dynamic urls (I'm assuming that's what they're called, an example of what I have in mind is index.php?page=). However, I can not figure out how to do this. I will eventually want to use SEF urls, but for now I'll be content just to have the dynamic urls. If anyone can tell me how to do this, I'd...
2
4672
by: chets | last post by:
Hi All, I am facing problem in executing one dynamic query in PRO *C program on linux. I want to update table mytable by data MADURAI for a column mycolumn1 where primary key is myPK.I want to use EXECUTE IMMEDIATE with context.But it is not working. Following is my piece of code. Please help. Thanks in advance. int main() {
5
3177
by: pittendrigh | last post by:
There must be millions of dynamically generated html pages out there now, built by on-the-fly php code (and jsp, perl cgi, asp, etc). Programatic page generation is transparently useful. But querying a database, negotiatinig lots of if-then-else logic and echo'ing html code out on port 80 every time a page is requested has to be a huge waste of resources. Why not use that logic to print static html instead of dynamic?
2
7106
by: tarunsanju15 | last post by:
Hi, I am writing a dynamic query in which i have to select a records depend upon the no. of values entered by user like: select * from _table where _tableColumn IN (values entered by user) the values entered come in this format: 456,465,123 bt if i pass this value in string format through a bind variable. The query is not working it is taking whole value as whole.. Please help me out.. I am writing this query in MySql
7
2372
by: dino d. | last post by:
Hi- I want to create a dynamic image with areas so that when the user clicks different areas, the user jumps to those pages. The problem is, I can't seem to figure out how to do this efficiently. Suppose I have a table,items in a database: itemid description count So, basically, I want to create an image that has 3 ovals, representing the top 3 occurring items (with the highest count) in
0
9424
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
10223
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
10000
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9866
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7413
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6675
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5448
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
3968
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3571
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.