Microsoft Access, auto generate columns in DataSheet subform - vba

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

Related

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

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.

Add data field from table to form automatically using vba

In an Access database, I have a split form. The datasheet is based on a query.
The table that is queried sometimes grows in fields.
This field is in the query, but not in the form because it has to be dragged from the "available fields" on design view on access into the form.
Is there some code that will allow a field to be added to a form when a button on the form is pressed instead of the user going into design view?
This would be more convenient than having every user opening and editing (possibly breaking) the database in design view.
As you can see from the comments, similar questions have been asked and so the default answer is that even with VBA code the form must be in design mode to add new controls - you cannot do this in Form View. But despite the limitations of Access there is still often a perfectly reasonable need that still requires a useful solution.
One potentially cluttered and limited solution is to add hidden unbound controls (i.e. ControlSource property is blank) that can then be bound and shown during Form View. First, during design time add hidden, unbound TextBox and Label controls to the form. Here is some template code within a button click event handler.
Private Sub cmdAddFields_Click()
Dim rs As Recordset2
Set rs = Me.RecordsetClone
Dim fld As Field2
...
'* Determine which new fields need to be shown
set fld = rs.Fields(missingFieldIndexOrName)
...
Me.txtCustom1.ControlSource = fld.Name
Me.lblCustom1.caption = fld.Name
Me.txtCustom1.Visible = True
Me.lblCustom1.Visible = True
...
End Sub
It should be apparent that you would be limited to the number of these dummy fields that you have added, and it'll require some clever way of determining what your missing fields are but that could be done by looping through the rs.Fields collection and the form's Control collection to match names (for instance).

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!

Hidden Column in Listbox - Access 2007

I have a listbox in Access 2007 that is linked to a table. That table has 4 columns but I only have 2 of those columns visible in the listbox. I use the loop command to identify the selected row but I can only view the contents of the visible columns. I display the visible column when I find it so at least I know I have the right row. It is my belief that the other 2 hidden columns are technically available to me because I see them referenced when I view the SQL associated to the listbox. So I have 2 related questions:
How can I confirm that those 2 hidden columns are actually available to me? And how can I access them (I want to get the primary key associated to the row selected.)
If those hidden columns are available and I wanted to make them visible in the listbox, how would I do that?
Learning Access is now a weekend hobby.Thanks in advance. DaveL
You can make a listbox show whatever you would like. When you have it selected in design view then open the property sheet and select the Format tab. Where it says column count and column widths is where you can modify the obvious. The Data tab on the property sheet will allow you to select all 4 of your fields to appear in the listbox.
Now to use the data in that listbox, you can use the VBA for click() and choose which column you want to work with if you have the primary key associated with that listbox.
Public Sub The_Listbox_Click()
Dim myR as Recordset
Set myR = CurrentDb.OpenRecordset("Table_Name", dbOpenDynaset)
myR.FindFirst ("[Primary_Key_Field] = '" & Me.The_Listbox.Column(0) & "'")
'You can now use that record with myR![Field_Name]
Set myR = Nothing
End Sub

Display queries in access subform from a selected listbox

Within Access 2010, I am trying to make a form display a query within a subform QueriesSubForm that when selected from listbox QueryListBox and then click on the button runbtn. It is supposed to display the query within the linked subform, and change when you do this whole steps again from a different choice selected on the listbox and click on the button.
At the moment I can only get it to work, if I want it to display the queries in a new task window, when programmed like so:
QueriesListBox Listbox - SQL View
SELECT MSysObjects.[Name]
FROM MSysObjects
WHERE (((MSysObjects.[Type])=5) AND ((Left([Name],1))<>"~"))
ORDER BY MSysObjects.[Name];
runbtn Button - VBA View
Private Sub runbtn_Click()
DoCmd.OpenQuery QueryListBox, acViewNormal
End Sub
It works and appears to just open one of the queries from the queries list and display it to me, which I do not want.
This might be an easy thing, but I can not see how it is done with either SQL, VBA or Macro, which I am guessing is need for this to work
Ok, here's one way to do it. First make sure your subform is set up with no source object. Then setup your button click like so:
Private Sub runbtn_Click()
Me.QueriesSubForm.SourceObject = "Query." & QueryListBox.Value
End Sub
That should get you the result you're looking for. Alternatively, if you want your form to open with a certain query to displayed on open, you could set up your subform's source object to that query. Using the properties window find the source object drop down and find the query you want to show when the form opens.