query criteria based on form field - sql

So I have a query where I select a field and set the criteria so that it only selects records based on the current value of a particular field in my form. The criteria looks like this.
[Forms]![FORMAL_CERT_REVIEW_CHECK_FORM]![REVIEW_CHECK_ID]
Pretty simple stuff. But I am running into the issue where when I run the query I get the prompt that says I need to enter a value. I know that this usually happens when you set the criteria to something that may not exist or you spelt it incorrectly, but I have checked all of this and it seems like everything looks fine.
I was curious if there is something I could be missing, like a property on the field or something that I have not thought of.

When you directly open a query which includes a reference to a form control, Access is able to retrieve the query's parameter value from that control on the open form.
However, if you attempt to use the same query as the source for a recordset, Access does not resolve the query parameter from the open form.
For example, this is my query, qryREVIEW_CHECK_ID.
SELECT f.id, f.datetime_field, f.some_text
FROM tblFoo AS f
WHERE f.id=[Forms]![FORMAL_CERT_REVIEW_CHECK_FORM]![REVIEW_CHECK_ID];
With FORMAL_CERT_REVIEW_CHECK_FORM open, everything works fine when I open the form directly ... like this for example ...
DoCmd.OpenQuery "qryREVIEW_CHECK_ID"
However, using that query as the source for a recordset triggers error 3061, "Too few parameters. Expected 1."
Dim db As DAO.database
Dim rs As DAO.Recordset
Set db = CurrentDb
Set rs = db.OpenRecordset("qryREVIEW_CHECK_ID")
The workaround is to open the recordset from the QueryDef object. And include Eval() so that Access will resolve the parameter using the parameter's name.
Dim qdf As DAO.QueryDef
Set qdf = db.QueryDefs("qryREVIEW_CHECK_ID")
qdf.Parameters(0) = Eval(qdf.Parameters(0).Name)
Set rs = qdf.OpenRecordset

Your description doesn't specify whether your form is a simple form or a sub-form. I came across the same issue and realized that I was only entering the sub-form's name in the criteria.
Assuming that you have FORMAL_CERT_REVIEW_CHECK_FORM sub-form under PARENT_FORM, your criteria should read
[Forms]![PARENT_FORM]![FORMAL_CERT_REVIEW_CHECK_FORM]![REVIEW_CHECK_ID]
I hope this helps you or others. Used in Access 2016.

I have experienced this on several occasions after making a design change to the form. There is no fault with what you have done - it is an access corruption. The solution is to copy the database to another file name, delete your forma and query, compact and repair, and then import the form and query again. This normally solves the problem. It appears importing it resets the internal references allowing the form to work as it should.

Doesn't seem like this was ever solved, and I just came up with the same issue. I solved it by deleting the form and recreating it. Like you I had, [Forms]![MyForm]![ID] and out of no where it started asking for user input for the criteria on my listbox query. Making a new form and copying over the fields seems to have fixed it.

Related

Run query connected to another database in VBA Access

I am trying to run saved query inside VBA Access. That query is connected to another database and looks like that:
SELECT * FROM TABLE IN 'C:\USERS\Another_database.accdb'
This query is saved as "My_query" inside first Access database. VBA code looks like this:
Function My_function()
Set rst = CurrentDb.OpenRecordset("My_query", dbOpenDynaset)
End Function
When I try to run it i got an error:
Run-time error '3219'
Any ideas why? It works for normal queries (without IN 'C:\USERS\Another_database.accdb' part.
The most efficient way to get data from another Access database on an ongoing basis is with Linked Tables.
Click External Data on the ribbon, then New Data Source → From Database → Access
Browse to the source database, and make sure you choose Link to the data source by creating a linked table
Select one or more tables that you want to link
[
The linked tables will be created and you will be able to query the linked tables as if they were local to the current database.
More Information:
Office Support : Import or link to data in another Access database
Office Support: Manage Linked Tables
Maybe you need to define a Recordset first or try to remove the quotation marks you have in the example? The following example works fine:
Dim rs as Recordset
Set rs = CurrentDb.OpenRecordset("SELECT Field FROM Table IN 'here goes your path'")
Now you have an Array rs() in which you can loop.

Edit Current Object's SQL in MS Access through VBA

I am using MS Access 2013 trying to edit the SQL of the current query that is being displayed on the screen. I can get the name of the current query using qName = Application.CurrentObjectName however the current query is not saved, nor do I want it to be saved.
I know that using something like below, I can get the SQL of a saved query and modify that query.
Dim qd As QueryDef
Set qd = CurrentDb.QueryDefs(qName)
qd.SQL = "Select Customers.ID From Customers"
However, the query that I want to modify is not saved, but rather just being worked on. What I want to do is access the SQL which is visible in SQL view, read that into a variable, and modify it. I am not sure how to proceed and would appreciate some help. (What I have tried is summarized above.)
(In case you are curious. The queries I am working on may be new or may be being modified from saved queries; saving could overwrite something which I am not yet finished with/is not working, thus causing more issues.)
If your unsaved new query is open in Datasheet View, you can retrieve its SQL like this:
MsgBox Application.Screen.ActiveDatasheet.RecordSource
However if you want to modify that SQL within its current query window, I can't help you.

VBA Access Need to obtain autonumber before saving new record

I've got a database with a SQLServer back end which was migrated from Access and an Access front end. After the migration one problem I keep running into is that autonumbers are not generated until after the record is saved (kind of obvious but Access didn't seem to care). I have a form that opens to create a new record in a table, but elements of that form require the value of the autonumber (Identity) field of that new record to calculate things. I want to somehow obtain this number right as the form loads instead of having to save it and reopen it just to obtain this number. What's the best way to go about this? Thanks in advance.
Access databases return + generate the autonumber when the record is dirty. In the case of SQL server + Access you cannot use nor does the form display the autonumber UNTIL record save time.
The simple solution is to thus force a save in the forms data, and then any following/existing code you have will continue to work.
So your code can look like this:
If Me.NewRecord = True Then
Me.Dirty = False
End If
The above will work as long as SOME editing has occurred. Note that if NO editing has occurred the above will NOT generate the autonumber ID (however even in non SQL server databases, when no editing has occurred then autonumber is not available anyway).
The above works for a bound form. If you have reocrdset code, then you change typial code like this:
Set rstRecords = CurrentDb.OpenRecordset("tblmain")
rstRecords.AddNew
In above your VBA code can/could grab autonumber. However the above code for sql sever will have to force a save.
In fact code that will work for both ACE or SQL server is thus:
will become:
Dim rstRecords As DAO.Recordset
Dim lngNext As Long
Set rstRecords = CurrentDb.OpenRecordset("tblmain", dbOpenDynaset, dbSeeChanges))
rstRecords.AddNew
' code here does whatever
rstRecords.Update
rstRecords.Bookmark = rstRecords.LastModified
lngNext = rstRecords!ID
rstRecords.Close
So the simple “issue” is you need to write out the record to force SQL server to generate the auotnumber. Once you done this record save, then your forms and most VBA code should run “as is”. You do not need to "resort" to additional code such as select ##identity UNLESS you using SQL insertcommands as opposed to say above forms or recordset code.
What you are referring to is the AutoNumber column in Access which is an Identity field in SQL.
The only way to accomplish this functionality in SQL is to insert the record when your form is opening and then use the ##Identity in SQL to retrieve the most recent value.
When your Access application was combined together with the database, Access was essentially doing this for you. You can check the following link for more details.
http://bytes.com/topic/sql-server/answers/143378-identity-sql-vs-autonumber-access
If its on a bound form, give a save button which will save record to database of Master table.It will have nothing except the identity field's value. Then enable or show subform which needs ID from this master table/form.
Looks ##identity code may not be possible for you since its bound form. To convince users why they need to save before adding any data to form, I name the button "show details" or "Add data to details" , this saves the record using docmd on the form, and makes visible the details section.
DoCmd.RunCommand acCmdSaveRecord
'OR a different code snippet, Just update Dirty status of form
If Me.Dirty = True then
Me.Dirty = False
End If
'You may write code to show/visible detail section/subform

(VB / ACCESS / CR) Filter VB Crystal Report based on Access Form

Before I get to the question, here is an overview of what is going on.
Access
A form that has a ComboBox that selects a JobId
Crystal Reports
A Report that calls info from several tables, all based on the JobID
VB
A Form (Using the Crystal Reports Plug-In) that shows the Report outside of the Crystal Reports Designer app.
My Problem
I need the report displayed in VB to be filtered to the job chosen in the Access ComboBox.
Update
I have my Database linked to VS2012, and that works fine without any issues. I can pull info from a Table easily. What I need to do is link the ComboBox from an Access Form to VS2012 to filter the Report.
I hope that makes my question clearer.
Update 2
I was able to figure out how to create a SELECT Query based on the value of my ComboBox inside of Access, so I should be able to use that to access the Value I am looking for, however I still need to know how to use that value as a filter for CR...
One possible solution would be to create a saved Select Query in Access that replicates the query in CR, and name that query [JobReport_base]. Then, create another saved Select Query in Access and name it [JobReport_current]. Add some code to your Access form that updates the .SQL property of the [JobReport_current] query to return just the records for the selected [JobId], something like
Dim qdf As DAO.QueryDef
Set qdf = CurrentDb.QueryDefs("JobReport_current")
qdf.SQL = "SELECT * FROM JobReport_base WHERE JobId = " & cbxJobId
Set qdf = Nothing
Then update your Crystal Report to pull the data from the [JobReport_current] query instead of the individual tables.
Multiple solutions. In your case, the simplest ones are the following:
There is this 'sqlQueryString' property of the report that you could update by directly updating the string.
You could also add a parameter (let's call it 'PAR_yourCombobox') to the report. When accessing the report in your VB code, just set the value of your parameter to the value on the screen. as far as I remember, it should look like:
yourReport.parameterFields(i).addCurrentValue yourForm.controls("yourCombobox").value

MS Access query with dynamic from statements

Ok this is vexing me. I have a query I created with an in statement in the from clause. What I am looking to do is have a global variable populate that from statement. Example
Select *
Form query1 in <Global Variable filename>
What is going on is I link to a file that has hundreds of linked table and queries in it. My database only has a few select queries and link table to different database. I did not want to re-build all the queries and linked table is my database. The issue is the file with all the links changes name once a month. I just want to read a text file with the current name of the database in it so I do not have to keep changing my queries every time the database name changes. Also this has to a query since I have other queries using the externally linked query.
I have one suggestion, but its pretty kludgy.
Rewrite the query on the fly with VBA call
Private Sub update_qtest()
Dim db As Database
Dim qd As QueryDef
Set db = CurrentDb
Set qd = db.QueryDefs("qtest")
qd.SQL = "SELECT * from query1 in " & g_file_name
End Sub
As I said, it's kludgy, but I don't think there's a way to pass the from clause as a parameter.
Another way to do this would be to just use the same file name each month so you wouldn't have to change anything in your Access app at all. You could easily code copying the file to the standard name over top of the previous copy (you'd have to delete it before copying, of course), which would retain the history.