How to use DLookup criteria from different tables in Access - ms-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] & "'")

Related

Store filtered employees in training record

Good afternoon,
I have a form used to create a "toolbox talk". A toolbox talk is not always applicable to every employee but might be limited to a specific department, gender, or competency (or any combination of the three). I have created a subform which using unbound text boxes allows me to filter my list of employees based on the toolbox talk criteria - great!. See screenshot below:
However what I cant work out now is how I can then store the filtered results (list of employees) as recipients against the toolbox talk record.
I know that I could include a control to select employee ID/Names line by line as per the filtered results, however I was hoping that a quicker option could be created.
Can someone please suggest a possible solution?
Thank you in advance.
If you want to 'batch' create records, one approach is an INSERT SELECT action SQL that uses the same criteria selected by the form controls. If your code applies this criteria to the form Filter property, that property can be referenced to incorporate filter criteria for SQL. I prefer to use CurrentDb.Execute because then don't have to deal with RunSQL popup warnings.
Private Sub Command16_Click()
Dim mySql As String
mySql = "INSERT INTO tblEmployeeToolboxTalk (EmployeeID, ToolboxTalkID) " & _
"SELECT EmployeeID," & Me.ToolboxTalkID & " AS TTID FROM tblEmployees WHERE " & Me.Filter
CurrentDb.Execute mySql
End Sub
If you need guidance on conditionally building filter criteria in VBA, review http://allenbrowne.com/ser-62.html

Microsoft Access vba update date of record on button click

I have a form with combobox cmbProjectName where a project name can be selected from tblProjects. The form also has a button btnComplete.
When the button is clicked, I would like to update the record for the selected project so that field Date Modified is filled with today's date. I'm having trouble coding up the VBA to find the correct record to update.
The field I am looking to update is tblProjects.[Last Modified], and I would like to find the record by referencing the combobox cmbProjectName by using the column tblProjects.projName.
This could be handled several different ways, however, it looks like you might be trying to find a VBA SQL solution. As such, try this:
Currentdb.Execute "UPDATE tblProjects " & _
"SET tblProjects.[Last Modified] = DATE()
WHERE tblProjects.projName = " & cmbProjectName.Value & "", dbfailonerror
This would of course require that the tblProjects.projName be a unique value for the entire table. Otherwise, you will need some other sort of solution.

Blank subform: Unable to find a record, based off multiple fields

I've looked around for an answer to this issue, but have fond none. Thank you in advance to anyone who's able to help. I'm trying to look up records and alter them, based off multiple fields. However, my form shows up blank.
I have a database with one to many links for the following tables:
Sample->Set->Catch->Length->Diet (Key fields: SampleID, SetID, etc.)
Preliminary data is entered. I have additional data for some individuals to be entered into the Length and Diet tables. So, I created a form with combo boxes that allow the user to navigate to the correct fish by selecting: Date, Station, Set, Species, and Length. So, when I select a date, I'm restricted to stations sampled on that day and so on. I have a query string set up to restrict results to those matching the criteria entered into the combo boxes. My subform is based off the final query in this string (Query 5). It's linked on the primary key field for the length table (LengthID). All fine so far.
The issue: When I open my form and select values for each combobox, the subform remains blank. However, I can run Query 5 from the sidebar at this point and it runs successfully. I could just enter data directly into the query, but it would be less streamlined and vulnerable to human error.
I've also tried opening my subform directly from the sidebar. When I do this, Access prompts me for the Date, Station, Set, Species, and Length. Twice. The form then shows up and all are fields blank including the LengthID field, which should be filled in (since I'm looking up an existing record). I don't know why it prompts me twice, but I think that the subform isn't showing up in regular form view because the database sees the LengthID field as blank.
My combo boxes appear to navigate correctly to a given record. The query string my combo boxes and subform are based on all work when run directly. But I can't enter data into my subform, presumably because the subform can't find the correct record even though the query it's based off of can find it just fine. I've run out of troubleshooting ideas, any advice is greatly appreciated. Thanks!
If I understand correctly, you're trying to achieve a query WHERE clause utilizing combo-boxes. There are many SO questions out there on this but this should get you going. Let me know if you run into trouble and I'll help you out.
I assume you have a linked parent/subform combo. This code would be on the parent form search button:
Dim strSQL As String
strSQL = " 1=1 "
If Not IsNull(cmbComboBox1) Then
strSQL = strSQL & " AND Field1 = " & cmbComboBox1
End If
If Not IsNull(cmbComboBox2) Then
strSQL = strSQL & " AND Field2 = " & cmbComboBox2
End If
If Not IsNull(cmbComboBox3) Then
strSQL = strSQL & " AND Field3 = " & cmbComboBox3
End If
Me.Filter = strSQL
Me.FilterOn = True

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.