Changing Query Criteria doesnt change query results viewed on form - sql

I have a simple database I am developing in MS Access 2010 where I have a form with a "view specific" command button and a "view all" command button. Both buttons will run a query: the specific one should apply a criteria to one of the fields, and the all one should run the query with no criteria, or with a * criteria in that field. There is another field that requires criteria for both queries, so essentially the specific button should run a query with two criteria and the all button should run a query with one criteria (or one and an * criteria). The query is a stored query I created via Design View. The "all" SQL statement is something to the effect of:
SELECT tableA.field1, tableA.field2, tableB.field1, tableB.field2
FROM tableA INNER JOIN tableB ON tableA.field3=tableB.field2
WHERE tableB.field1=True;
I want the specific query to run based off of an option chosen in a combo box on the form, so it's SQL statement should look the same, except the WHERE clause would change to:
WHERE tableB.field1=True AND tableB.field2=Forms!ViewQryResults!comboSelectSpecific;
Problem
My problem is that the specific query, I'll call it Query2, works as intended, but the all query, Query1, doesn't change the results viewed on the form. Neither query throws an error message, and it seems that the query is running again as the record total at the bottom of the screen goes away, and then comes back after the query finishes and gets a total number of records again.
Attempted Solutions
I have tried multiple different solutions to attempt to get it to work, none of which have.
I first tried to establish a parameter, but then Access prompts the user for the parameter value as soon as the form opens, which I do not want. If I simply declare the parameter using the parameter button in the ribbon in design view for the query, but do not assign it to a field as a criterion in the design grid, Access no longer prompts me for the parameter value, and I can assign its value via VBA, but then I do not know how to assign the parameter to a field criteria using VBA. My attempts throw errors that say Access doesn't recognize the name of my parameter.
I then tried altering the SQL string for the query and then requerying. I used text manipulation functions to find the WHERE clause, and replace it with a WHERE clause that has both criteria, then requeryed. To determine the proper context for the SQL string, I changed the query in Design View to do what I wanted, and then switched to SQL View and copied the SQL string that Access created to represent the query.
I then inserted a Debug.Print line to print the SQL string at each step, and compared them character by character and they match exactly, meaning the text manipulation is doing what it should be doing and creating the SQL strings correctly, or at least as Access would if I wasn't messing with them at all. I tried this from both directions, i.e. I made the stored query in the way it should be for one button, and then used code to change it for the other button, and then swapped, but neither method was successful in getting both queries to work. The basic code I tried for manipulating the SQL string is as follows:
Private Sub Query2_OnClick()
Dim d As Database
Dim q As Query
Dim strSQL As String
Dim strSQLSelectFrom As String
Dim strSQLWhereNew As String
Set d = CurrentDb
Set q = d.QueryDefs("Query2")
strSQL = q.SQL 'Saves original SQL statement
'Text Manipulations to create strSQLSelectFrom as just the SELECT and FROM portions
strSQLWhereNew = "tableB.field1=True AND tableB.field2=Forms!ViewQryResults!comboSelectSpecific;"
q.SQL = strSQLSelectFrom & strSQLWhereNew
DoCmd.Requery
Me.Refresh
Debug.Print q.SQL 'Verify text manipulations created SQL String I expect
q.SQL = strSQL 'Returns SQL to original statement
Debug.Print q.SQL 'Verify SQL statement properly returned to original statement
End Sub
This arrangement works to allow me to query specifics based on my combo box. When I click the other button, whose code just does a requery because the first button should reset SQL to the way it was, the results do not change. The query appears to run as indicated by the total records counter going away and coming back, but it never changes the results. If I go back and choose another option from my combo box, and query specific, the results update to the new specific selection.
Again, if I click the All Query button, the results remain based on the combo box selection. If I change the combo box selection, and then click All Query (which shouldn't care at all about the combo box because it isn't listed anywhere in the code for that button), the results change to the new selection, like both buttons are running specific queries. That part is the most puzzling, I can figure out why it is doing that.
I know a simple solution would be just to create a second query and stop trying to change one back and forth, but I really feel I am missing a fundamental piece that I am going to need to understand at some point, so I am really looking for that fundamental piece that will make this work.

IIUC - Simply change the form's RecordSource to point to needed saved query with .Requery:
Private Sub ViewAll_OnClick()
Me.Form.RecordSource = "Query1"
Me.Requery
End Sub
Private Sub ViewSpecific_OnClick()
Me.Form.RecordSource = "Query2"
Me.Requery
End Sub
Alternatively, you can keep the same query recordsource and filter form using DoCmd.ApplyFilter, assuming criteria controls are on same form requiring filtering. Any valid SQL WHERE clause can be used in second argument and even dynamically created.
DoCmd.ApplyFilter , "field1 = True AND field2 = '" & Forms!ViewQryResults!comboSelectSpecific & "'"
And to remove filter:
DoCmd.RunCommand acCmdRemoveAllFilters

Related

Is there a way to filter MS Access queries by multiple forms without creating multiple queries?

I maintain an MS Access database that manages forecasting, inventory, and purchasing.
Sometimes I need to update forecasts or inventory for all items, sometimes I just need to update for a single warehouse, and sometimes I need to update for a single item.
These processes are controlled by forms, and usually start with deleting existing tables, so I'll focus on those three queries.
To delete all, the user presses the button for all which runs the following:
DELETE Forecast_Days.*
FROM Forecast_Days;
To delete all records for a specific warehouse, the user presses the button on the line for that warehouse:
DELETE Forecast_Days.*
FROM Forecast_Days
WHERE [Forecast_Days]![Whse]=[Forms]![frm_Forecast_Update]![Whse_t];
To delete a single record for a single item, the user presses the button in a different form for that specific item:
DELETE Forecast_Days.*
FROM Forecast_Days
WHERE [Forecast_Days]![Whse]=[Forms]![frm_Forecast_Item_Edit]![Whse_t] AND
[Forecast_Days].[Item]=[Forms]![frm_Forecast_Item_Edit]![Item_t];
This is just the first step in a series of processes. For each process, I need to create an _all, _whse, and _item query; the only difference being the WHERE statement.
To reduce the clutter and simplify maintenance: is there a way I can set this up so that I am injecting the WHERE statement to the base query from the button.
Or is there a way to write a single query that looks at all potential parameters? My struggle with this approach is that if I push the button from form A, I don't want the query prompting the user for the values that normally come from form B.
#HansUp provided the general direction I needed. I figured I would post an answer and close this thread.
Assuming the following is a saved query named "Delete_Forecast_Days"
DELETE Forecast_Days.*
FROM Forecast_Days
In VBA, I can do the following:
Dim whereStr as String
Dim sqlStr as String
whereStr = " WHERE Whse='" & [Forms]![frm_Forecast_Update]![Whse_t] & "';"
sqlStr = CurrentDb.QueryDefs("Delete_Forecast_Days").SQL
sqlStr = left(sqlStr, Len(sqlStr) - 3) & whereStr
CurrentDb.Execute sqlStr, dbFailOnError
This will grab the SQL from a saved query, remove the ";" at the end, then append the where statement I want.
Ultimately, I decided against this approach, because I didn't want to find myself in 6 months changing a query and getting unexpected errors because the WHERE statement I wrote in VBA doesn't work with that query anymore.

UserForm not requery

I have a form, that is bound to a query. There are sveral condition on filtering the record and one of them is list box where I can select conrete values. I have a macro, that insert IN() statement into the SQL with selected values and the query results working properly and is showing the correct records.. Never the less when I use form.requery it still shows all of the items and it is not showing the results from query). When I change other filters (for example in combobox) then the form requery correctly although both of the changes launch the same macro...
I finally found a solution :) I Just put Me.RecordSource = Me.RecordSource :)
If your recordset is bound to the form just use
Me.Requery
If it is on your form within a form (subform) then use
Me!SubFormName.Form.Requery
If your form is not bound to a recordset/query you need to set the SQL string again.

Displaying results in subform only works for first query

I am trying to build the front end for a Mysql database application using linked tables in MS Access. Currently, I have a button on a form which executes a query that allows the user to search for records by a person's name. On the form, there is a subform which displays the results of the executed query.
My problem is that whenever I open the form, the subform only displays the query results for the first time the query is executed. If I try to search for another name, it will open the results set in a separate sheet and not update my subform.
How can I get the subform to update on every search?
Disclaimer: I am new to Access and do not know any VBA code.
Query:
SELECT employees.FNAME, employees.LNAME, access.NAME, access.USERNAME, access.CREATED_BY, access.ACCESS_GRANTED, access.ACCESS_TERMINATED, access.ADMIN
FROM employees INNER JOIN access ON EMPLOYEES.ID = ACCESS.ID
WHERE (((employees.FNAME) Like "*" & Forms![Form1]!FNameTxt & "*"));
Picture of my form after query with name "chase" is executed
I never use dynamic parameterized query. I would use VBA code to set Filter and FilterOn properties, like:
Me.Filter = "[FName] LIKE '*" & Me.cbxFNames & "*'"
Me.FilterOn = True
If you prefer dynamic parameterized query the VBA would be: Me.Requery
If code is behind the main form then need to reference subform through container control. Recommend giving the container control a name different from the object it holds, like ctrEmps
Me.ctrEmps.Requery
The real trick is figuring out what event to put code into.

MS Acess 2003 - VBA for Update SQL query?

hey guys, could someone show me the simple update query through vb? I need to add new fields to the table (just 3) and add a couple text boxes on a form so that users can add some additional data relative to the record (which is already what this form is based on).
So the first form I have is a form that populates a list, when the user double clicks on a selection from that list, it opens a new form, so that the ID of the the table that is tied to this form that I need to add the these text boxes on (all the combo boxes and text boxes relative to one record are tied to the active form at this point, however there are all unbound. On a button click there is already vb that saves the information to the table). I did not create this however, it was built by someone who is not there anymore, and apparently is better than I at this stuff. My problem is that there is soooo much vb that checks for records, and various sql statements based on case, that I cannot decipher it to its simplest form.
So I was looking for a simple example of an update sql statement in vb so I can try to break this apart.
I need it to update the record based on the ID: sql WHERE RecordID = me.RecordID
I actually thought I knew how to do this based on examples, however every time I try, then try to run on button click, I get a run-time error of SYNTAX error, and the debug just highlights the db.execute(sql) part. So I tried to get the resulting immediate window of the sql statement, and it looks fine to me:
UPDATE tblMain
SET [Name] = "John Doe",
[DATE] = #9/30/2009#,
[TYPE] = "TypeA",
WHERE RecordID = 958;
Can I update a table without accounting for every field in the table (because this one has about 15 plus the new 3, so I am ignoring about 14 fields here, but I do not want to alter those anyway???
So as always, I appreciate the help yall!! Thanks!
EDIT:
Sorry I always forget this....I was actaully trying it DAO....
Dim db as DAO.Database
Dim sql as String
set db = CurrentDb
etc
You were thaaat close! You have a simple extra comma after your last column. Get rid of it and it works fine.
UPDATE tblMain SET
[Name] = "John Doe",
[DATE] = #9/30/2009#,
[TYPE] = "TypeA"
WHERE RecordID = 958;
Yes, you can absolutely update only a few columns rather than all of them. That is a best practice, BTW.
Finally, It's considered bad practice to name your columns after reserved words like "Name" and "Date", but I know you inherited this.
You were wise to include Debug.Print sql in your code. bpayne already pointed out the extra comma in your SQL statement.
I want to point out another trouble shooting technique you may find useful to debug SQL statement problems.
Copy the statement from the Immediate Window, and paste it into the SQL View of a new query. Modify the query in the query designer until you can get it working, then revise your VBA code to generate a matching SQL statement.
In this case you might not have noticed the extra comma. However, you could create another new query and build the UPDATE statement from scratch in the query designer. After getting that one working, you could compare its SQL View to the failing query.

Pass a parameter into an access report programmatically

I've got an existing Access MDB. I'm adding a command button to an existing Form that runs an existing report. The change being made is that this button needs to pass in a parameter containing the ID of the record being reported on - currently the report runs on every record in the MDB.
I've altered the Query that the report runs on to use a parameter for the ID value, so that now when the button is clicked Access prompts for the record ID to report on, and the report displays like it should.
However, I can't for the life of me figure out how to pass a parameter into the report for the query to use. How can I do this?
The DoCmd.OpenReport method has various arguments, one of which is a Where statement:
DoCmd.OpenReport"rptReport", acViewPreview,,"ID=" & Me.ID
That is
expression.OpenReport(ReportName, View, FilterName, WhereCondition, WindowMode, OpenArgs)
My general approach to this type of problem is to save the criteria in the database, typically a control table that has one row. Then to reference your criteria you put a query in paranthesis that returns one value, of the criteria you want. In your case, it would be something like:
(select reportID from control)
The advantage of this techinque is that the control table remembers the settings for the next time you run the report. Of course, ReportID would be tied to a field in a form. I also like the fact that your queries are isolated from forms; they can be run independently of forms.
The Where clause of the docmd.openreport is a string that uses the same format as the where clause in a SQL statement.
The reason to put parameterize you query at the docmd instead of the RecordSource of the report is flexibility. You may have a need to open the report without any paremeter/return all the records or have the ability to filter on different fields.
Why everyone wants to make this so complicated, I don't know.
save your report's recordsource without parameters.
as suggested by Remou, pass the criteria in the appropriate argument of DoCmd.OpenReport.
Trying to do it any other way is going to be a matter of resisting the natural methods for accomplishing tasks in Access.
I know this is an old post but this took me a bit. Error was "Invalid use of parren" however the issue was the space in the field name. I was creating a report from a db that someone did the common mistake, spaces.
To pass a param to a query through the where clause when the database field has a space use this example:
DoCmd.OpenReport "rptByRegionalOffice", acViewPreview, , "[" & "Regional Office" & "]" & "=" & "'" & cmboOffices.Value & "'"
If you think about this you can see that this will produce where [Regional Office]='string value' just as you would expect in access sql.