Docmd Where Clause with IN clause and = operator - vba

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.

Related

MS Access confusing inner join failing

Okay I am confused…But that’s me easily confused.
I have a table. tblPartDrawing.
This table has three columns being PartDrawingID, Part and PartDrawing(Path).
Column Part is linked to tlkupPart. tlkupPart has PartID, PartNumber, PartDescription and PartThread in it. The link is on PartID in the table structure.
I have created a look up from tblPartDrawing.Part to tlkupPart.PartID with the following SQL code:
SELECT tlkupPart.PartID, [PartNumber] & " " & [PartDescription] AS Expr1,tlkupPart.PartNumber
FROM tlkupPart
ORDER BY tlkupPart.PartNumber;
As I read this, and perhaps I am missing something here this means PartID is the stored value in the Part column of tblPartDrawing.Part
However when I ask SQL to produce the following:
SELECT tblPartDrawing.PartDrawingID, tblPartDrawing.Part, tblPartDrawing.Drawing, tlkupPart.PartNumber, tlkupPart.PartDescription, tlkupPart.PartThread
FROM tblPartDrawing INNER JOIN tlkupPart ON tblPartDrawing.Part = tlkupPart.PartID;
It is throwing a Type Mismatch error. Clearly I am missing something, but I cant see what. Anyone else see the issue here?
If Part Number is a Short Text field (as it contains P), then PartID should be a text field, so you can join both fields and not get a "Type Mismatch" error.

Expected function / variable error message

i am trying to write a simple append query using SQL for my access database. Upon trying to execute the code, the message i am getting is:
Complilation error. Exepected function or variable
The query is a query which joins 4 tables and pastes the fields into another table. When using a standard MS Access query it works fine. I then generated and copied the SQL code (below) but unfortunately cannot get the query to work.
A final note about something strange. Unlike all the other SQL queries i have successfully written, this one, upon writing the Application.DoCmd.RunSQL (st_sql) into VBA, the space between the "L" and the "(st_sql) for some reason gets truncated.. Strange, this doesnt happen for any other string in the Whole routine where i successfully have other append queries.
Below is the code:
st_sql = "INSERT INTO[tblContactReporting03]([ID Project],[tblProjManagementPhaseHierarchy],[tblProjManagementSubPhaseHierarchy],[ID_Event],[SubTask_Hierarchy],[Project],[Sub project],[Project_Phase],[Project_Sub_Phase],[ContactFullName],[Role_Type],[type],[Event],[Effective_date],[Commitment],[Sub_task_name],[Status],[Notes])" & _
"SELECT[tblProjectMasterList].[ID Project],[tblProjManagementPhase].[Hierarchy],[tblProjManagementSubPhase].[Hierarchy],[tblContactReporting02].[ID_Event],[tblContactReporting02].[SubTask_Hierarchy],[tblProjectMasterList].[Project],[tblProjectMasterList].[Sub project],[tblProjManagementPhase].[Project_Phase],[tblProjManagementSubPhase].[Project_Sub_Phase],[tblContactReporting02].[ContactFullName],[tblContactReporting02].[Role_Type],[tblContactReporting02].[type]," & _
"[tblContactReporting02].[Event], [tblContactReporting02].[Effective_date],[tblContactReporting02].[Commitment],[tblContactReporting02].[Sub_task_name],[tblContactReporting02].[Status],[tblContactReporting02].[Notes]" & _
"FROM[tblProjectMasterListINNER JOIN ([tblProjManagementPhase] INNER JOIN ([tblContactReporting02] INNER JOIN [tblProjManagementSubPhase] ON [tblContactReporting02].[ID_Project_Sub_Phase] = [tblProjManagementSubPhase].[ID_Project_Sub_Phase]) ON ([tblContactReporting02].[ID_Project_Phase] = [tblProjManagementPhase].[ID_Project_Phase]) AND ([tblProjManagementPhase].[ID_Project_Phase] = [tblProjManagementSubPhase].[ID_Project_Phase])) ON [tblProjectMasterList].[ID Project] = [tblProjManagementPhase].[ID_Project]" & _
"ORDER BY [tblProjectMasterList].[ID Project], [tblProjManagementPhase].[Hierarchy], [tblProjManagementSubPhase].[Hierarchy], [tblContactReporting02].[ID_Event], [tblContactReporting02].[SubTask_Hierarchy];" & _
Application.DoCmd.RunSQL(st_sql)
I'd recommend a Debug.Print st_sql before running so that you'll be able to debug the constructed SQL.
The error you're getting is because RunSQL is a sub, not a function, so you need to call it 1) without parentheses:
Application.DoCmd.RunSQL st_sql
or 2) preceed it with Call and use parentheses:
Call Application.DoCmd.RunSQL(st_sql)
You can use syntax 2 for functions that when you don't need to use their return value.

Why doesn't my query use my criteria?

I have a db in Access and I'm trying to get a textbox to run my query and pass an other bounded textbox's value in as the criteria in DLookUp. I have the query running in design view and when I enter the criteria directly it returns the correct results. When I open the report it gives me the sum of all the possible rows. In other words it doesn't filter the rows.
I haven't used Access in about twelve years, thankfully, and everything I've done up to this point has been tutorial/example patchwork, but here it is...
SQL Query:
SELECT Sum(IIf(Attended=-1,1,0)) AS attendance
FROM Students_Classes_Attendance
WHERE (((CStr([Students_Classes_Attendance].[Class_Id]))=[classId]));
DLookUp as Control Source:
=DLookUp("[Total Attendance by Class]![attendance]",
"[Total Attendance by Class]",
"[Class_Id] =" & [Class_Id])
I'm lost at the moment. I'm guessing that the value isn't there before the query fires and since the criteria is an optional parameter that it's being passed null, but I would hope you'd get an error from that. Not that #Error is very meaningful anyway.
Does anyone know for certain the problem and the best way to correct it? Thanks.
Edit:
I did the changes recommended in the answer so now my DLookUp looks like...
=DLookUp("[attendance]",
"[Total Attendance by Class]",
"[Class_Id] =" & [Class_Id])
...still returns the total for all rows. Removing the criteria completely makes no difference either, which returns me to thinking it has something to do with the bound textbox not having a value.
DLookup uses the following syntax:
Syntax for numerical values:
DLookup("FieldName" , "TableName" , "Criteria = n")
Syntax for strings: (note the single apostrophe before and after the string value)
DLookup("FieldName" , "TableName" , "Criteria= 'string'")
Syntax for dates: (note the # before and after the date value)
DLookup("FieldName" , "TableName" , "Criteria= #date#")
I believe you just need to remove the table name from the first parameter. Try this:
=DLookUp("[attendance]", "[Total Attendance by Class]", "[Class_Id] = " & [Class_Id])
Keep in mind that if Class_Id is a Text Field, you need to surround it by single quotes:
=DLookUp("[attendance]", "[Total Attendance by Class]", "[Class_Id] = '" & [Class_Id] & "'")

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