MS Access Dlookup referencing a joined query - ms-access

So I'm building a form in MS Access 2010, and I want to populate a text box with the result of the following query, which is saved in Access as 'GRT_tblEstablishments Names Query':
SELECT est.school_name
FROM GRT_tblEstablishments est, GRT_school_record schrec
WHERE schrec.ID = 4
AND schrec.Current_School = True
AND est.ID = schrec.School_ID;
I'm using a DLookUp in the Control Source box as follows:
=DLookUp("school_name","GRT_tblEstablishments Names Query","[schrec.ID] = ID")
The problem I seem to be having is feeding the schrec.ID to the query from the DLookUp... All I get is #error when I load the form... I've been fighting it all afternoon with no success... I'm sure it must be something really simple, but my Access skills are reasonably rudimentary... What am I doing wrong?
Thanks!

The ID must be concatenated - and be careful with spaces:
=DLookUp("[school_name]","[GRT_tblEstablishments Names Query]","[schrec].[ID] = " & ID & "")

Related

MS-Access using Dlookup to pull results from query into textbox on form

I am very new to access and I am using the Dlookup function to pull the results from a query into a text box to appear on a form.
I have the following expression in the Data Control Source field for the text box and it is pulling in the very first result from the query.
=DLookUp("SumOfSales","qTtlSalesbyComp","Company = Company")
I need it to act as a vlookup and match the Company in the query to the Company in the Company text box and pull the SumofSales that corresponds. Any hep would be greatly appreciated.
If Company is text:
=DLookUp("SumOfSales","qTtlSalesbyComp","Company = '" & Company & "'")
If it is numerical:
=DLookUp("SumOfSales","qTtlSalesbyComp","Company = " & Company )
I just could not seem to get the Dlookup to work. I ended up using subforms to pull in the query results. I believe this ended up being a much cleaner way of executing what I wanted.

Possible to change MS Access subform fields through VBA?

I can find plenty of examples of how to return specific records in a subform through altering the underlying source query in code and re-querying, but I'm struggling to use the same principle to alter the fields that are returned.
I have the following situation:
Combobox to select 1 of 5 fields. Subform is supposed to show the selected field plus a couple of static fields, lets call them fields 6 and 7
So in the case the user selects field 1 from the dropdown, subform should show fields 1, 6 and 7. In the case they pick field 4, subform should show fields 4, 6 and 7 etc.
This is what (amongst other things) I've tried:
Set the subform up through the wizard with a query (select field1, field6, field7) as source, amend said query after combobox selection is made:
Set qd = CurrentDb.QueryDefs("myqueryname")
qd.SQL = "Select " & mycomboboxselection & ",field6,field7 from mytablename"
Form_mymainformname.mysubformname.Requery
The query itself updates fine if I run that standalone after the change, but the subform within the main form doesn't change and when I click on the subform itself from the navigation window it seems to be stuck looking for field 1 as it asks me to input a parameter value
Can anyone help with how to achieve this please?
Set the RecordSource of the subform to the SQL:
Dim SQL As String
SQL = "Select " & mycomboboxselection & ",field6,field7 from mytablename"
Me!YourSubformControl.Form.RecordSource = SQL
It will force a requery of the subform.
Ok I found a solution after a few more hours searching and trial and error.
There are two seperate problems here. Firstly creating the subform uses the newly created form as the source object rather than directly using the query, and it seems that no matter how you try to manipulate the record source of said form, it doesn't like changing the fields it was built with.
So, create the subform, change the source object from the form to your query (and delete the now pointless newly created form), then you can use the code I started with:
Set qd = CurrentDb.QueryDefs("myqueryname")
qd.SQL = "Select " & mycomboboxselection & ",field6,field7 from mytablename"
Which works! sort of....
You have to close and reopen the form every time to see the actual updates though, which obviously isn't what we're going for
The other line does nothing:
Form_mymainformname.mysubformname.Requery
It works fine for a change of records, but apparently not for a change of fields. I suspect this is a bit of a ms quirk
The below, however, works, even though I feel like it should do exactly the same as the code line above:
Form_MyForm.MySubForm.SourceObject = Form_MyForm.MySubForm.SourceObject

How to use DLookup criteria from different tables in Access

I am very new to VBA and Access, and have been madly searching the internet for answers, but I seem to be stuck on this one. I may be getting stuck thinking in Excel spreadsheet logic when trying to design this in Access.
I have two tables, REQUESTFORM and CLIENTDATABASE. The Request form has various fields generated from incoming emails. My intent is for the ClientDatabase to auto-populate new CLIENTID's when emails from new individuals arrive in the RequestForm table, and add the appropriate CLIENTID to the REQUESTFORM table. The REQUESTFORM has fields for NEWFIRSTNAME and NEWLASTNAME, while CLIENTDATABASE will have fields FIRSTNAME and LASTNAME, to keep the field names different. I want CLIENTDATABASE to have the primary key data, so I can handle any spelling mistakes that come in.
Using DLOOKUP is similar to excel's VLOOKUP, but DLOOKUP only seems to use criteria in the same table. In Excel you could 'point' to other tables if necessary.
So when I try this in a query:
NameMatch: DLookUp("[ClientID]","ClientDatabase","[FirstName]=[NewFirstName] And [LastName]=[NewLastName]")
It doesn't seem to be working because it doesn't recognize NewFirstName, because it isn't in the ClientDatabase, it is in RequestForm.
I have tried coding a user defined function in VB, but I keep running into the same problem, even if I reduce it to one criteria. I can work with one criteria if I have to by combining first and last name as a fullname field, but still.
Public Function NameMatch(ByVal pInput As String) As String
On Error Resume Next
NameMatch = DLookup("[ClientID]", "ClientDatabase", "[FirstName] = 'pInput'")
End Function
Is there a way to code the user defined function to define 'pInput' as [NewFirstName] and successfully see it? Or write the formula better in the query? I don't get an error with the UDF, just a blank. There's probably a dozen other pitfalls I've missed as well. Any help appreciated.
Stardance
It will be something like this where you concate the values into the search criteria:
NameMatch: DLookUp("[ClientID]","ClientDatabase","[FirstName] = '" & [NewFirstName] & "' And [LastName] = '" & [NewLastName] & "'")

Automating query selection based on combo box on a form

Okay, friends, I'm leaving my job in a week and a half, and I'm trying to make what I've done easier for my boss to do. He has no access knowledge, so I'm trying to create a form that will automate the reports I've been generating. Rather than create a different form for all the different reports, I'm trying to automate it from a table of parameters. Here's what I'm going for:
I have a table, which I have created, which is comprised of 5 fields. I'd like to use these fields to fill parameter fields in a standard form template. The five fields in my table are as follows:
The type of query being run (the result spit out)
The queries that generate this report, separated by a comma and no space. "QRYNAMEA,QRYNAMEB"
The Table which these queries generate, which will be used by transferspreadsheet
The destination excel file, which already has a pivot table set up to feed of the data.
The input sheet of this excel file. Currently, all of these sheets are called "Input". (that isn't important)
My issue comes with having no idea where to go after I've made my combo box. I know enough visual basic to automate my queries, but not enough to populate the form with the information in 3,4 and 5 (so far, I've been manually changing these for different queries). I have no idea how to look up the record in the table from the choice in the 'choosebox', and then select individual fields from that in my automation.
I'm pretty confident in my ability to parse #2 and automate the queries, and to put the values into the fields I'm looking at, but I don't know how to actually pull those values from the table, before I can do these things. I also can't seem to describe this well enough for google to help me.
Has anyone done something like this before? I'm assuming I just lack knowledge of one of the VBA libraries, but I've not had any luck finding out which.
edit:
my inclination at this point is to create a query for this table, which will return a single field depending on the input I give. I can imagine doing this in SQL, but I still don't know how to populate the forms, nor extract the field object from the table once I get it.
I have to head out for the day, but I'll be back on Friday to keep working on this, and I'll post my solution, once I find it. This seems like a unique conundrum, and it would be nice to give an answer to it.
Final edit: code is polished (does not have much in the way of error handling):
The first method, which pulls the fields from the table and populates the form, is activated by choosing a new entry in the combo box and looks like this:
Private Sub QuerySelect_Change()
Dim db As Database
Dim rec As Recordset
Set db = CurrentDb
Set rec = db.OpenRecordset("SELECT [Queries to Run], [Source Table], [Destination Spreadsheet], [Destination Sheet Name] FROM TBL_QRY_SETTINGS WHERE TBL_QRY_SETTINGS.[Query Type] Like '" & [Forms]![QuerySelector]![QuerySelect] & "';")
[Forms]![QuerySelector]![QueriesToRun].Value = rec("Queries to Run")
[Forms]![QuerySelector]![SourceTable].Value = rec("Source Table")
[Forms]![QuerySelector]![FileDest].Value = rec("Destination Spreadsheet")
[Forms]![QuerySelector]![SheetName].Value = rec("Destination Sheet Name")
Set rec = Nothing
Set db = Nothing
End Sub
The second code pulls that data to run the query. I like how this turned out. It runs when a button near the combobox is clicked.
Private Sub DynamicQuery_Click()
Dim qryArray As Variant
Dim i As Integer
qryArray = Split([Forms]![QuerySelector]![QueriesToRun], ",")
DoCmd.SetWarnings False
For i = LBound(qryArray) To UBound(qryArray)
Debug.Print qryArray(i)
DoCmd.OpenQuery (qryArray(i))
Next
DoCmd.SetWarnings True
DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel12Xml, [Forms]![QuerySelector]![SourceTable], _
[Forms]![QuerySelector]![FileDest], _
True, [Forms]![QuerySelector]![SheetName]
End Sub
Note that the final code for part (1) is almost the same as the selected answer, except that I am grabbing more than one field. This works because I know that I have unique "Query Types", and my recordset will only contain one record.
Anyway, I hope some people stumble upon this and find it useful. Send me a message if you do. As far as I can tell from brief googling, this sort of automation work has not been done in access. It should make it easier for access-illiterate to run their own queries, and be simple for designers to add to, if they want all their queries available after a few clicks.
Someone could conceivably use this to automate a variety of reports in sequence, by iterating through a table like the one I reference.
I may be massively misunderstanding what you're doing, but I think it's as easy as creating a new form using the form wizard. It will let you choose the table that contains the data, and it will let you choose which fields you want to add.
You can later change any of the textboxes to combo boxes which will allow you to limit the choices available to fill in.
Am I understanding that correctly?
EDIT: This will fill a variable (MyRandomField) with the contents of a field in a table
Dim db as Database
Dim rec as Recordset
set db = CurrentDB
set rec = db.OpenRecordSet("Select SomeField from SomeTable Where Something = 'SomethingElse'")
MyRandomField = rec("SomeFieldName")
set rec = Nothing
set db = Nothing

Query by Form for multiple fields in Access 2010

I want to create a query which takes field parameters through a form. For this, I created a form with combo boxes and drop down options to select the values from, this populates a text value in the respective invisible text fields whose default value I have set to null. Now in my query I give criteria for column as iif(isNull([Forms]![Conditions]![text_on_form]), [column_in_table], [Forms]![Conditions]![text_on_form]). I have done this for all the columns on which the where clause comes from the form. I have tried running this. The results seem to be random. It worked for three columns, but when I played around with it, it was giving me empty result set. Can anyone tell me what I am doing wrong? Or if there is a better way to implement query by form in Access.
It sounds like you are trying to create dynamic SQL. Here is the method in vba I generally prefer:
Dim SQL As String
SQL = "SELECT tblName.* From tblName WHERE (1=1)"
If Not IsNull(Me.combo1) Then
SQL = SQL & " And ([Field1] Like ""*" & Me.combo1 & "*"")" ' I am using like statements here, but that is because this is a search tool.
End If
If Not IsNull(Me.combo2) Then
SQL = SQL & " And ([Feild2] Like ""*" & Me.combo2 & "*"")"
End If
Docmd.RunSQL SQL
End Sub
Basically, add on to the SQL statement only if the user has put a value into your text box/ combo box or whatever. The "Where (1=1)" is to account for a situation where all fields are null.
Play with this concept to create your SQL statements. Avoid using invisible text boxes to store data, it generally means you are doing something wrong and will get mixed results (someone else on this forum can explain better than me why that is).
Just use the Like operator. Put this in your criteria field in the query Like "\*" & Forms![Form_Name]![Form_Field] & "\*" -- This tells it to get anything if the field is blank (or null) and matches whatever you have in the field. This may not be what you want. It should be noted that it will return anything with the text string in it. For example: if you type "the" it will return tether, these, theses, thermometer (anything with the word "the" in it. It works best for multi word or longer strings that can be matched more accurately, however it works for a search query because there is usually a set of human eyes looking for the result and erroneous results is not a huge problem.