Access 2013 - Embedded query filtered by combo box on form - forms

I'm new to Access and this is the problem I'm suffering: I have four tables - Task, Person, Role, and TaskPerson (mapping table). I have a form that at the top has a unbound combo box displaying a list of people from Person. In the body of the form I have a query pulling from the Task and TaskPerson tables that is embedded as a datasheet. The fields from TaskPerson perform a lookup on Person and Role to display the actual values. Each task can have multiple people assigned to it and each person can have multiple roles. I am looking to pick a name from the combo box with the datasheet updating to only show the tasks associated with that person (i.e. matching the name from the combo box to the name in the person field (which is a lookup) on the form and only showing those tasks).
I have tried adjusting the Record Source for the query so the person field criteria would pull from the combo box using
'Forms![Task Form]![Combo11]'
but that hasn't worked. I have also tried a version of this answer:
Private Sub Form_SelectionChange()
' If the combo box is cleared, clear the form filter.
If Nz(Form) = "" Then
Me.Form.Filter = ""
Me.FilterOn = False
' If a combo box item is selected, filter for an exact match.
' Use the ListIndex property to check if the value is an item in the list.
ElseIf Me.Combo11.ListIndex <> -1 Then
Me.Form.Filter = "[Combo11] = '" & _
Replace(Me.Combo11.Text, "'", "''") & "'"
Me.FilterOn = True
End If
End Sub
While the code is not balking, it also isn't grabbing the selected name from the combo box, so it doesn't update. A likely factor is when I type Me.Combo11.Text, it doesn't actually display Combo11 as an option. I tried typing it in, in hopes of working, but I know that is a bit foolish.
Any detailed answers would be appreciated. I'm still learning my way around and I get lost a bit easily.
Steve.

The first method is the easier one.
In the query you have
WHERE TaskPerson = Forms![Task Form]![Combo11]
Note that there are no ' around the combo reference. With 'Forms![Task Form]![Combo11]' the whole thing is interpreted as string, so it doesn't work.
Then in Combo11_AfterUpdate you simply have
Me.Requery
Disadvantage of this method: you always have to select a person, or the form will be empty.
The second method:
Your query lists all record, the combobox applies a filter. Or removes it, if the user clears the combobox.
I suggest going back to the answer you used, and only replace
Combo_Reported_LOB_Selection by Combo11
and
[ReportedLOB] by [TaskPerson]
And the code doesn't go into Form_SelectionChange(), but into Combo11_AfterUpdate()

Related

How to create "Go To Next" record button in Access Form that references an alternate form

In my Access dB, I have a Form ("frmSearch") with a Subform ("subFrmData") that references a query ("qryDynamicData").
The Main Form has 6 drop downs that filter the data table in the Subform. The combo boxes are cascading so that once you select one, the entries that appear in the remaining combo boxes are only those entries in the query that correlate to the first selection. The goal is to keep making the data in the Subform data table shorter and shorter. Here are the fields in the combo boxes:
Region
Account Executive
Manager
Engineer
Stage
Project Number ("ProjectSLCT")
When the user filters down to where the list of projects they are looking at is small enough, they use the final combo box ("Project Number") to select an entry from the table. Doing this brings up another form ("MPC_ProjectNotes") as a pop-up form where they can keep track of project specifics. The event looks like this:
DoCmd.OpenForm "MPC_ProjectNotes", , , "Project_Number= '" & Me.ProjectSLCT.Value & "'"
I want to create a Next Record button on the "MPC_ProjectNotes" form that would in effect allow them to run through the steps of selecting the next item in the ProjectSLCT dropdown and thereby relaunching the MPC_ProjectNotes form with the next item from the combo box (and from the datasheet in "subFrmData") without having to close the MPC_ProjectNotes form and adjust the combo box.
Any thoughts? I don't really even know what to google to get myself pointed in the right direction on this. It seems "Next Buttons" aren't generally setup to work across forms.
Ok, here is what I would suggest:
In place of launching form MPC_ProjectNotes to ONE reocrd?
Why not launch the form with the SAME criteria and list as your combo box ProjectSLCT.
Now, we would of course land in the first reocrd of ProjectSLCT. but that's probably ok!
Now say if ProjectSLCT was NOT on the first record? Then we would simple have to add one extra step: move the form to the right record.
So, the logic is this:
Launch the 2nd form to the same "list" as the combo box.
Move the 2nd form to the SAME item currently selected in the combo box.
Now, you don't even have to write a next/previous button, but can simple display the built in navigation buttons. Since the form is LIMITED to the same list, then regular navigation in that form will work and work without you having to write any code!
So someplace in your first form, you EVENTUALLY wind up with this:
combobox data source = select * from tblWhoKnows where (CRITERA GOES HERE!!!).
So, now we simple launch the 2nd form with this:
DoCmd.OpenForm "MPC_ProjectNotes", , , (CRITERA GOES HERE!!!)
Now the form is loaded with the SAME list. We just this extra line of code to move/jump the form to the current selected row in the combo.
forms("MPC_ProjectNotes").RecordSet.FindFirst "Project_Number= '" & Me.ProjectSLCT.Value & "'"
So we open the form to the "list", and then jump to the corrent combo box selected. The result is a form that you can navagate teh combo list, but we jump/started out on the same combox selected item from that list in the form.
So the code will look something like this:
DoCmd.OpenForm "MPC_ProjectNotes", , , (CRITERA GOES HERE!!!)
Forms("MPC_ProjectNotes").RecordSet.FindFirst "Project_Number= '" & Me.ProjectSLCT.Value & "'"
You will of course "change" the above "CRITERA" to the SAME criteria you used in your code to fill out the last combo box.

MSACCESS - How to customize all the Switchboard entries texts at once by a condition

I have a default Switchboard generated by MS Access and i want to customize every single entry of the list at once.
The Switchboard form by default is set on "contiunous form" and the entry's control is a textbox (ItemText) identified via VBA as OptionLabel1.
I added to the default "Switchboard Items" table a new field called "SecLevel" where i added for each entry/record a value like Admin, Operator and User.
Now i want each item in the Switchboard form's list to change its text color based on "SecLevel" value like red for Admins and blue for Operators.
So i tried like this:
Private Sub Form_Current()
TempVars!CurrentItemNumber.Value = [ItemNumber].Value
Dim ctrl As control
For Each ctrl In Me.Controls
If ctrl.Name = "OptionLabel1" Then
If DLookup("[SecLevel]", "Switchboard Items", TempVars!CurrentItemNumber.Value) = "Admin" Then
Me.OptionLabel1.ForeColor = RGB(255, 0, 0)
ElseIf DLookup("[SecLevel]", "Switchboard Items", TempVars!CurrentItemNumber.Value) = "Operator" Then
Me.OptionLabel1.ForeColor = RGB(0, 0, 255)
Else
Me.OptionLabel1.ForeColor = RGB(0, 0, 0)
End If
End If
Next
End Sub
This doesn't work help..
Wrong Dlookup criteria. You want to fetch the SecLevel of the Switchboard Item with same Item Number as stored in TempVars!CurrentItemNumber.Value. use:
DLookup("[SecLevel]", "Switchboard Items", "[Item Number] = TempVars!CurrentItemNumber.Value")
or TempVars!CurrentItemNumber.Value gets converted to True (if <> 0, first values is fetched as criteria is true for all rows) ot False (if = 0, no values is fetched)
Wrong event.Form_Current event is fired every-time you move the forms recordset cursor to another record. To execute code on form startup, use Form_Open if you don't need values from bound queries/fields (e.g. to check priviligdes and close if not sufficent priv) as it fires before data is fetched.
But as you need [ItemNumber].Valueuse Form_Load event (fires when form with data is loaded.
On a continuous Form a control inside Details-Section is copied for every record, but still has same name. In Form_Current event Me.OptionLabel1 always refers to the control in actual selcted row. All other copies are not affected.
To work around use Conditional Formatting or use Detail_Paint event.
Some other improvements can be:
if you know controls name, no need to loop whole Controls collection, just refer to by using Me.Controls("NameOfControl").
use Select Case to tell different values of an expression apart. E.g.
Select Case DLookup("[SecLevel]", "Switchboard Items", "[Item Number] = " & TempVars!CurrentItemNumber.Value)
Case "Admin" '
' code on Admin here
Case "Operator"
' code on Operator here
Case Else
' code executed if no match in cases
End Select
Be aware of case-insensitive string comparison if usual Option Compare Database is set.
Use proper naming conventions! Even you don't seem to tend to ugly ungarian-notation OptionLabel1 is a poor identifier, not telling us anything useful. See variable names for some good infos (also check the rest of the site as it contains lots of good advices!). In table/field names avoid special chars, only use letters, numbers and underscore, then you don't need square brackets! Also get used to rename controls dropped from a query/table, as otherwise the control and the data field get the same name what can cause some trouble! Another great resource on vba coding is RubberduckVBA addin (try it:)) and their blog. Even they focus a lot on Excel, there is no better resource to learn OOP vba coding. Maybe start with bad habbits and then move on where you like (I recommend OOP Battleship Part 1: The Patterns)

Access Search Subform + Update Query Subform?

So I'm new to Access 365, and I'm working on a database for my church's cemetery. I have a "main" form that will house searches and the results of said searches (https://i.imgur.com/v6ZmDx2.png).
So I'd like to put a box on this form that when I press the "Run Query" button, updates with all records matching the criteria. I have the query working, and if I go into the individual search form and search, it works fine.
If I try dragging the query onto the main form, I get a SearchQuery subform, but when I go into form view, I have to fill out data before the form even loads. I need it to only update after I click the button, so that I can enter info, THEN search (https://i.imgur.com/6jJ416o.png & https://i.imgur.com/XPPpg6S.png). If I click cancel, it loads fine, but when I type in data to the search then press "Run Query", it still prompts me for the info (https://i.imgur.com/FKbZ6WK.png).
Thanks in advance!
Your code is constructing criteria with control names as the data to search in, must use table field names. Remove the Result_ from each expression.
Coffin and Cremation radio buttons are within an OptionGroup control. This means you must test for the value of the OptionGroup, not the controls within the group. Clicking radio button sets value of the OptionGroup control. Following is revised code for the OptionGroup and checkboxes. Note removal of Result_ - fix the other conditional expressions as well. Might want to rename the OptionGroup control.
'Coffin/Cremation
If Not IsNull(Me.optGroup) Then strFilter = strFilter & "([Coffin/Cremation] = " & Me.optGroup & ") AND "
'Veteran
If Not IsNull(Me.Veteran) Then strFilter = strFilter & "([Veteran] = " & Me.Veteran & ") AND "
'Monument
If Not IsNull(Me.Monument) Then strFilter = strFilter & "([Monument] = " & Me.Monument & ") AND "
Why is the Clear Search button using EmbeddedMacro? Code to clear search parameters:
Private Sub cmdReset_Click()
'Purpose: Clear all the search boxes in the Form Header, and show all records again.
Dim ctl As Control
'Clear all the controls in the Form Header section.
For Each ctl In Me.Section(acHeader).Controls
Select Case ctl.ControlType
Case acTextBox, acComboBox, acCheckBox, acOptionGroup
ctl.Value = Null
End Select
Next
'Remove the form's filter.
Me.FilterOn = False
End Sub
Consider using comboboxes instead of textboxes to help users enter valid data. Can still allow any input and use LIKE/wildcard. RowSource SQL could be like:
SELECT DISTINCT [Last Name] FROM A ORDER BY [Last Name];
Advise not to use space nor punctuation/special characters (only exception is underscore) in naming convention.
You can access any form from the subform as follows:
MainForm: LOAN SETTLEMENT FORM
ex:
Forms![LOAN SETTLEMENT FORM]!txtEMP_ID.Value = Me.EMP_ID.Value
Forms![LOAN SETTLEMENT FORM]!txtEMP_NAME.Value = Me.EMP_NAME.Value

Access 2010 - enter references to form elements as the value of a text field

Is there a way to take a value from a field on a form and use it as a reference to a different field in the same form, and not just literally? I want to be able to manually enter something like [txtFlavor] in one field and have it show the actual flavor, the value of the field named "txtFlavor" in another field, and not just the string "[txtFlavor]". I'm basically trying to store some vba references (terminology?) in a table so I can bring up a string of text with references to values on the form.
I have been asked to create a system that will store letter templates in Access 2010 and allow users to choose a record with personal information and insert that info into a template letter, preferably displaying it on a form immediately in plain text. I already proposed using reports to do this but that was unacceptable to the end users. They really just want a form that combines
a) contact records, one at a time
with
b) letter templates, one at a time
I've been trying to store the template info with it's form references in a table, but I have yet to be able to make references pull data from another text field on the form.
Is it possible and/or sensible to try to store something like the following in a table, or to enter it into a field on a form?
[txtFlavor] & " is dull but popular."
and then have it show up elsewhere in the form as
Vanilla is dull but popular.
I sure feel dumb and am sure I've missed something obvious. Everything I do is just repeated literally and not interpreted as a reference.
You could get your users to create their templates using 'tags' as placeholders for the database information, in a similar way to how you would design a merge document in Word. So in your example above, the template document would look like:
{Flavor} is dull but popular.
When it comes time to create the merged result you would need to use the Replace function to change these tags to actual data values. So if you had a read-only text box on your form, the control source could be:
=Replace([txtTemplate], "{Flavor}", [Flavor])
I assume you would have lots of potential tags, so using this approach you would need to nest the Replace functions. I have split my nesting across multiple lines to make it a bit more readable:
=Replace(
Replace(
Replace([txtTemplate], "{EmpName}", [EmpName]),
"{EmpAddress}", [EmpAddress]),
"{EmpPhone}", [EmpPhone])
If you had many more database fields/tags this would start to become very unwieldy so I would recommend using some VBA to make life easier, maybe something along the lines of:
Dim rsSource As Recordset
Dim strMerge As String
Dim intField As Integer
'Assuming your form has a field called EmpNo (numeric data) that you can use to pull data...
Set rsSource = CurrentDb.OpenRecordset ("Select EmpName, EmpAddress, EmpPhone From Employees Where EmpNo = " & Me.EmpNo)
strMerge = txtTemplate
For intField = 0 to rsSource.Fields.Count - 1
strMerge = Replace(strMerge, "{" & rsSource(intField).Name & "}", rsSource(intField))
Next intField
txtMerge = strMerge
rsSource.Close
Set rsSource = Nothing
You could put this code in the AfterUpdate event of your txtTemplate text box and it would update the contents of the txtMerge text box. You either need your tag names to match your database columns, or else you could alias the columns in the Select statement so they match the tag names.

How do you edit records from a VBA form that you want to interactively select?

I have a set of ComboBox's in an MS Access 2003 DB that are all bound to fields in a single table. However, the data that they allow you to select doesn't come from that table and instead comes from various other tables. This works fine for the record creation story but now I want to be able to edit the record retroactively. The problem is that I can't figure out how to refill the form elements without writing a bunch of custom code.
My initial inclination is to provide a combo box that limits your choices to record IDs and then do a custom query and use that to set the selected values in all of different form elements. However, I feel like I should be able to do something as simple as DoCmd.GoToRecord , , , ID and the form should repopulate just fine. I'm not opposed to doing the busy work but I'm sure I'm just missing something in my relatively puny knowledge of VBA and Access.
Just to add to the mix, I would offer two approaches, one recommended, the other not.
Approach 1: If you've bound your form to the whole data table (this is the non-recommended approach), you can use the combo box wizard to navigate to the requested record, but I wouldn't recommend it in recent versions of Access:
a. it doesn't allow you to properly name the combo box before it creates code.
b. the code is just WRONG.
Here's the code I just produced in my test database:
Dim rs As Object
Set rs = Me.Recordset.Clone
rs.FindFirst "[InventoryID] = " & Str(Nz(Me![Combo2], 0))
If Not rs.EOF Then Me.Bookmark = rs.Bookmark
This is wrong in so many ways it's just remarkable. This is what the code should be:
With Me.RecordsetClone
.FindFirst "[ID]=" & Me!cmbMyComboBox
If Not .NoMatch Then
If Me.Dirty Then Me.Dirty = False
Me.Bookmark = .Bookmark
Else
MsgBox "Not Found!"
End If
End With
There is no need to clone the form's recordset when the RecordsetClone already exists.
There is no reason to use an object variable when you can just directly use the pre-existing object.
There needs to be a check for a dirty record before departing the record because if you don't force the save, errors in the save process can lead to lost data.
But the better approach is this:
Approach 2: Use the combo box to change the form's underlying recordsource.
The AfterUpdate event of your combo box would look something like this:
If Not IsNull(Me!cmbMyComboBox) Then
Me.Recordsource = Me.Recordsource & " WHERE [ID]=" & Me!cmbMyComboBox
End If
Now, this only works the first time, as on the second resetting of the Recordsource, you end up with two WHERE clauses, which is not good. There are two approaches:
a. assuming that the form opens without a WHERE clause, store the opening recordsource value in a module-level variable in the form's OnLoad event:
Private Sub Form_Load()
strRecordsource = Left(Me.Recordsource,Len(Me.Recordsource)-1)
End Sub
And at the module level, define strRecordsource accordingly:
Dim strRecordsource As String
Then in the combo box's AfterUpdate event, you have this instead:
Me.Recordsource = strRecordsource & " WHERE [ID]=" & Me!cmbMyComboBox
Now, if your form opens with a WHERE clause already defined, it gets more complicated, but I'll not go into that and leave it as an exercise to the reader what the best approach might be.
I presume that you've already set up the row sources for each combo box. So long as you haven't limited the combo box to that list; it should display what you have stored in that column.
However, if your Combo Box changes its list for each row you can do something like this in the record's OnCurrent event or the field's GotFocus event:
Me.combo_box_name.Requery
After re-reading your question, I think I see what you are trying to achieve. You're on the right track with GotoRecord, although I would probably use OpenForm in this case, because it has a WhereCondition property that allows you to use SQL to specify exactly what record to open. It sounds like you want to implement a "jump to record" type functionality in your form, where the user selects a record ID from a list and the form changes to display the selected record.
One possibility is to switch to the new record each time the user selects an item in the ComboBox. You can handle this in the ComboBox's Click event.
I'll use a simple example: suppose you have a Students table, and a StudentForm for viewing/editing records in the Students table. The StudentForm has a ComboBox cboStudentID that is bound to the Students.ID column via it's RowSource property. When you select a student ID in the ComboBox, the StudentsForm will switch to display the corresponding student record.
In the Click event handler for the ComboBox, you can code this "jump to record" functionality with something like the following:
Private Sub cboStudentID_Click()
Dim recordID As Long
'The ItemData property will return the value of the bound'
'column at the specified index.'
recordID = cboStudentID.ItemData(cboStudentID.ListIndex)
'Jump to the record. This assumes we want to use the same form.'
'You can change the form name if you want to open a different form when'
'the user selects an ID from the ComboBox.'
DoCmd.OpenForm "StudentForm", WhereCondition:="Student.ID=" & recordID
End Sub
As David W. Fenton points out in the comments, you can shorten the following line:
recordID = cboStudentID.ItemData(cboStudentID.ListIndex)
to this:
recordID = Me!cboStudentID
or just:
recordID = cboStudentID
since the default value of the ComboBox in this case will be the value of the bound column at the current ListIndex. In this case, you could just remove recordID altogether and code the Click event as follows:
Private Sub cboStudentID_Click()
DoCmd.OpenForm "StudentForm", WhereCondition:="Student.ID=" & cboStudentID
End Sub