MoveFirst works on first call, fails on second - vba

I am creating an Access 2007 database, which contains two tables (Applicants and Opportunities) and a link table (Applicants-Opportunities). I am populating these tables from a flat file in another table using VBA. The code for checking whether a record already exists in the link table is
szSQL = "((([Applicants-Opportunities].[User Id])="""
& rsInc![User Id] & """)
AND (([Applicants-Opportunities].[Opportunity Id])="""
& rsInc![Opportunity Id] & """))""
rsLnk.FindFirst szSQL
The first time through, with all three tables blank, this code works. The second time, I get a 3070 error saying that the system doesn't recognise "Applicants-Opportunities.User Id" as a valid field name.
I'm at a complete loss. If it worked the first time, why not the second? Neither Id in the second case is the same as in the first.

.FindFirst method change current position to first found record and change property .NoMatch to False. If nothing found .NoMatch is true.
If you need search another records you can use .FindNext method with checking .NoMatch property.
You can read about in manual from msdn. There is example.
But, you might use sql for your target. Something like this:
UPDATE [Applicants-Opportunities] INNER JOIN [another table]
ON [Applicants-Opportunities].[User Id] = [another table].[User Id]
AND [Applicants-Opportunities].[Opportunity Id] = [another table].[Opportunity Id]
SET [Applicants-Opportunities].[SomeField] = 'SomeValue'
WHERE [Applicants-Opportunities].[SomeOtherField] = 'SomeOtherValue'
sorry for my english)

Related

Docmd Where Clause with IN clause and = operator

I'm using a docmd to open a report in ms access.
This command works as expected:
Docmd.OpenReport "rptCustomerProject", acViewReport, , "ProjectStatusID IN ([TempVars]![StatusActive], [TempVars]![StatusCompleted], [TempVars]![StatusPending]"
This command also works as expected:
Docmd.OpenReport "rptCustomerProject", acViewReport, , "CompanyOrgID = " & cboCompany
My problem occurs when I try and combine the two where clauses into one. I get a
Run-time error '13': Type mismatch.
I've tried various formatting but can't figure it out.
Docmd.OpenReport "rptCustomerProject", acViewReport, , "CompanyOrgID = " & cboCompany AND "ProjectStatusID IN ([TempVars]![StatusActive], [TempVars]![StatusCompleted], [TempVars]![StatusPending]"
Thanks in advance.
I made the changes and the Type mismatch error disappeared, however the ProjectStatusID no longer works.
I originally included the Where clause in the reports record source, but it said it was too complicated to analyze, so I redid the Select statement in my record source and put the Where clause in the form that calls the report. Different buttons on the form have different Where clauses. This is the only one I can't get to work.
My Reports record source is:
SELECT *
FROM (SELECT tblCompanyOrg.CompanyOrgID, tblCompanyOrg.CompanyOrg, tblCustomer.CustomerID, tblCustomer.CustPhone, tblCustomer.CustEmail, [CustFName] & " " & [CustLName] AS FullName FROM tblCompanyOrg INNER JOIN tblCustomer ON tblCompanyOrg.CompanyOrgID = tblCustomer.CompanyOrgID)  AS q1 INNER JOIN (SELECT tbl2Project.ProjectID, tbl2Project.CustomerProjectID, tbl2Project.CustomerID, tbl2Project.ProjectStatusID FROM tbl2Project)  AS q2 ON q1.CustomerID = q2.CustomerID;
After several days of troubleshooting I have found the issue. My TempVars are either a numeric value or a null. When evaluating the where clause with just the ProjectStatusID IN (TempVars list) everything works fine. When I add an additional stipulation to the Where clause I get a Run-Time error ‘3071’ This expression is too complex to be evaluated. Setting my TempVars that are Null to 0 solves the problem. My ProjectStatusID field is an autonumbered field and doesn’t contain a value of 0. Another solution I found was to build a string variable and only assign TempVars that are not Null to it. As far as the original question was asked, braX did provide the solution. Thanks to all.

Reference table and form text box MS Access VBA

Pardon the code below. I am a VBA novice. I am looking to upon clicking a form button, inform customers that they must make another library selection if the item they have chosen is checked out. I determine something is checked out if the "Check In Date" for the most recent date in the "1Transaction" table is NULL. Note for every check in and check out, a new record is created in the 1Transaction table and every record (whether check in or check out) will have the check out date info. So the logic, take the most recent date for the lease (book) number and if there is no return date then it is still checked out. The code below is meant to make the references and return a message box in VBA but I am stuck. I understand logically what I require but I know my VBA syntax is very off. Thanks.
Private Sub Check_Out()
If [1Transactions].[Asset].Value = Me.Lease_Num
And DMax([Tables]![1Transactions].[Check Out Date])
And [Tables]![1Transactions].[Check In Date] = NULL
Then MsgBox "The requested documents are currently checked out"
End If
DoCmd.OpenForm "Check In"
End Sub
Note:
1Transactions = Table holding all check in/out data
Me.Lease_Num = value pulled from combo box that user fills out to provide "lease number" (book code) they are interested in checking out.
Okay - instead of trying to modify every line of your code, I think it's better to use a Parameter Query to simple check if the item is out now
First create a query using your transactions table - modify the SQL to below
and save it as "qdfLease"
PARAMETERS [What Lease Num] Text ( 255 ); SELECT TOP 1
[1Transactions].Asset, [1Transactions].[Check Out Date],
[1Transactions].[Check In Date] FROM 1Transactions WHERE
([1Transactions].Asset = [What Lease Num]) And ([1Transactions].[Check
In Date] Is Null) ORDER BY [1Transactions].[Check Out Date] DESC;
Modify the code in your sub to:
Dim qdf As DAO.QueryDef
Dim rs As DAO.Recordset
Dim strLeaseNum As String
strLeaseNum = nz(Me.Lease_Num,"")
Set qdfLease = CurrentDb.QueryDefs("qdfLease")
qdfLease.Parameters("What Lease Num") = strLeaseNum
Set rs = qdfLease.OpenRecordset(dbOpenDynaset, dbReadOnly)
If rs.EOF Then
' Item is Checked In
Else
' Item is Checked Out
End If
rs.Close
Set rs = Nothing
You have [1Transactions].[Check Out Date].Value = Me.Lease_Num
Is that what you want to compare the lease_num to? It sounds like it should be a different field name in [1Transactions]
I would change this
[Tables]![1Transactions].[Check In Date] = NULL
to this
IsNull([Tables]![1Transactions].[Check In Date])
What are you trying to compare here
DMax([Tables]![1Transactions].[Check Out Date])

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

Run time error 3021- no current record

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.

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