How to use a combo box to fill mutltiple field in a subform in MS-Access? - vba

I have a sub form in Access that allows a user to select records using check boxes. In addition to this sub form there is a combo box with a list of names.
Is it possible to select a few records using the check boxes and assign a name to them with a press of a button?
The button is called [assignButton] , the sub form is called [list subform] and the combo box is called [personCombo] .
This seems like a simple task, but I am unfamiliar with how the VBA for the button triggering this kind of action would be written?
All records are bound to an existing table called "tbl_jobs" this table has the same amount of rows and columns as the subform in the screenshot

Disclaimer: The following code is only intended to illustrate how to update the subform rows, so it includes no error handling or other common process code. Also notice that the SQL statement has no additional criteria in the WHERE clause, primarily because the question lacks the subform's actual RecordSource query and/or information about how the subform table is prepared and/or filtered for each time the form is loaded.
Private Sub AssignPerson_Click()
Dim qry as QueryDef
Set qry = CurrentDb.CreateQueryDef("", _
"UPDATE tbl_jobs SET Person_Name = [ParamName]" & _
" WHERE [Select] = True")
qry.Parameters("ParamName") = PersonCombo.Value
qry.Execute
Me.list_subform.Requery 'Ensure subform displays updated rows
End Sub
Really this question is borderline "Too broad" for Stackoverflow. There are multiple ways to accomplish what you want, and your problem is one of design, coding and understanding. But in the end, this model code is rather simple and satisfies the basic requirements so I feel it not worth nitpicking.

Related

ms Access: Switching between subform recordsource when changing records

I have a main form and a subform on it. I want the recordsource of the subform to change depending on the value of an ID field of the main form. This works when I do it in the Form_Load event of the parent Form. However, I also want it to update when the user switches to a new record on the main form (single form) while it is open.
The code I have atm is the followng:
Private Sub Form_Load()
'***************************************************************************
'Purpose: Switch subform recordsource based on recipe ID
'Inputs: None
'Outputs: None
'***************************************************************************
Dim strRecipeID As String
Dim strSub1QueryName As String
strRecipeID = Forms![frmMainForm]![RecipeID] 'get RecipeID
strSub1QueryName = DLookup("[QueryName]", "tblRecipeQueries", [RecipeID] = strRecipeID) 'Get name of query
Forms!frmMainForm!frmSub1Sub.Form.RecordSource = MakeSqlString(strSub1QueryName) ' Set Subform1 recordsource
End Sub
MakeSQLString() is a function that gets the SQL SELECT statement as a string from a given access query. I tried the change event, the Click event and the Current event and requerying the subform after that but none have any impact on contents of the subform (the recordsource does not change) but stays the same one that was selected when the form loaded.
I'm not sure which other events could work for this or from where I can execute the change in recordsource most effectively, maybe the subform instead? Maybe it has something to do with the subform loading before the parent form? I'm not sure, might be a rooky mistake.
I appreciate any help. BTW, the fields on the subform stay the same, so changing the recordsource just updates the calculations that are made in the query to get the values for those fields. The query names are stored in a table in my db. Again, It works in the Load event of the main form I just can#t get it to update on the fly while the main form is open and the user navigates to a new RecipeID on said main form.
In your DLookup you are not enclosing the where portion in quotes. You have:
DLookup("[QueryName]", "tblRecipeQueries", [RecipeID] = m_selectedId)
But it should be:
DLookup("[QueryName]", "tblRecipeQueries", "RecipeID =" & m_selectedId)
That should take care of your issue.

How to select table values from combobox selection?

I'm using an Access 2003 database and have 2 comboboxes I am trying to work with. The first box I have perfected already, which is a dropdown of different tables (categories of parts). Once that table is selected, I want to be able to look at the part numbers within that category through a dropdown box selection. From here I want to be able to pull up the correct report for that category with that part number in it so I can print a report for every part number. I'm sure I'll have to write some sort of VBA, Query or Macro AfterUpdate() code, but I just don't know how to fill that second combobox with the selected table's part numbers.
Click here for an image of my Menu layout
Here's my Query for the first box to show the tables I want:
SELECT Msysobjects.Name
FROM Msysobjects
WHERE (((Msysobjects.Name) not Like "MSYS*"
And (Msysobjects.Name) not like "_*"
And (Msysobjects.Name) not like "~*"
) AND ((Msysobjects.Type)=1))
ORDER BY Msysobjects.Name;
And I think this is what I'll need to print after the second box has it's selection:
Private Sub partnumberselect_AfterUpdate()
DoCmd.OpenTable Forms![_Datasheet Printing].Form.TagLabelSelection.Column(1), acViewNormal
End Sub
Thank you in advance and let me know if you have any questions.
You are attempting what are called "cascading comboboxes" which means the second box is dependent on the selection of the first.
This is accomplished through the control source of the second combo box.
The first thing you should do is write a query that returns all possible options of the second combobox, without caring so much about filtering it based on the first combo selection. Once you have it returning the correct data, you will add a WHERE clause to the second box's control source that's something like:
WHERE Msysobjects.Name Like Forms![_Datasheet Printing]!TagLabelSelection.Value
This is referencing your first combobox on your form. So after a selection is made in the first combobox, the underlying control source of the second will have the proper criteria to return the appropriate options.
However, you will need to add some VBA to the AfterUpdate() event on the first combobox. Once the selection is made, you need the second box to refresh the control source to populate the correct selections. The code is simply:
Forms![_Datasheet Printing]![MySecondComboboxName].Requery
Please see the example below.
Private Sub cboCountry_AfterUpdate()
On Error Resume Next
cboCity.RowSource = "Select tblAll.City " & _
"FROM tblAll " & _
"WHERE tblAll.Country = '" & cboCountry.Value & "' " & _
"ORDER BY tblAll.City;"
End Sub
You can read all about this concept, and others, in the link below.
http://www.fontstuff.com/access/acctut10.htm

navigation subform requery stopped working

I've built an unbound form which allows a user to select from two combo boxes that contain related information (Zone and Watershed Unit -- each Zone contains multiple watershed units) in order to see what regulations apply to each. Based on these selections (stored in txtZone and txtWU on the main form) a subform would show the existing regulations (sfrmRegsbyZWU based on qryRegsbyZWU). This serves as a reference for the user, who picks a new regulation to add from another subform, clicks a button, and the selection is added to the regulations for the Zone/Watershed Unit selected. I had this successfully built with a workaround in the OnCurrent event of the subform (which was undesirable because the user couldn't click on a record and delete it) and everything worked until I added inserted code to change the query definitions for the query which is the basis for the subform as opposed to having it in the "On current" event of the subform.
At that point the requery syntax in the main form which had previously worked stopped working. This is in all embedded in a navigation form in Access 2010, so the previously working syntax was:
Forms!frmNav!NavigationSubform.Form.sfrmRegsbyZWU.Requery
I've tried every permutation of Requery I can think of, and I can not get it working. The underlying query has been changed, but the form doesn't update to reflect it. Can anyone explain to me what has gone wrong, and how to fix it? The code (attached to the _After Update() event of the combo boxes) is:
Private Sub cboZone_AfterUpdate()
'Changes WU combo box as well as the underlying text boxes
Me.cboWU.SetFocus
Me.cboWU = ""
'Blank out other selections
Me.txtWU.SetFocus
Me.txtWU = ""
'Update text box with combobox selection
Me.txtZone.SetFocus
Me.txtZone = Me!cboZone.Column(0)
'Change the query underlying the Existing Regs panel (frmRegsbyZWU, qryRegsbyZWU) to reflect selection
Dim strZSQL As String
Set qdfZ = CurrentDb().QueryDefs("qryRegsbyZWU")
Dim myZVar As Variant
myZVar = Forms!frmNav!NavigationSubform.Form.txtZone
'MsgBox (myZVar)
If IsNull(myZVar) Then
strZSQL = "SELECT * FROM tblRegulations WHERE FALSE"
Else
strZSQL = "SELECT * FROM tblRegulations WHERE Zone_No=" & Forms!frmNav!NavigationSubform.Form.txtZone
End If
'MsgBox (strZSQL)
qdfZ.SQL = strZSQL
'DoCmd.OpenQuery ("qryRegsbyZWU")
Forms!frmNav!NavigationSubform.Form.sfrmRegsbyZWU.Requery
Thanks in advance for any help!

Microsoft Access, auto generate columns in DataSheet subform

I want to create a form in MS Access 2003 that lets the user pick from any existing query, and then have it display the results inside the form (as a sub-form in DataSheet view). The user will then be able to select one or more records and click a button on the parent form to do certain actions based on the selection. I want it to be able to work with any query, with very few limits, and display the full results of the query (all columns). The only requirement I might have is that it include certain fields for certain actions. For example, if I have a "send email" action, the query will require a field named "email", or maybe "to" and "subject".
Changing the DataSource of the DataSheet sub-form at run-time isn't a problem, I've done that before using VBA. Getting the columns displayed to change is the problem.
In a .NET WinForms app this could be done with the "auto generate columns" on a GridView control, or using the GridView.Columns collection directly in code. In VBA I don't see a way to add/remove columns from a DataSheet view. I also don't see a way to auto generate them based on the query. It appears the columns are controlled by the controls placed on the form (in form view), and while it is possible to add/remove controls using VBA, the form would have to be placed in Design View and require exclusive access to the database -- sounds very messy and I would like to avoid the exclusive access part.
Am I missing something? Is there an easy way to do this?
Here's how I would go about it. Create a blank subForm control on your main form. To change the source and the columns just leave the source object blank, then when you set it with code, the columns will reset to whatever source you use. So set it like so:
Private Sub setSource()
Me.subForm.SourceObject = "Query.myQuery"
End Sub
Then to get the selected items, assuming you know what column you want, you would do something like this:
Private Sub getSelected()
Dim rs As Recordset
Dim f As Form
Set f = Me.subForm.Form
Set rs = f.RecordsetClone
Debug.Print f.SelTop
rs.MoveLast
rs.MoveFirst
rs.Move f.SelTop - 1
Debug.Print rs!ID
End Sub
If you don't know the column explicitly you can use this to loop through the columns of the selected item and run some analysis on each name until you determine it's the column you want.
Dim i as Integer
For i = 0 To rs.Fields.Count - 1
Debug.Print rs.Fields(i).Name
Next

Access 2007: Filtering a report's results using a drop-down box

My question is twofold.
I have around twenty assorted tables in a database. The table layouts are diverse; the one common thread is that all of them have a 'County' field.
I need to set up a series of reports which allow a user to select a county from a drop-down box, triggering the report to run and return only records attached to that particular county.
This is doable at the datasheet level using a filter-by-form, but that's pretty clunky and I have several tables/queries which will need this same county filter.
I may be halfway there with the following:
Create an unbound form.
Add a combo box.
Set the Row Source of the combo box to include the County field.
Set its Bound column to 1.
Set its Column Count property to 2.
Set the Column Width property to 0";1"
Name the Combo Box 'ChooseCounty'.
Add a Command Button to the form.
Code the button's click event as follows:
(Note: To write the code, in Form Design View select the command button. Display the button's property sheet.
Click on the Event tab.
On the On Click line, write:
[Event Procedure]
Click on the little button with the 3 dots that appears on that line.
When the code window opens, the cursor will be flashing between two already existing lines of code.
Between those lines, write the following code.)
Me.Visible = False
Close the Code window.
Name this form 'ChooseCounty'.
In the Query that is the Report's Record Source [County] field
criteria line, write:
forms!ChooseCounty!ChooseCounty
Next, code the Report's Open event:
(Using the same method as described above)
DoCmd.OpenForm "ChooseCounty", , , , , acDialog
Code the report's Close event:
DoCmd.Close acForm, "ChooseCounty"
When ready to run the report, open the report.
The form will open and wait for the selection of the Company.
Click the command button and then report will run.
When the report closes, it will close the form.
I can persuade the report to trigger the form, but only once - I can't seem to figure out where precisely the 'forms!ChooseCounty!ChooseCounty' needs to go. Perhaps someone can clarify or offer a more elegant way to do this?
I need to set up a large meta-report containing sub-reports on all of the tables - and, using the same drop-down 'choose a county' form, I need to have that choice cascade down through all the subreports. I don't have the faintest idea how to go about this. Suggestions welcome!
~ T
You seem to be asking two questions, the last of which is clear to me, but the first is not. The second one is in regard to how to cascade the filter to the subforms. You can do this in one of two ways:
put the form control reference as criterion in the recordsource of each subreport, OR
create a non-visible control on the report that has as it's controlsource "=Forms!ChooseCounty!ChooseCounty". Name that control "CountyFilter". Then, add CountyFilter to the link properties. If, for instance, you are linking the subreports on ID, you'd have:
LinkMaster: ID;CountyFilter
LinkChild: ID;County
(assuming, of course, that ID is your link field for the child reports, and that "County" is the name of the field in the child subreport).
Now, I'm wondering why you would have the County data not just in the parent record but in the child records -- that makes no sense. If you do have it, then the solution above will work.
If you don't, then I don't understand the question, as the whole idea behind subreports is that they are filtered by the parent record, so if the parent record is a person, and you filter by COUNTY, you're only going to get the child records in the subreport for that person, which by definition are already filtered by COUNTY because the parent has been filtered.
As to the earlier question, you write:
I can persuade the report to trigger
the form, but only once - I can't seem
to figure out where precisely the
'forms!ChooseCounty!ChooseCounty'
needs to go
You have two choices:
hardwire the recordsource of the report to use the form control reference, so the WHERE clause of your report would be "WHERE County=Forms!ChooseCounty!ChooseCounty" (and you should set this as a parameter of type text to insure that it gets processed correctly).
the better meethod is to set the recordsource in the report's OnOpen event.
After you open the form as a dialog, you'd have something like this:
Me.Recordsource = "SELECT * FROM MyTable WHERE County='" _
& Forms!ChooseCounty!ChooseCounty & "'"
And immediately after that line, you can close the form, since it's not needed any longer.
You will likely want an OnNoData event for the case where no records are returned. This is usually something simple like:
MsgBox "No records found!"
DoCmd.Close acReport, Me.Name
I hope this answers your questions, but if not, I'm happy to offer more explanation.