I am trying to create a DLookup with multiple criteria in Access 2010, and running into a little trouble. I create invoices via a form. On the invoice form I select the AccountID, and set billing month and year. Based on that information, I would like to search my Prepayment query (quePrepayment) and pull in any prepayments that match those three criteria.
I am currently getting this error:
Run-time error '3075':
Syntax error (missing operator) in query expression 'AccountID= & Forms![frmInvoices]!AccountID & Billing_Month = & Forms![frmInvoices]!Billing_Month & Billing_Year = & Forms![frmInvoices]!Billing_Year)'
Private Sub AccountID_Change()
Billing_Prepayment = DLookup("Total_Prepayment", "quePrepayment", "[AccountID] = & Forms![frmInvoices]!AccountID And [Billing_Month] = & Forms![frmInvoices]!Billing_Month And [Billing_Year] = & Forms![frmInvoices]!Billing_Year")
End Sub
Make the third DLookup argument a string with the Forms![frmInvoices] control references built into it. (The db engine can de-reference those controls when it evaluates the expression.)
Billing_Prepayment = DLookup("Total_Prepayment", "quePrepayment", _
"[AccountID] = Forms![frmInvoices]!AccountID And [Billing_Month] = Forms![frmInvoices]!Billing_Month And [Billing_Year] = Forms![frmInvoices]!Billing_Year")
However, that string is so long it may be challenging to see whether it is built correctly. You can use an approach like this instead ...
Dim strCriteria As String
strCriteria = "[AccountID] = Forms![frmInvoices]!AccountID " & _
"And [Billing_Month] = Forms![frmInvoices]!Billing_Month " & _
"And [Billing_Year] = Forms![frmInvoices]!Billing_Year")
Debug.Print strCriteria
Billing_Prepayment = DLookup("Total_Prepayment", "quePrepayment", _
strCriteria)
Then in case of trouble, you can go to the Immediate window (Ctrl+g) to examine what was built for strCriteria.
Related
I am writing some VBA in MS Access, although the principle of my question would apply just as well to Excel or Word VBA. I have written a function GetStringParameterFromTable which returns a string value. It is possible that the function may result in a VBA-generated error, despite my best efforts to write it so that it does not. If an error happens, I don't want the code to crash, so I must use error handling. However, I don't want the code to display an error message and stop within the function if there is an error. I want the function to finish executing and return control to the calling procedure, and then I want the calling procedure to display the error message and tidy up, e.g. close open files. My question is: how does the calling procedure know that there has been an error in the function it called, and how does it get the error message?
I have thought of three ways of implementing this:
(1) Make GetStringParameterFromTable into a Sub, and pass it ParameterValue, ErrorFlag and ErrorMessage by reference.
(2) Keep GetStringParameterFromTable as a Function, define ErrorFlag and ErrorMessage as global variables and have the function alter ErrorFlag and ErrorMessage.
(3) Keep GetStringParameterFromTable as a Function and define a type with three components – ParameterValue, ErrorFlag and ErrorMessage – and make GetStringParameterFromTable return a value of the type I have defined.
I think that my requirement must be quite common, but I can’t find any examples of how it’s implemented. Does anyone have any views on which of my suggestions is the best way, or whether there is a better way that I haven’t thought of?
I have been contemplating the same thing since C#.net has implemented Tuples. I have implemented Tuples using VBA's type to create my tuples. What I have done is the following:
Public Type myTuple
Value as String 'Or whatever type your value needs to be
ErrCode as Long
ErrDesc as String
End Type
Public Function DoWork (ByRef mObject as MyClass) as myTuple
Dim retVal as myTuple
'Do whatever work
If Err.Number <> 0 then
retVal.Value = Nothing
retVal.ErrNumber = Err.Number
retVal.ErrDesc = Err.Description
Else
Set retVal.Value = Whatever Makes Sense
retVal.ErrNumber = 0
retVal.ErrDesc = VbNullString
End If
DoWork = retVal
End Function
I would like to be more specific, but you didn't provide a code example.
I am doing it like this and log the errors in a table:
' Lookups Replacements
'---------------------
Function DLook(Expression As String, Domain As String, Optional Criteria) As Variant
On Error GoTo Err_Handler
Dim strSQL As String
strSQL = "SELECT " & Expression & " FROM " & Domain 'DLookup
'DCount: strSQL = "SELECT COUNT(" & Expression & ") FROM " & Domain
'DMax: strSQL = "SELECT MAX(" & Expression & ") FROM " & Domain
'DMin: strSQL = "SELECT SUM(" & Expression & ") FROM " & Domain
'DFirst: strSQL = "SELECT FIRST(" & Expression & ") FROM " & Domain
'DLast: strSQL = "SELECT LAST(" & Expression & ") FROM " & Domain
'DSum: strSQL = "SELECT SUM(" & Expression & ") FROM " & Domain
'DAvg: strSQL = "SELECT AVG(" & Expression & ") FROM " & Domain
If Not IsMissing(Criteria) Then strSQL = strSQL & " WHERE " & Criteria
DLook = DBEngine(0)(0).OpenRecordset(strSQL, dbOpenForwardOnly)(0)
Exit Function
Err_Handler:
'Can be made as Error Sub as well
Dim ErrNumber as Integer
Dim ErrDescription as String
ErrNumber = Err.Number
ErrDescription = Err.Description
Err.Clear
On Error Resume Next
Dim strSQL as String
strSQL = "INSERT INTO tblErrorLog (ErrorNumber, ErrorDescription) VALUES (" & ErrNumber & ", '" & ErrDescription & "')"
Currentdb.Excecute strSQL, dbFailOnError
End Function
Called with:
If DLook("Column2", "Table1", "Column1 = " & ID) = 0 Then
'Do stuff
End If
If DLook("Column2", "Table1") = 0 Then
'Do other stuff
End If
My database has three tables, Holder, Product (which is an account) and Transaction. I have set up a form from the Holder table that has a subform from the Product table and the Product subform has the Transaction table as a subform. On the Holder portion of the form, I have put an Outstanding unbound text field that should display the total amount and tax fields of transactions from the transaction table that have not been paid (indicated by a checkbox on the Transaction table). I have set the control source of the unbound text box to =calcOutstanding() and written the following function for the form.
Public Function calcOutstanding()
Dim db As Database
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT SUM(tblTransaction.TxAmount + tblTransaction.TxTax) As Outstanding" _
& "FROM tblTransaction" _
& "INNER JOIN tblProduct ON tblTransaction.fkProductID = tblProduct.ProductID" _
& "INNER JOIN tblHolder ON tblProduct.fkHolderID = tblHolder.HolderID" _
& "WHERE tblTransaction.TxPaid = False" _
& "AND tlbHolder.HolderID = Me.HolderID;"
DoCmd.RunSQL strSQL
calcOutstanding = Outstanding
End Function
The field now just shows #Error. What am I doing wrong?
There's a bunch wrong with your approach:
DoCmd.RunSQL is just for action queries (INSERT, UPDATE, DELETE).
You cannot return a value from DoCmd.RunSQL like you are attempting to and push it into a variable.
Your concatenation for the where clause is incorrect.
As HansUp mentioned, Access is very picky about parentheses in JOINs in its SQL.
Assuming the SQL is correct, this code lives on the parent form, and you dno't get multiple rows back in your query, maybe something like this would work:
Public Function calcOutstanding() As Currency
Dim db As DAO.Database
Dim rst As DAO.Recordset
Dim strSQL As String
Set db = CurrentDb
strSQL = "SELECT SUM(tblTransaction.TxAmount + tblTransaction.TxTax) As Outstanding " _
& "FROM (tblTransaction " _
& "INNER JOIN tblProduct ON tblTransaction.fkProductID = tblProduct.ProductID) " _
& "INNER JOIN tblHolder ON tblProduct.fkHolderID = tblHolder.HolderID " _
& "WHERE tblTransaction.TxPaid = False " _
& "AND tlbHolder.HolderID = " & Me.HolderID
Set rst = db.OpenRecordset(strSQL, dbForwardOnly)
calcOutstanding = rst![Outstanding]
Set rst = Nothing
set db = Nothing
End Function
Notice the concatenation in the WHERE clause to get the value from the form's data source (otherwise the SQL couldn't reconcile Me.HolderID within the scope of the SQL itself). Also, we push the returning dataset into a recordset and read from that. Something along these lines should work, I think. (Not in front of Access now, so sorry if any non-compiling statements.)
EDIT: Added the function return type as integer for specificity's sake.
EDIT 2: Added the function return type as currencyfor specificity's sake. Doh.
Right off the bat, I see a problem in the code you posted:
strSQL = "SELECT SUM(tblTransaction.TxAmount + tblTransaction.TxTax) As Outstanding" _
& "FROM tblTransaction" _
& "INNER JOIN tblProduct ON tblTransaction.fkProductID = tblProduct.ProductID" _
& "INNER JOIN tblHolder ON tblProduct.fkHolderID = tblHolder.HolderID" _
& "WHERE tblTransaction.TxPaid = False" _
& "AND tlbHolder.HolderID = Me.HolderID;"
There should be a space either at the end of each line Outstanding " _ or at the beginning of each line like " FROM tblTransaction otherwise your string will read OutstandingFROM tblTransaction when parsed, which will give you an error.
I doubt you need an external function to do this. MS Access allows you to reference fields from subform simply by Me.Subform!FieldName.Value
This means, you could simply access the subform fields that are related to your current record. Even perform IIF(condition, truevalue, falsevalue) on that field
read more about accessing forms and subforms here: http://access.mvps.org/access/forms/frm0031.htm
EDIT:
in your third subform (tbl_transaction), create a new unbound TextBox called (txt_outstanding) and assign this expression
=IIF([txPaid]=false, sum(txAMount +TxTax),0)
now you can access this field in your parent form something similar to this:
me.txt_someTextbox.value = nz(me.tbltransactionsubform!txt_outstanding.value,"")
long time stalker but first time poster here so apologies for any social faux pas I make.
I am trying to use DLookup to search for a record in a table using VBA. The specific record I am after is the one closest in date to sdate (a user specified date) which also meets some other criteria. There are likely to be a couple of records with dates prior to sdate which meet the same criteria, and I am only interested in the one which is chronologically closest to sdate.
The following is a simplified example of the code I am using to try and achieve this. I use baseTestString as there are quite a few similar DLookup expressions so it saves typing and clarifies the code slightly (to me at least).
DoCmd.OpenTable ("Results")
DoCmd.SetOrderBy "[Survey_Date] Desc"
DoCmd.Close acTable, ("Results")
'set a new criteria for baseline testing using Dlookup
basetestString = "[Equipment_ID] = '" & equipID & "' AND [Baseline?] = True _
AND format([Survey_Date],""ddmmyyyy"") < format(" _
& sdate & ",""ddmmyyyy"")"
'set variables
[Forms]![results]![text_A] = Nz(DLookup("[Input]", "[results]", _
basetestString))
I believed (perhaps naively) that DLookup returns the first record it finds that matches the criteria specified. So, my code was designed to sort the table into chronological order, thinking that this would be the order that DLookup would cycle through the records.
However, each time I run the code, I am returned the lowest possibly date that matches the criteria rather than the one closest to sdate. After some playing around, I believe that DLookup uses the primary key as its basis for cycling through the records (the earlier dates are entered earlier, and hence given a primary key using autonumber which is lower than later dates).
This leads to me my questions...
1) I am correct in believing this is what is happening when I am returned the wrong record?
2) Is there a way to use DLookup in the way I am attempting? Can I choose which field is used to order the records for DLookup? Assigning the date field as the primary key is not possible as the dates might not always be unique.
3) Is there any other way I can achieve what I am trying to do here?
Thank you very much
It is always unsafe to rely on an order of records in a relational database. You could use DMax to get the date you need, but I think that in this case a recordset would be quicker.
Dim rs As DAO.Recordset
Dim db As Database
Dim ssql As String
Set db = CurrentDB
ssql=" SELECT input" _
& " FROM results" _
& " WHERE results.[baseline?] = true" _
& " AND results.equipment_id = '" & equipID & "'" _
& " AND results.survey_date = (SELECT" _
& " Max(results.survey_date) " _
& " FROM results" _
& " WHERE results.[baseline?] = true" _
& " AND results.equipment_id = '" & equipID & "'" _
& " AND results.survey_date <#" & Format(sdate,"yyyy/mm/dd") & "#)"
Set rs = db.OpenRecordset(ssql)
strInput = rs("Input")
Debug.Print strInput
You can also check the number of records returned, in case of an error.
I have been facing the error 3061 with error message "Too few Parameters: Expected 2". I have done all of the following to resolve the issue but still couldn't it.
I ran the query in SQL mode and it gives me result
I checked all the field names
I checked all the "&" s are placed. I find them correct.
Here is my code:
Private Sub cmbYear_Change()
Dim db As Database
Dim rs As DAO.Recordset
Dim Query As String
Query = " SELECT Yrs_Teaching, Highest_Edu, AD_Descr FROM ClassSurvey" & _
" WHERE ClassSurvey.Program/School_ID = " & Me.cmbProgId.Value & _
" AND ClassSurvey.ClassID = " & Me.cmbClassId.Value & _
" AND ClassSurvey.Teacher_ID = " & Me.cmbTeacherID.Value & _
" AND ClassSurvey.SYear = " & Me.cmbYear.Value
Set db = CurrentDb
Set rs = db.OpenRecordset(Query)
If rs.RecordCount > 0 Then
Me.TB1 = rs!Yrs_Teaching
Me.TB2 = rs!Highest_Edu
Me.TB3 = rs!AD_Descr
Else
Me.TB1 = "N/A"
End If
Set rs = Nothing
Set db = Nothing
End Sub
It appears your table includes a field named Program/School_ID. Bracket that field name in the SELECT statement so the db engine can properly recognize it as one field name.
That change might be all you need. But if you have another problem, give yourself an opportunity to examine the completed SELECT statement you're giving to the db engine. It might not be what you expect.
Dim db As Database
Dim rs As DAO.Recordset
Dim strQuery As String
strQuery = "SELECT cs.Yrs_Teaching, cs.Highest_Edu, cs.AD_Descr FROM ClassSurvey AS cs" & _
" WHERE cs.[Program/School_ID] = " & Me.cmbProgId.Value & _
" AND cs.ClassID = " & Me.cmbClassId.Value & _
" AND cs.Teacher_ID = " & Me.cmbTeacherID.Value & _
" AND cs.SYear = " & Me.cmbYear.Value
Debug.Print strQuery
Set db = CurrentDb
Set rs = db.OpenRecordset(strQuery)
If you get an error, you can go to the Immediate window (Ctrl+g), copy the statement text from there, open a new query in the query designer, switch to SQL View, paste in the statement text and try running it there. This tip is especially useful when the db engine complains about a missing parameter because when you try to run the query from the designer, Access will show you an input box asking you to supply a value and that box also contains the name of whatever Access thinks is the parameter.
I came across this when I was looking for a solution to the same problem. Turns out one of the values from a control on the form was not passing the value to the statement, sending it to the debug window (Debug.print) helped me spot the problem after a long time because I was using a global variable which the sql query was parsing. So load your controls' values into variables first!
This error may be because the column names in the query have special characters. Try surrounding the column names with square brackets in the SQL query. Column name with special symbols should be within square brackets and variables should be inside single quotes.
I had this issue too, I realized it was because I did not put quotes around my variables.
This was fixed by adding '& Chr(34)' around my variables
My fixed code looks like:
TextProducer = [Forms]![MyFormName]![TextInputBoxName]
strQuery = "SELECT FILEMASK" & _
" FROM TABLE_NAME" & _
" WHERE Producer = " & Chr(34) & TextProducer & Chr(34)
just wondering when using an expression on a form in a text box, to return a value from a table, can the expression have multiple tables in the expression to return the value?
the tables are linked and I can return the value in a query, so I figured that Access would be able to do it with this method as well????
=DSum("[tblMain]![Revenue]","tblMain","[tblMain]![Quarter]=3 AND [tblMain]![Region]='NorthEast'" AND [tblOffice]![Location]='NewYork'")
this is the expression that I entered into my text box, without the reference to the 2nd table it works fine, but once I had it, I get the flickering error message in the text box (just as on a report)......
I know this method is probably used more in reports than forms, but I am novice, and trying to come up with a dashboard solution that returns lots of facts quickly per department. I am using this in the "Control Source" field of the data tab of the properties window, not VB. Mainly because I do not know how to get it to work with VB.
Thanks for the help as always!
As far as I know, you cannot refer to more than one table or query in a domain aggregate function. As grazird says, how are these tables related? Let us say it is on tblMain ID, you can build a query called, say, qryMainOffice, the SQL (SQL View, Query Design window) would look something like:
SELECT [tblMain].[Revenue],[tblMain]![Quarter],[tblMain]![Region],
[tblOffice]![Location]
FROM tblMain
INNER JOIN tblOffice
ON tblMain.ID = tblOffice.MainID
DSum would then be (remove line break):
=NZ(DSum("[Revenue]","qryMainOffice",
"[Quarter]=3 AND [Region]='NorthEast' AND [Location]='NewYork'"),"Not found")
You could also use a recordset or query in VBA to return the value.
EDIT re COMMENT
To use the above in VBA, you either need to add parameters or use a string:
''Reference: Microsoft DAO 3.x Object Library
Dim rs As DAO.Recordset
Dim db As Database
Dim strSQL as String
Set db= CurrentDB
strSQL = "SELECT Sum(t.[Revenue]) As TotalNY" _
& "FROM tblMain t " _
& "INNER JOIN tblOffice o " _
& "ON t.ID = o.MainID " _
& "WHERE t.[Quarter]=3 AND t.[Region]='NorthEast' " _
& "AND o.[Location]='NewYork' " _
'' I have use aliases for simplicity, t-tblMain, o-tblOffice
'' If you wish to reference a control, use the value, like so:
'' & " AND [Location]='" & Me.txtCity & "'"
'' Dates should be formated to year, month, day
'' For joins, see http://www.devshed.com/c/a/MySQL/Understanding-SQL-Joins/
Set rs = db.OpenRecordset strSQL
If Not rs.EOF Then
Me.txtAnswer = rs!TotNY
Else
Me.txtAnswer = "N/A"
End If
You can also use different queries to return several results that can be shown with a list box or a subform:
strSQL = "SELECT TOP 5 o.[Location]," _
& "Sum(t.[Revenue]) AS TotRevenue" _
& "FROM tblMain t " _
& "INNER JOIN tblOffice o " _
& "ON t.ID = o.MainID " _
& "WHERE t.[Quarter]=3 AND t.[Region]='NorthEast' " _
& "GROUP BY o.[Location]"
The above would return revenue for quarter 3 for all locations in NorthEast region. If you want the top values of each group, you are looking at a more complicated query, which I will leave for now.
How are these tables related? Can you describe the relationship and any primary/foreign keys?
Also, referencing the table name is not necessary in the first parameter of this function (since it is already taken care of in the second one).
For example, your code could be:
=DSum("Revenue","tblMain","Quarter=3 AND Region='NorthEast'" AND [tblOffice]![Location]='NewYork'")
Just trying to save you some keystrokes and increase its readability. :)