473,765 Members | 2,081 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

how to populate a combo box with canned queries and display results

AccessIdiot
493 Contributor
I have one big fat table with goose nesting data. Things like nest location (name of island in a river), nest type (ground/platform), number of eggs, number of eggs hatched, type of predation, etc.

I have some canned queries that I need to report: total number of eggs, number of eggs by island, number of eggs by type, number of nests, number of nests by island, number of nests by type, etc. So there are a few basic questions (total # nests, total # eggs, total nest success, total nest failure) and then further filters (all of the above filtered by type, location, possibly date range).

I would LOVE to build a dynamic search form but I keep failing (combo box #1 = total # of . . .; combo box #2 = filter by type/location; 3rd filter of date range).

So now I'm trying to just build one combo box that contains all these canned queries and then have a subform or report (whatever is easiest) show the results. The queries are not simple select statements, they are sums and counts. Any ideas? All I've got right now is an unbound form with an unbound combo box that contains a value list of two columns: name of query, description of query. I'm clueless about what to put in the after update part of my combo box.

By the way this is Access 2007. Cheers!
Jul 8 '10
21 2639
AccessIdiot
493 Contributor
Broken links? Ahh, fixed, thanks, will check them out.

So here is what I have so far on an unbound form:

three combo boxes - two hidden and stacked that appear based on what the first one calls.

Two buttons: one for apply filter and one for remove filter. I found some great code for filtering a report based on a couple of combo boxes from a form.

The filter code seems to work for one combo box (cboType) but not for the other (cboIsland). I think because its trying to combine the where clause and really they are two separate where clauses but I don't know how to modify it to say "construct the where clause based on which cbo is visible".

The error I'm getting has to do with a data type mismatch but I'm not sure a) why when they are both constructed the same way and one works and the other doesn't and b) how to fix it. The tables that feed the combo boxes are two columns: auto id and text value. The combo boxes are bound to the first column but display the 2nd.

Here is the code:
Expand|Select|Wrap|Line Numbers
  1.  
  2.  
  3. Option Compare Database
  4. Private Sub cboFilterBy_AfterUpdate()
  5. If Me.cboFilterBy.Value = "Nest Type" Then
  6.     Me.cboType.Visible = True
  7.     Me.cboIsland.Visible = False
  8. ElseIf Me.cboFilterBy.Value = "Island" Then
  9.     Me.cboIsland.Visible = True
  10.     Me.cboType.Visible = False
  11. Else
  12.     Me.cboType.Visible = False
  13.     Me.cboIsland.Visible = False
  14. End If
  15. End Sub
  16.  
  17. Private Sub Form_Current()
  18.  
  19. If Me.cboFilterBy.Value = "Nest Type" Then
  20.     Me.cboType.Visible = True
  21.     Me.cboIsland.Visible = False
  22. ElseIf Me.cboFilterBy.Value = "Island" Then
  23.     Me.cboIsland.Visible = True
  24.     Me.cboType.Visible = False
  25. Else
  26.     Me.cboType.Visible = False
  27.     Me.cboIsland.Visible = False
  28. End If
  29. End Sub
  30.  
  31. Private Sub Form_Load()
  32.      DoCmd.OpenReport "rpt_NestingMain", acViewPreview
  33. End Sub
  34.  
  35. Private Sub cmdApplyFilter_Click()
  36.     Dim strType As String
  37.     Dim strIsland As String
  38.     Dim strFilter As String
  39.  
  40. 'If a combo box is empty its value is Null so I can use an If Statement to check whether or not the user made a choice
  41. 'and then construct the appropriate SQL:
  42.  
  43.     If IsNull(Me.cboType.Value) Then
  44.         strType = "Like '*'"
  45.     Else
  46.         strType = "=" & Me.cboType.Value & ""
  47.     End If
  48.     If IsNull(Me.cboIsland.Value) Then
  49.         strIsland = "Like '*'"
  50.     Else
  51.         strIsland = "='" & Me.cboIsland.Value & "'"
  52.     End If
  53.  
  54. 'Combine the criteria to form a WHERE clause for the filter:
  55.     strFilter = "[Nest Location] " & strType & " AND [Island Name] " & strIsland
  56.     With Reports![rpt_NestingMain]
  57.          .Filter = strFilter
  58.          .FilterOn = True
  59.     End With
  60.  
  61. End Sub
  62.  
  63.  
  64. Private Sub cmdRemoveFilter_Click()
  65.      On Error Resume Next
  66.      Reports![rpt_NestingMain].FilterOn = False
  67.      Me.cboFilterBy.Value = ""
  68.      Me.cboType.Visible = False
  69.      Me.cboIsland.Visible = False
  70. End Sub
  71.  
Jul 12 '10 #11
AccessIdiot
493 Contributor
Okay, I fixed it myself - nevermind! Thanks for the links, they helped me figure out how to correctly phrase for a numeric value in the cbo. Now to filter further on date range!
Jul 12 '10 #12
jimatqsi
1,276 Recognized Expert Top Contributor
I think you are missing 2 equal signs on line 55.

Expand|Select|Wrap|Line Numbers
  1. strFilter = "[Nest Location]= " & strType & " AND [Island Name]= " & strIsland
About the datatype mismatch, how is Nest Type defined in the table? Is it a string field? You are passing the nest type through strType, which is a string, but your filter does not enclose the type in quotes, so it looks like you are treating it as a numeric value. It has to be all one way or all the other.
Did you mean
Expand|Select|Wrap|Line Numbers
  1. strFilter = "[Nest Location]= '" & strType & "' AND [Island Name]= '" & strIsland & "'"
Jim
Jul 12 '10 #13
AccessIdiot
493 Contributor
Yep you are right, its not working.

This is where I get confused. The table that the combo box is bound to has two columns: the primary key auto id and a text field that has the text I care about. So its that whole thing where you bind to one column but display two, the first with a width of zero. This was common practice in access '03 but I'm not sure if that's still how it's done with '07. It's how I have it set up.

So I'm assuming that that is why I was getting the data type error - because the code I was using was formatted for a text field when really the combo box is bound to the numeric field. This is what my code looks like now (I tried to fix it for the data type) but it is not giving me the results I want.

BTW this code is totally hacked from a couple of different examples so its probably really sloppy.


Oh and I've left in the commented out code for filtering by date because I'm going to tackle that next. :-)

I know part of the problem is the big where clause at the end where I'm including both cboType and cboIsland when really I need to filter on one or the other. I'm just not sure how to tackle that. When one is visible I need the invisible one to not be included in the where statement.

Expand|Select|Wrap|Line Numbers
  1. Option Compare Database
  2. Private Sub cboFilterBy_AfterUpdate()
  3. If Me.cboFilterBy.Value = "Nest Type" Then
  4.     Me.cboType.Visible = True
  5.     Me.cboIsland.Visible = False
  6. ElseIf Me.cboFilterBy.Value = "Island" Then
  7.     Me.cboIsland.Visible = True
  8.     Me.cboType.Visible = False
  9. Else
  10.     Me.cboType.Visible = False
  11.     Me.cboIsland.Visible = False
  12. End If
  13. End Sub
  14.  
  15. Private Sub Form_Current()
  16.  
  17. If Me.cboFilterBy.Value = "Nest Type" Then
  18.     Me.cboType.Visible = True
  19.     Me.cboIsland.Visible = False
  20. ElseIf Me.cboFilterBy.Value = "Island" Then
  21.     Me.cboIsland.Visible = True
  22.     Me.cboType.Visible = False
  23. Else
  24.     Me.cboType.Visible = False
  25.     Me.cboIsland.Visible = False
  26. End If
  27. End Sub
  28.  
  29. Private Sub Form_Load()
  30.      DoCmd.OpenReport "rpt_NestingMain", acViewPreview
  31. End Sub
  32.  
  33. Private Sub cmdApplyFilter_Click()
  34. 'Purpose:   Build up the criteria string form the non-blank search boxes, and apply to the form's Filter.
  35.     'Notes:     1. We tack " AND " on the end of each condition so you can easily add more search boxes; _
  36.                         we remove the trailing " AND " at the end.
  37.     '           2. The date range works like this: _
  38.                         Both dates      = only dates between (both inclusive. _
  39.                         Start date only = all dates from this one onwards; _
  40.                         End date only   = all dates up to (and including this one).
  41.  
  42.     Dim strFilter As String                  'The criteria string.
  43.     Dim strType As String
  44.     Dim strIsland As String
  45.     Dim lngLen As Long                      'Length of the criteria string to append to.
  46.     Const conJetDate = "\#mm\/dd\/yyyy\#"   'The format expected for dates in a JET query string.
  47. 'If a combo box is empty its value is Null so I can use an If Statement to check whether or not the user made a choice
  48. 'and then construct the appropriate SQL:
  49.  
  50.     If Me.cboType.Value > "" Then
  51.         strType = strType & " AND ([Nest Location]=" & Me.cboType.Value & ")"
  52.     End If
  53.  
  54.     If Me.cboIsland.Value > "" Then
  55.         strIsland = strIsland & " AND ([Island Name]=" & Me.cboIsland.Value & ")"
  56.     End If
  57.  
  58.     'Date field. Use the format string to add the # delimiters and get the right international format.
  59.     'If Not IsNull(Me.txtStartDate) Then
  60.         'strFilter = strFilter & "([EnteredOn] >= " & Format(Me.txtStartDate, conJetDate) & ") AND "
  61.     'End If
  62.  
  63.     'Another date field example. Use "less than the next day" since this field has times as well as dates.
  64.     'If Not IsNull(Me.txtEndDate) Then   'Less than the next day.
  65.         'strFilter = strFilter & "([EnteredOn] < " & Format(Me.txtEndDate + 1, conJetDate) & ") AND "
  66.     'End If
  67.  
  68.  '***********************************************************************
  69.     'Chop off the trailing " AND ", and use the string as the form's Filter.
  70.     '***********************************************************************
  71.     'See if the string has more than 5 characters (a trailng " AND ") to remove.
  72.     lngLen = Len(strWhere) - 5
  73.     If lngLen <= 0 Then     'Nah: there was nothing in the string.
  74.         'MsgBox "No criteria", vbInformation, "Nothing to do."
  75.     Else                    'Yep: there is something there, so remove the " AND " at the end.
  76.         strFilter = Left$(strFilter, lngLen)
  77.         'For debugging, remove the leading quote on the next line. Prints to Immediate Window (Ctrl+G).
  78.         'Debug.Print strWhere
  79.     End If
  80. 'Combine the criteria to form a WHERE clause for the filter:
  81.     strFilter = "[Nest Location] " & strType & " AND [Island Name] " & strIsland
  82.     With Reports![rpt_NestingMain]
  83.          .Filter = strFilter
  84.          .FilterOn = True
  85.     End With
  86.  
  87.  
  88. End Sub
  89.  
  90.  
  91. Private Sub cmdRemoveFilter_Click()
  92.      On Error Resume Next
  93.      Reports![rpt_NestingMain].FilterOn = False
  94.      Me.cboFilterBy.Value = ""
  95.      Me.cboType.Visible = False
  96.      Me.cboIsland.Visible = False
  97. End Sub
  98.  
Jul 12 '10 #14
AccessIdiot
493 Contributor
Okay, got it working except for date range filter. If I leave that part blank I get an error. If I put something in it does nothing. I can't figure out the right syntax to include it as part of the final filter statement.
Jul 12 '10 #15
jimatqsi
1,276 Recognized Expert Top Contributor
Try wrapping your date criteria in "#", one before and one after the date, like this
'strFilter = strFilter & "([EnteredOn] <# " & Format(Me.txtEn dDate + 1, conJetDate) & "#) AND "

Jim
Jul 13 '10 #16
AccessIdiot
493 Contributor
That didn't do it. I think the conJetDate already formats it with #'s.

I think it has something to do with how the final statement is put together.

Expand|Select|Wrap|Line Numbers
  1. Private Sub cmdApplyFilter_Click()
  2.     Dim strFilter As String 'The criteria string.
  3.     Dim strType As String
  4.     Dim strIsland As String
  5.     Dim strDate As String
  6.     Dim lngLen As Long   'Length of the criteria string to append to.
  7.     Const conJetDate = "\#mm\/dd\/yyyy\#"
  8.  
  9. If Me.cboType.Value > "" Then
  10.   strType = strType & " AND ([Nest Location]=" & Me.cboType.Value & ")"
  11. End If
  12.  
  13. If Me.cboIsland.Value > "" Then
  14.   strIsland = strIsland & " AND ([Island Name]=" & Me.cboIsland.Value & ")"
  15. End If
  16.  
  17. 'Date field. Use the format string to add the # delimiters and get the right international format.
  18. If Not IsNull (Me.txtStartDate) Then
  19.   strDate = strDate & "([Field Obs Date] >= " & Format(Me.txtStartDate, conJetDate) & ") AND "
  20. End If
  21.  
  22. If Not IsNull (Me.txtEndDate) Then   'Less than the next day.
  23.   strDate = strDate & "([Field Obs Date] < " & Format(Me.txtEndDate + 1, conJetDate) & ") AND "
  24. End If
  25.  
  26. lngLen = Len(strDate) - 5
  27. strDate = Left$(strDate, lngLen)
  28.  
  29. 'final string
  30. strFilter = "[Nest Location] " & strType & " AND [Island Name] " & strIsland & " AND [Field Obs Date] " & strDate
  31.  
  32. With Reports![rpt_NestingMain]
  33.          .Filter = strFilter
  34.          .FilterOn = True
  35. End With
  36. End Sub
  37.  
Basically I'd like to be able to enter a starting date only OR a range of dates and have it work. I believe the code came from that classic Allen Browne site.
Jul 13 '10 #17
AccessIdiot
493 Contributor
Okay, got it. That NeoPa guy sure knows what he's talking about. ;-)
Jul 13 '10 #18
jimatqsi
1,276 Recognized Expert Top Contributor
:) Yea, a lot of us noticed that.
Jul 13 '10 #19
NeoPa
32,572 Recognized Expert Moderator MVP
AccessIdiot: Okay, got it. That NeoPa guy sure knows what he's talking about. ;-)
Absolutely!! :D

M. (I won't use full name here & I can't refer to you as AccessIdiot as I know better than that),

Great to see you back again.

I just caught your latest thread and saw that you'd been back for a week or so. I'll pop over there now and see if I can't provide some sort of answer for you.

-NeoPa.

PS. How are the fish getting on up there? All mapped and documented yet?
Jul 13 '10 #20

Sign in to post your reply or Sign up for a free account.

Similar topics

6
2315
by: Jules | last post by:
Hi: I have an Access 97 Search form set up - a couple of combo boxes, a couple of text fields and a command button. I want the command button to run an SQL script and then open the results form. I can get the button to open the other form but I can't get it to run the module with the subroutine in it. This is my first sorti into programming Access so be kind - I have some SQL and ASP experience but these modules are a problem for me.
5
2457
by: Filips Benoit | last post by:
Dear all, How can i populate a combo with the field-caption-names of 1 table? Thanks Filip
5
11696
by: jdwyer05 | last post by:
Hello, I am trying to populate a combo box with only unique values. Currently I am using an access database and VB6 Enterprise. The program populates the combo box fine however, there are several repeated values in this column. What i would like to do is just show one instance of that particular record. For example: if the column has the values: Accounts Payable, Process Control, Shipping, Accounts Payable i would like the combo...
2
2030
by: mpmason14 | last post by:
i know there is a way to populate one combobox based on another, but i've never done it myself and am looking for some help. i have a table that has SwitchNo and NumberofPorts as two columns. i want to create a union query to display the correct numberofports for the selected switch in switchno. ex) SwitchNo - 1 Numberofports - 24 switchno - 2
2
1656
by: lottaviano | last post by:
I have a form with two combo boxes. The value chosen in the first combo box (cbo1) is supposed to change the values that appear in the second combo box (cbo2). This currently works great for the first record entered by the user (continuous forms). However in the second record, cbo2 shows the values influenced by cbo1 in the first record, rather than the 2nd record (i.e. it doesn't update). My problem may be that both combo boxes have...
7
22680
by: nareshpulipati | last post by:
Hi all, I am new to VB .net. Iam trying to populate the database item into combo box. Database Type:SQL(ODBC) My code retuns no value in combo box Public Class Form1 Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged Dim Cmd As Odbc.OdbcCommand Dim Con As Odbc.OdbcConnection Dim Sql As String = Nothing
18
2563
by: jmarcrum | last post by:
Hi everyone! I have a form that when the user opens it, the Date combo box on the form is populated with every month of the year. But I don't want it to do that! I want it to populate with the next 3 Sundays chronologically for the user to select from. How do I need to change my code? Here's my OnLoad event for the form... Private Sub Form_Load() Dim intSunday As Integer 'set the rowsource type Me.cmbDate.RowSourceType =...
2
7997
by: Coolboy55 | last post by:
I'm creating a report with 3 source queries. Each source query returns distinct values of the same field name (SkillID). How do I display the distinct results of all 3 queries on the same report? Thanks! CB55
4
9251
by: =?Utf-8?B?R3JlZw==?= | last post by:
Can someone give me e simple example of to populate a combo box / list box using an ArrayList? THanks.
7
3343
by: RG360 | last post by:
Hello. I am new in Access and I need assistance from Pro's I have a data entry form from 2 main tables and they have relationships with other tables. My main table only contains Field ID's, because all of these fields are referenced from other tables. On my form, these fields are Combo Boxes, wherein you can add/select from the list to populate the table. All works fine, except I would like to create a combo box to find records based...
0
10007
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9951
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
9832
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...
0
8831
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6649
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
5275
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5419
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
3531
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2805
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.