简体   繁体   中英

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:

  1. Syntax for numerical values:
    DLookup("FieldName" , "TableName" , "Criteria = n")

  2. Syntax for strings: (note the single apostrophe before and after the string value)
    DLookup("FieldName" , "TableName" , "Criteria= 'string'")

  3. 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] & "'")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM