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.
Related
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
I have a query that produces a recordset that I use for a computer generated invoice that I have created with an MS Access report. The recordset looks something like this (but with hundreds of invoices):
ControlNumber|ShippingAddress|InventoryDescription|...
17-001 123 Fake St Description A
17-002 145 No addr Description B
17-003 23456 new st Description C
I have the report set up so it will generate me separate completely filled out invoices on a different page for every invoice in the system. I don't want to have to hunt through hundreds of them to find the specific one I want to print, though.
I have another MS Access form that the operator uses to select which of these invoices to print with a drop down combo box, and a button. After I use the dropdown to choose which one I want to print (say 17-003), I want to hit the button and have the report pop up with only that one single invoice. How do I tell the report to only show me a subset of that recordset?
I am fine with using existing Access functions or with writing VBA code if necessary, but I would prefer to not default to VBA if possible.
Options for dynamic filtering of report dataset:
dynamic parameterized query as the report RecordSource, this can be a popup input or reference to a control on form - I never use dynamic parameterized queries
manually open report in design view and set the Filter property then switch report to print preview then print
code (macro or VBA) applies filter when report opens by referencing control on form, example VBA: DoCmd.OpenReport "report name", , , "ControlNumber='" & Me.cbxCN & "'"
I have a combobox on a subform (ProgramSubform) in Access that's supposed to list report years for a project from a table (Program). Most projects have more than one report year, but the combobox always brings only 2014.
For example, the dropdown for project 5278 should be:
2012
2013
2014
Instead, it's only
2014
This is the select query that I'm using. It was working properly before, but I don't know when it stopped working; no changes were made to the tables or subform.
SELECT Program.ReportYear
FROM Program
WHERE (((Program.ProjNo)='ProgramSubform.ProjNo'));
Any idea why it might have stopped working, or how to fix it?
This WHERE clause asks Access to limit the rows returned by the query to those whose ProjNo values match the text string 'ProgramSubform.ProjNo'
WHERE (((Program.ProjNo)='ProgramSubform.ProjNo'))
But ProgramSubform.ProjNo is actually a data control on a subform. So don't include quotes around its name.
You can use a reference to the control via the parent form in the Forms collection:
WHERE Program.ProjNo= Forms![Parent Form]!ProgramSubform!ProjNo
If you're building the SELECT statement with VBA code in the form, you can include the control's value instead of its name:
"WHERE Program.ProjNo=" & Me!ProgramSubform!ProjNo.Value
"WHERE Program.ProjNo='" & Me!ProgramSubform!ProjNo.Value & "'"
Use the first version for a numeric field or the second for text.
Notes:
I assumed ProgramSubform is the name of the subform control. It could also be the name of the form contained in that subform control. But those names can be different. So make sure you used the subform control name.
This query is used as the Row Source for a combo box on the subform. You want to update the values displayed in the combo whenever ProjNo.Value changes. You can accomplish that by calling the combo's Requery method from the After Update event of ProjNo.
Pay attention to the brackets, you have three before Program.ProjNo on WHERE clause, but you only need two brackets (in this case) you should use:
SELECT Program.ReportYear
FROM Program
WHERE ((Program.ProjNo='ProgramSubform.ProjNo'));
anyway you will prefer:
SELECT Program.ReportYear
FROM Program
WHERE Program.ProjNo='ProgramSubform.ProjNo';
I have some code to populate a single subform on a main form with a recordset. The problem is that the records are not shown on the subform. If I open the subform as a form on it's own then with almost the same code it works perfectly:
Forms!frmCorrespondanceHolidays.RecordSource = strsql ' WORKS FINE
Me.frmCorrespondanceHolidays.Form.RecordSource = strsql 'SHOWS NO RECORDS
I have tested that if I just paste the value of strSQL into a query the correct records are returned.
I am beginning to think it is a bug in Access. I have tried recreating the database by creating a new one and importing all the objects. I have also compact & repaired. Not sure what else to try!
The name of a subform is different than the Source name of the sub report. Here is where you need to look for the name to reference in VBA. You select the subform once when the Parent form is in Design view and the look at the properties.
After further investigation I have found it is related to the sql rather than the subform. If the sql includes a query that doesn't reference the parent form records are shown. If the sql includes a query that does reference the form then no record are shown. Guess I will have to work around this limitation. Thanks for the pointers.
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.