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. :)
Related
I clipped this from another post, since it is similar to what I need. Instead of using me.ID, etc, I need to reference a field in another table, specifically [Formdate] in a table named Brief Sheet.
I tried many variations, such as table "Brief Sheet".Formdate but no luck
What would be the proper syntax?
rst.FindFirst "[ID] <> " & Me.ID & _
" AND [TitleText] = '" & Me.TitleText & _
"' AND [UnitCode] = " & Me.UnitCode & _
" AND [AcademicYear] = " & Me.AcademicYear & _
" AND [Titleofchapterjournalarticle] = '" & Me.Titleofchapterjournalarticle & "'"
Use Dlookup. In the snippet you posted, the coder has already instantiated a recordset and is using recordset methods to find a record within it. What you said you want to do is actually a little simpler.
Below is a test procedure to illustrate getting your date value from your table.
You didn't clarify what criteria you would use to select the proper FormDate from the table "Brief Sheet", so I included "ID=3", which will select the FormDate record, whose ID=3. Adjust that as necessary.
Also, if your table name really is "Brief Sheet", and you have the ability to rename it, I highly recommend establishing some naming convention rules for your tables, first not having any spaces. Even Brief_Sheet would make your life easier down the road.
Public Sub Test1()
'dimension a variable to hold the date value
Dim datFormDate As Date
'fill the variable with the value you need to reference
datFormDate = DLookup("FormDate", "Brief Sheet", "ID = 3")
'Print the value to the "immediate" pane (just for testing)
Debug.Print datFormDate
'If you're running this code from within your form module, you can assign
'the value in your variable to a field in your table as such:
me.DateFieldtxtbx = datFormDate
End Sub
I need help with a textbox field on an Access 2007 form. I'm trying to insert the result of a query into the text box control on the form. This is used soley as information for the user. The form supplies the query with parameters to get the value. The query works fine and returns the correct result. What I can't seem to figure out is how to pass the query result to the textbox. I’ve tried several different ways but with no luck.
(PS> I know a combo box can do a lookup, however I don’t want the user to have to click the dropdown just to select the value as there can only ever be one value result from the query.) I'm open to suggestions as I'm not a programmer or DB Admin, but I've taking a few classes on Access (enough to be dangerous).
Private Sub cbo3_Change()
Me.tbx2 = ("SELECT tbl_Billing.Savings_b FROM tbl_Billing GROUP BY tbl_Billing.UBI_b, tbl_Billing.TaxYr_b, tbl_Billing.TaxPrg_b, tbl_Billing.Savings_b HAVING (((tbl_Billing.UBI_b)=forms!f1_UpBilled!cbo1) And ((tbl_Billing.TaxYr_b)=forms!f1_Upbilled!cbo2) And ((tbl_Billing.TaxPrg_b)=forms!f1_UpBilled!cbo3));")
End Sub
If you wish to do this in run time, you need to do the following, I take the controls you are referring to in this is on the same form.
The very simple and straight forward way to get it done is as follows,
Private Sub cbo3_Change()
Dim tmpRS As DAO.Recordset
Set tmpRS = CurrentDb.OpenRecordset("SELECT tbl_Billing.Savings_b FROM tbl_Billing GROUP BY " & _
"tbl_Billing.UBI_b, tbl_Billing.TaxYr_b, tbl_Billing.TaxPrg_b, " & _
"tbl_Billing.Savings_b HAVING ((tbl_Billing.UBI_b = '" & Me.cbo1 & "') And (tbl_Billing.TaxYr_b = '" & Me.cbo2 & "') " & _
"And (tbl_Billing.TaxPrg_b = '" & Me.cbo3 & "'))")
If tmpRS.RecordCount > 0 Then
Me.tbx2 = tmpRS.Fields(0)
Else
Me.tbx2 = 0
End If
Set tmpRS = Nothing
End Sub
Just note, I have implied all your combo boxes are returning String and the field you are comparing against are Text type. If that is not the case, you need to make changes accordingly.
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.
In my Access database, I'm trying to perform a search and find routine which is quite complicated. Basically, I have 4 criteria to look for in these four tables: Date, Service, Code and Function.
With this information I go into a table, and search in a field and for one criteria. After I've found the rows which correspond to one of the 4 criteria, I save the value of the neighboring field for all the rows which matched correctly. After this, I wanted to save the values of all the neighboring fields as an array. Then repeating these steps, I was going to save all 4 searches as 4 individual arrays.
The relationships of my tables are as follows:
I receive a "Demande" which is a request, and in that request are the four criteria: Date, Service, Code and Function.
In the table "Services_YES" I look for the Service that corresponds to the demand.
In the table "Pool_Personnel" I look for the Fonction that corresponds to the demand.
In the table "Days_Available" I look for both the Date and the Code (called Code_Horaire) which corresponds to the demand.
From there, I was hoping to record each Code_Personal for all of the results found, and then find which Code_Personal's matched in all of the 3 tables.
So My question:
How I can do a search and find function which creates an array of for all of the Code's which correspond to the criteria rows?
I have created psuedo code to help explain, and incase someone can translate this into real VBA:
While demandeTable.functionField.Value = poolpersonnelTable.Fonction1Field.Value
get all poolpersonnelTable.codepersonalField.Value for all rows that match
save fonctionArray = codepersonalField.Values
Loop
I'm very stuck on how to complete this 'filtering', and would strongly appreciate all help.
Using VBA is not the answer.
I ended up creating a Query, and using user-inputed text to fill in the variable parts of the query:
comboService = Chr(34) & Me.Combo8.Value & Chr(34)
txtDate = Chr(34) & Me.Text15.Value & Chr(34)
comboCodeHoraire = Chr(34) & Me.Combo17.Value & Chr(34)
"SELECT tblPoolPersonnel.LName, tblPoolPersonnel.FName, tblPoolPersonnel.[Tel Natel], tblPoolPersonnel.[Tel Home], tblPoolPersonnel.Email" & vbCrLf
"FROM ((tblPoolPersonnel INNER JOIN tblFonction ON tblPoolPersonnel.Code_Personal = tblFonction.Code_Personel) INNER JOIN tblDayAvailable ON tblPoolPersonnel.Code_Personal = tblDayAvailable.Code_Personal) INNER JOIN tblServiceYES ON tblPoolPersonnel.Code_Personal = tblServiceYES.Code_Personal" & vbCrLf
"WHERE (((tblServiceYES.Service)=" & comboService & ") AND " + _
"((tblDayAvailable.Availability)=True) AND " + _
"((tblDayAvailable.Date)=" & txtDate & ") AND " + _
"((tblDayAvailable.CodeHoraire1)=" & comboCodeHoraire & "))"