Run time error 3021- no current record - vba

I want to link the result of a query to a Textbox but I get this error: here is my code:
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("SELECT XValue, YValue,Wert FROM tb_DCM_Daten WHERE (FzgID=" & Forms!frm_fahrzeug!ID & " AND Name='" & List2.Value & "')")
Text10.Text = rst!XValue //error in this line
It should be return c.a 20 record
Why do I get this error and how can I solve it?

One possible reason for the error is that Name is a reserved word in Access, so you should use
... & " AND [Name]='" & ...
You could also test for rst.EOF before trying to use rst!XValue. That is, to verify whether or not your query is returning at least one row you can add the code
If rst.EOF Then
MsgBox "The Recordset is empty."
End If
immediately after the .OpenRecordset call. If the Recordset is empty, then you'll need to verify your SQL statement as described by #GregHNZ in his comment above.

Usually, I would do this. Create a new query in Access , switch to SQL View , Paste my code there and go to Design >> Run.
SELECT XValue, YValue,Wert FROM [tb_DCM_Daten] WHERE [FzgID]=12 AND [Name]='ABC';
if your query syntax is correct you should see the result otherwise error mssg will tell where you are wrong. I used to debug a much more complicated query than yours and this is the way that I've done.
If there is still error, maybe you should try
Dim sql as String
sql = "SELECT...."
Set rst = CurrentDb.OpenRecordset(sql)
Another possible reason might be your table name. I just wonder what is your table name exactly ? if your table contains white space you should make it like this [DCM Daten].

One more thing I like to add that may cause this, is your returning a sets of resultset that has "Reserved word" fields, for example:
Your "Customers" table has field name like the following:
Custnum | Date | Custname
we know that Date field is a reserved word for most database
so when you get the records using
SELECT * FROM Customers
this will possible return "No Current Record", so instead selecting all fields for that table, just minimize your field selection like this:
SELECT custnum, custname FROM Customers

After trying the solutions above to no avail, I found another solution: Yes/No fields in Access tables cannot be Null (See allenbrowne.com/bug-14)
Although my situation was slightly different in that I only got the "No current record." error when running my query using GROUPBY, my query worked after temporary eliminating the Yes/No field.
However, my Yes/No field surprisingly did not contain any Nulls. But, troubleshooting led me to find an associated error that was indeed populating my query result with Null Yes/No values. Fixing that associated error eliminated the Null Yes/No values in my results, thus eliminating this error.

I got the same error in the following situation:
In my case the recordset returned one record including some fields with Null value.
Dim rst As DAO.Recordset
Set rst = CurrentDb.OpenRecordset("SELECT * FROM tbl WHERE (criteria)", dbOpenDynaset)
Textbox1 = rst!field1 'error in this line - Non-Null value
Textbox2 = rst!field2 'Null value
Textbox3 = rst!field1 'Null value
Viewing Locals when rst is opened and before asignments, shows the recordset as I expect it to be. The error is thrown when trying to a asign a value from this recordset.
What fixed this, is ensuring that all fields contained non-Null values.
Just posting this for future seekers.

Related

How to get result from Count Query that shows in Query Datasheet view?

I'm trying to get the result of a Count query. I need to know if it's greater than 0.
My code:
Set db = CurrentDb
Set qdg = db.QueryDefs("quyGpSumReportCount")
qdg.Sql = Replace(qdg.Sql, "plugtable", VigilTable)
qdg.Sql = Replace(qdg.Sql, "plugchurch", "'" & vChurch & "'")
Set rst = qdg.OpenRecordset("quyGpSumReportCount")
Debug.Print "Total = " & rst!Total
PartCnt = rst!Total
rst.Close
Set rst = Nothing
The query looks like this for the first church once the replacements have been made:
SELECT Count(*) AS Total
FROM (SELECT DISTINCT t.fldUserID, v.[fldChurch/Parish] FROM tblSpring2022 _
AS t INNER JOIN tblVolunteers AS v ON t.[fldUserID] = v.[ID] WHERE _
(v.[fldChurch/Parish] = '1548 Heights')) AS [%$###_Alias];
Since I don't change back to the query after running it, I can switch to the Datasheet view and see the results. In the Field Totals, there is one entry and it's value is 1. (I've run it with a couple of different churches and get different but accurate values, including 0 for a few.)
Every attempt I've made to capture the value, using the name of the field, Total, or Fields(0) or rst.Fields(0) or anything else comes up Null.
So the query is running and returning the correct result but am unable to access that result from within VBA.
OK, I didn't solve this, you guys did; but it is solved.
For reasons that entirely escape me, qdg.OpenRecordset and qdf.OpenRecordset both resulted in a Data Conversion Error. But db.OpenRecordset, suggested above, works perfectly. Not only does it run but the result of the query finds its way both into a MsgBox and into the textbox on the form, making it possible for me to use it.
If I could upvote comments I would; the solution is, after all, there.
Thanks to all!

Return Query Value Using VBA function in Access

I'm currently working on a project and I've been having trouble trying to get a function that is able to return the value of a query, which I do need in order to display it on a textbox.
The current code is like this:
Public Function rubrieknaamSQL() As String
Dim rst As DAO.Recordset
Dim strSQL As String
strSQL = "SELECT T_Train.trainPlate, T_Category.categoryName FROM T_Category INNER JOIN T_Train ON T_Category.id = T_Train.category_id WHERE (((T_Train.trainPlate)=[Forms]![F_Comboio]![Combo_Search_Comboio]));"
Set rst = CurrentDb.OpenRecordset(strSQL)
rubrieknaamSQL = rst!categoryName
rst.Close
End Function
I should say that the code is copied from other publisher and I do not own its rights. However, it still won't work when I try to run it and the error displayed goes like this:
Run-Time Error 3061 : Too few parameters. Expected 1
and it happens in Set rst command.
For a SELECT query to set a recordset object, concatenate variable:
" ... WHERE T_Train.trainPlate=" & [Forms]![F_Comboio]![Combo_Search_Comboio]
If trainPlate is a text field, need apostrophe delimiters (date/time field needs # delimiter):
" ... WHERE T_Train.trainPlate='" & [Forms]![F_Comboio]![Combo_Search_Comboio] & "'"
For more info about parameters in Access SQL constructed in VBA, review How do I use parameters in VBA in the different contexts in Microsoft Access?
There are ways to pull this single value without VBA.
make combobox RowSource an SQL that joins tables and textbox simply references combobox column by its index - index is 0 based so if categoryName field is in third column, its index is 2: =[Combo_Search_Comboio].Column(2)
include T_Category in form RecordSource and bind textbox to categoryName - set as Locked Yes and TabStop No
build a query object that joins tables without filter criteria and use DLookup() expression in textbox
=DLookup("categoryName", "queryname", "trainPlate='" & [Combo_Search_Comboio] & "'")

Writing Dynamic SQL Statement

I am very new to Microsoft Access.
I would like to select a column from a table based on the value of a parameter (i.e. my table has columns x, y and z and I have a chosencol parameter which is set by the user using a dropdown.
I can select one / all of the columns using a select command, however, I would like to do this using my parameter chosencol instead.
Having read around, I have found a number of references to using the SET and EXEC commands, however, entering them into the SQL command in Access just yields errors.
Please could someone advise me as to how I go about implementing a dynamic-sql query in Access (in fine detail as I think I am writing the commands in the wrong place at the moment...)
First I created an example table in Access.
Next, I created an example form to query your value. The dropdown is called 'chosencol'. Select a value from the Column Select dropdown and press the "Lookup Value" button.
Here is the code under the "Lookup Value" button's On Click event. A SQL statement is dynamically built with the column you chose. The column is renamed to [FieldName] to that it can by referenced.
Private Sub btnLookup_Click()
Dim rsLookup As New ADODB.Recordset
Dim strSQL As String
strSQL = "select " & chosencol.Value & " as [FieldName] from Table1 where ID=1"
rsLookup.Open strSQL, CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly
If rsLookup.EOF = False Then
txtValue.SetFocus
txtValue.Text = rsLookup![FieldName]
End If
rsLookup.Close
End Sub
When the button is pushed, the value from whatever column you selected will be returned. For this simple example, I'm always returning row 1's data.
I'm pretty sure you can't do that in straight SQL. However, you can create the SQL string in VBA code and save it as a query.
CurrentDB.CreateQueryDef("MyQueryName", "SELECT " & chosencol & " FROM MyTable")
Now, MyQueryName will be a permanent query in your database and can be referenced wherever you want.
If chosencol is a multi-select dropdown, you'll have to read the selected values into an array and then write the array to one concatenated string and use that instead.

MS Access: Trying to select a value in a record corresponding to a certain value

Sorry if the title is confusing. But I have a table with a few different columns. One column is the KitNumber and the other is the ReturnDate. I am trying to select the value of the ReturnDate to see what the length of the entry is (also, does VBA let you get the length of a date?). What I need to do though, is the user will enter a number in an unbound, and then that value will look in the table to see if it matches another value in there, and if it does, it will select the return date. Here is the code I have now:
strSQL = "SELECT ReturnDate FROM Crew WHERE KitNumber = " & Me.AssignKit
Debug.Print strSQL
DateLen = Len(strSQL)
So say I enter '111111' in the unbound. I want it to look in the table then to see if there is a matching number. Then if there is it should return the ReturnDate value and get the length of it. Cause right now the Debug just returns the KitNumber instead of the date. Anyone be able to help me out? Thank you
If it's a one off, then a DLookup in the OnExit or OnChange events should give you the info you need to work with
using your example,
Debug.Print DLookup("ReturnDate","Crew","KitNumber = " & Me.AssignKit)
if KitNumber is stored as a string in the database, then you would need to put quotes around the selection
Debug.Print DLookup("ReturnDate","Crew","KitNumber = '" & Me.AssignKit & "'")
Note that DLookup returns the first one it finds, so if you need multiple values, you will have to look into recordset functions .Find and .FindNext

dlookup multiple tables and set textbox to result access 2007

I'll try and break down my problem as best I can and explain what I'm trying to achieve. Firstly, I have three tables:
**RFI** (stands for Request For Information)-
Fields: rfi_id, Customer_id .....
**RFI_project** -
Fields: rfipro_id, project_id, rfi_id *"....." represents other unnecessary fields*
**Customer** -
Fields: Customer_id, company .....
I have an access form with two comboboxes. On the first combobox I select the name of a project at which point the second textbox changes to show those *rfi_id*'s where there is a match with the project name selected.
Now what I'm trying to do is this - When I select an *rfi_id* in the second combobox I want it to display in a textbox on my form the company where there the *rfi_id* value matches the value in the combobox. It's a bit tricky due to the way the tables are joined...here is what I'm essentially trying to display in the textbox field in SQL terms:
SELECT Customer.company, RFI.Customer_id
FROM Customer, RFI
WHERE (((Customer.Customer_id)=[RFI].[Customer_id]) AND ((RFI.rfi_id)=[Forms]![Request for Info Form]![Combo90]))
ORDER BY Customer.company;
In order to do this I have tried the following to no avail. In the after update event of my second combobox I have inserted the following:
companyTB = DLookup("company", "Customer", "Customer_id =" & DLookup("Customer_id", "RFI" And "rfi_id =" & [Forms]![Request for Info Form]![cmbRFI]))
When I change the combobox value I get the error Run-time error '13': Type mismatch. I've tried searching for what I've done wrong but this is a very broad error apparently and I can't find anything similar (or that I understand). I also tried this instead -
companyTB = DLookup("company", "Customer", "Customer_id =" & DLookup("Customer_id", "RFI", "rfi_id =" & cmbRFI))
which gives me the following error - Run-time error '3075': Syntax error(missing operator)in query expression. Anyway, would anybody be kind enough to give me a breakdown of what I need to do to achieve this, or what I'm doing wrong (or maybe a better way to do it?). Forgive me for being to seemingly stupid at this, I've only just begun working with access more in depth in the last 3 weeks or so. Thank you.
Your first DLookUp has incorrect syntax:
companyTB = DLookup("company", "Customer", "Customer_id ="
& DLookup("Customer_id", "RFI" And "rfi_id ="
& [Forms]![Request for Info Form]![cmbRFI]))
I have broken it into three lines to make this easier to see. The second line has And between "RFI" and "rfi_id" when it should have a comma.
companyTB = DLookup("company", "Customer", "Customer_id ="
& DLookup("Customer_id", "RFI", "rfi_id =" & cmbRFI))
The error you are getting on your second combo seems likely to be due to the result returned by cmbRFI. You can check this by filling in an actual rfi_id, rather than the reference to the combo and by setting a text box equal to cmbRFI and see what it is returning. Combo can be difficult because the displayed column and the bound column can be different.
It can be convenient to set up your combobox with several columns, as shown in your query, so the rowsource might be:
SELECT rfi.ID, Customer.company, RFI.Customer_id
FROM Customer
INNER JOIN RFI
ON Customer.Customer_id=RFI.Customer_id
ORDER BY Customer.company;
(or the three tables, joined, if necessary)
Then
Column count = 3
Column widths = 2cm;0;0
Bound column = 1
You can now refer to the second column in your textbox:
= cmbRFI.Column(1)
Columns are numbered from zero.
It is always worth reading up on sql before working with Access:
Fundamental Microsoft Jet SQL for Access 2000
Intermediate Microsoft Jet SQL for Access 2000
Advanced Microsoft Jet SQL for Access 2000
Your last Dlookup statement seems absolutely fine so I'm a little confused as to why it isn't working, you may be able to get round the problem like this though:
Combox2_AfterUpdate (Or whatever the event is called)
Dim rs As Recordset
Set rs = Currentdb.OpenRecordset("SELECT C.Company, R.Customer_ID " & _
"FROM Customer As C, RFI As R " & _
"WHERE C.Customer_ID = R.Customer_ID " & _
"AND R.RFI_ID =" & [Forms]![Request for Info Form]![Combo90] & " " & _
"ORDER BY C.Company")
CompanyTB = rs!Company
rs.Close
Set rs = Nothing
End Sub