Is there a way to automatically populate fields in an MS Access form? Lets say the user makes a selection from a specific combo box on the form, is there something that can be done to automatically select the other fields on the form based on the PK?
Id like to add that the fields to auto populate would come from various tables..
***ammendment
I need to return multiple values once i select a specific record in the combo box. Can someone help? The multiple values will come from a query that returns values like this:
ID Code Count
24 TST 4
24 BPB 7
24 SSS 10
In the form, the combo box would chose the ID number. Once I choose an ID number of 24, i want to return all 3 records above that come from a query called Project_Error_Final (in this example there are 3 values to return, but i want the query to return any records with ID = 24). The VBA code i have so far is:
Private Sub cboProjectID_Change()
Dim VarComboKey As Integer
Dim VarObjective As Variant
Dim VarStartDate As Variant
Dim VarEndDate As Variant
Dim VarRiskCategory As Variant
Dim VarTarDatSet As Variant
Dim VarErrorCount As Variant
Dim VarErrorCode As Variant
VarComboKey = Me.cboProjectID.Value
VarObjective = DLookup("[Objective]", "[Project_HDR_T]", "[Project_ID] = " & VarComboKey)
Me.txtObjective = VarObjective
VarStartDate = DLookup("[Start_Date]", "[Project_HDR_T]", "[Project_ID] = " & VarComboKey)
Me.txtStartDate = VarStartDate
VarEndDate = DLookup("[End_Date]", "[Project_HDR_T]", "[Project_ID] = " & VarComboKey)
Me.txtEndDate = VarEndDate
VarRiskCategory = DLookup("[Risk_Category]", "[Project_HDR_T]", "[Project_ID] = " & VarComboKey)
Me.txtRiskCategory = VarRiskCategory
VartxtTarDatSet = DLookup("[Targeted_Dataset]", "[Project_Targeted_Dataset]", "[Project_ID] = " & VarComboKey)
Me.txtTarDatSet = VartxtTarDatSet
VarErrorCount = DLookup("[Count_Error_Codes]", "[Project_Error_Final]", "[project_ID] = " & VarComboKey)
Me.txtErrorCount = VarErrorCount
VarErrorCode = DLookup("[ErrorCode]", "[Project_Error_Final]", "[project_ID] = " & VarComboKey)
Me.txtErrorCode = VarErrorCode
End Sub
The value in question is the VarErrorCount and VarErrorCode. In the VBA code above, only a single value is returned. But, I am looking for multiple VarErrorCount and VarErrorCode values to be returned in my form once the ID combo box field is selected. In this particular example VarErrorCode should return "TST", "BPB" and "SSS." The VarErrorCount should return the corresponding VarErrorCode values: "4","7","10"
With regards to your multiple returns, you can't use a DLookup, but I will show you how you can achieve the result you want, as per your description.
In this particular example VarErrorCode should return "TST", "BPB" and "SSS." The VarErrorCount should return the corresponding VarErrorCode values: "4","7","10"
Change your last 4 lines above the End Sub to the following:
Dim dbs as DAO.Database
Dim rst1 as DAO.Recordset
Dim rst2 as DAO.Recordset
Set dbs = CurrentDb
Set rst1 = dbs.OpenRecordset("SELECT [Count_Error_Codes] FROM [Project_Error_Final] WHERE [project_ID] = " & VarComboKey)
If rst1.RecordCount > 0 Then
rst1.MoveFirst
Do Until rst1.EOF
VarErrorCount = VarErrorCount & rst1!Count_Error_Codes & ","
rst1.MoveNext
Loop
' Remove the last comma
VarErrorCount = Mid(VarErrorCount, 1, Len(VarErrorCount) - 1)
End If
Set rst2 = dbs.OpenRecordset("SELECT [ErrorCode] FROM [Project_Error_Final] WHERE [project_ID] = " & VarComboKey)
If rst2.RecordCount > 0 Then
rst2.MoveFirst
Do Until rst2.EOF
VarErrorCode = VarErrorCode & rst2!ErrorCode & ","
rst2.MoveNext
Loop
' Remove the last comma
VarErrorCode = Mid(VarErrorCode, 1, Len(VarErrorCode) - 1)
End If
rst1.Close
Set rst1 = Nothing
rst2.Close
Set rst2 = Nothing
dbs.Close
Set dbs = Nothing
Me.txtErrorCount = VarErrorCount
Me.txtErrorCode = VarErrorCode
Yes there is!
Obviously, you need to be able to relate the combo box selection to the value you wish to be populated into the other field(s). Assuming that you have a 1:1 relationship with the PK (since you want to display only one value in your form), you can use the AfterUpdate event plus the DLookup() function to retrieve a related value using the PK.
As a simple example, I set up a table named Foods as follows:
FoodID, FoodName, FoodCategory
1, Orange, Fruits
2, Chicken, Poultry
3, Almond, Nuts
4, Lettuce, Vegetables
In the form, I have a control that selects the FoodID as the PK bound value named ComboFoods, and an unbound text box control named TextFoodCategory that we will populate with the FoodCategory from the Foods table.
I've assigned the following code to the AfterUpdate event of the Combo Box so that when the value of the combo box changes, the text box will be populated:
Private Sub ComboFoods_AfterUpdate()
'Create a variable to store the combo box primary key selection
Dim VarComboKey As Integer
'Create a variable to store the DLookup results
Dim VarFoodCat As Variant
'Capture the primary key of the combo box
VarComboKey = Me.ComboFoods.Value
'Retrieve the related field value
VarFoodCat = DLookup("[FoodCategory]", "[Foods]", "[FoodID] = " &
VarComboKey)
'Set the value of the text box to the variable
Me.TextFoodCategory.Value = VarFoodCat
This will return the FoodCategory that is related to PK. This is all using one table, but the DLookup statement can be modified to reference any query or table that contains the PK.
Please note that DLookup will only work properly when the PK is unique in the data you are referencing. It will not work in a one to many relationship unless you specify other criteria that restrict the results to one record. There are other ways to use SQL queries and recordsets within VBA if you need to return multiple records, but that this out of scope for this question.
This worked when tested - best of luck!
Related
I'm trying to populate a combobox with records from a table filtered by a parent combobox.
The table I want to filter is called muni and parent table is called prov. They are related by a common field (muni has a field called gid_prov that contains prov gid for each record)
First combobox stores the prov gid and shows the prov name.
Both tables are in a database from postgresql connected to access by an DSN file using ODBC.
I have tried many options, and none is correct.
First I tried a simple option. This code is useless now
Private Sub PROV_Change()
MUNI.RowSourceType = "Table/Query"
MUNI.RowSource = "select * from memoria.muni where gid_provs =" & PROV
MUNI.Requery
MUNI.SetFocus
MUNI.Text = ""
End Sub
PROV is the name of the parent combobox that stores the prov gid. And MUNI the combobox I want to populate.
Other option I tried was creating a query with an sql statement, this is the code right now, i tried with the OpenRecordsetOutput, but is not working. I can access the database and get the fields, but I can't populate the combobox MUNI
Private Sub PROV_Change()
Dim oDb As DAO.Database
Dim oRs As DAO.Recordset
dbconnect = "ODBC;DRIVER=PostgreSQL ANSI;UID=***;PWD=***;PORT=5432;SERVER=127...;DATABASE=memoria_historica;DSN=C:\Users\***"
Set oDb = OpenDatabase("", False, False, dbconnect)
Dim sql As String
sql = "select gid,nombre from memoria.municipios m where m.gid_provs =" & PROV & "order by m.nombre;"
Set oRs = oDb.OpenRecordset(sql, dbOpenSnapshot, dbSQLPassThrough)
Me.muni2.RowSource = ""
If oRs.RecordCount > 0 Then
With oRs
.MoveFirst
.MoveNext
Do While Not .EOF
muni2.AddItem .Fields("nombre").Value
.MoveNext
Loop
End With
End Sub
Worked fine tih the support of #Thaippo. Thanks
You can you DAO library.
You could you DAO. Database and DAO. Recordset like:
Dim oDb as DAO.Database
Dim oRs as DAO.Recordset
Your second block of codes could do the work.
Set oDb = OpenDatabase("", False, False, dbconnect)
Dim sql As String
sql = "select m.nombre from memoria.muni
m,memoria.prov p where st_within(m.the_geom,p.the_geom) and p.gid =" & PROV ";"
Set oRs = oDb.Openrecordset(sql)
If oRs.Recordcount > 1 Theb
With oRs
.Movelast
.Movefirst
Do while not.EOF
PROV.Additem . Fields("nameOfFieldsYouNeed"). Value
.Movenext
Loop
End With
End if
And it's would be a good idea to clear the combox box before adding new items in it.
I created a Form in Access, and within this form there is a button which will allow the user to insert a record into a table ("Tbl")
The format of this table is:
Report1_Field1
Report1_Field2
Report2_Field1
Report2_Field2 (and so on)
The Form will ask the user to:
- Select the report name ("ReportName"); which could be "Report1" or "Report2"
- Input a value for Field1 and Field2
The VBA code behind the button is as follows:
Private Sub ButtonUpdate
Dim NameReport as String
Dim FirstField as String
Dim SecondField as String
NameReport = ReportName
FirstField = ReportName & "_Field1"
SecondField = ReportName & "_Field2"
DoCmd.RunSQL "INSERT INTO tbl (FirstField, SecondField) VALUES (Field1, Field2)"
End Sub
I am however getting the Run-Time error 3127: The INSERT INTO statement contains the following unknown field name: 'FirstField'. Make sure you have typed the name correctly, and try the operations again.
Thoughts?
The SQL string is reading "FirstField" and "SecondField" as literal text instead of using your variables. Try this:
DoCmd.RunSQL "INSERT INTO tbl (" & FirstField & ", " & SecondField & ") VALUES (Field1, Field2)"
I have a query that you enter a number, and you get a result (it calculates something).
Now, I have a form with two inputs. In one input you type a number. After you type the number, I want my query to be called with the input's value as an argument, and then generate the number from query's result to the second input.
Here's an example VBA:
Private Sub Refresh_Button_Click()
Dim strSQL as String
Dim inputbox1 as String
Dim myR As Recordset
'set the input1 as a string
inputbox1 = Me.input_box_1
'this select statement creates a SQL string
strSQL = "Select whatever from table_name where field = '" & inputbox1 & "'"
'this recordset pulls your SQL statement so you can get your fields
Set myR = CurrentDb.OpenRecordset(strSQL, dbOpenDynaset)
'this gives the value of your second input box
Me.input_box_2 = myR!field_you_want_to_appear
Me.Refresh
Set myR = Nothing
End Sub
I am using Access 2010 with linked tables from SQL Server 2008. I have a form that I am populating using a recordset and the control source of the textbox in this form is set to a field from the recordset. I find that although I can navigate through all the 16 records on the form, and the form loads correctly, I am unable to edit the Notes text box. It needs to be editable. The textbox has Enabled=True and Locked=False. The AllowEdits property of the form is set to true. All the tables in the query have primary keys. So, is it my query then - since it has right and inner joins in it? So the issue is that I cannot type in the textbox.
Just a little background, I tried using a query as the recordsource for this form, but found that Access' AutoSave feature inserted incomplete records into my Result table, in addition to the updates and inserts done by my Save button event. If the only way to circumvent this is to ask the user whether he/she would like to save changes every time he navigates, then that would be way too frustrating for the end user. So, I have had to use an unbound form where I use VBA to populate it using a ADO recordset.
Incidentally, I can edit the DocID and DocumentType columns, it's the fields from the query that cannot be changed (QCNote)
Here is the code from my Form_Open event. I also have a Form_Current event that disables the Submit button for inapplicable categories.
Private Sub Form_Open(Cancel As Integer)
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Set cn = CurrentProject.AccessConnection
Set rs = New ADODB.Recordset
With rs
Set .ActiveConnection = cn
DocID = [Forms]![QCDocAttributes]![DocID]
DocumentType = [Forms]![QCDocAttributes]![Document Type]
strSQL = "SELECT " & DocID & " AS DocID,'" & DocumentType & "' AS DocumentType, QC_QCDecisionPoint.Description, QC_QCDecisionPoint.QCDecisionPointID , QC_QCResultDecisionPoint.QCNote FROM QC_QCResultDecisionPoint RIGHT JOIN ((QC_QCAttribute INNER JOIN QC_QCAttributeDecisionPointAsc ON QC_QCAttribute.QCAttributeID = QC_QCAttributeDecisionPointAsc.QCAttributeID) INNER JOIN QC_QCDecisionPoint ON QC_QCAttributeDecisionPointAsc.QCDecisionPointID = QC_QCDecisionPoint.QCDecisionPointID) ON QC_QCResultDecisionPoint.QCDecisionPointID = QC_QCDecisionPoint.QCDecisionPointID WHERE (((QC_QCAttribute.Description)= '" & [Forms]![QCDocAttributes]![AttributesDropdown] & "' ));"
.Source = strSQL
.LockType = adLockOptimistic
.CursorType = adOpenKeyset
.Open
End With
Set Me.Recordset = rs
Set rs = Nothing
Set cn = Nothing
End Sub
I have a multi-select listbox which I want to be the source of a sql query with results displayed in a listbox. Currently I have the results going to a recordset which is displayed beautifully when only one 1 field is selected. For instance, if the user selects Gender, no recordset datasheet opens and List20 shows the field name, underscored, with the distinct values below it--Perfect!! When I try to select more than one item things go awry. For instance 2 items selected (Gender, Interface) will result in Gender (underlined) but with 2 F's and 2 M's below it and none of the Interface field values. How do I loop through each selection and have them show in the listbox? Here is my code. Also, weirdly, List13 shows no results when I run the query, but when I take away the line:
Set Me.List13.Recordset = rs
a recordset datasheet opens up and the desired results no longer appear in List20. Please help!
Private Sub Command19_Click()
Dim strSQL As String
Dim strCriteria As String
Dim varItem As Variant
Dim dbs As Database
Set dbs = CurrentDb()
Dim qdf As QueryDef
Dim rs As Recordset
On Error GoTo Err_Command19_Click
For Each varItem In Me!List101.ItemsSelected
strCriteria = strCriteria & ",'" & Me!List101.ItemData(varItem) & "'"
Next varItem
strCriteria = Right(strCriteria, Len(strCriteria) - 1)
strSQL = "SELECT DISTINCT " & strCriteria & " FROM Scrubbed"
strSQL = Replace(strSQL, "'", "")
Set rs = dbs.OpenRecordset(strSQL)
Do Until rs.EOF
Set Me.List20.Recordset = rs
Set Me.List13.Recordset = rs
Loop
With dbs
Set qdf = .CreateQueryDef("TmpDistinctValues", strSQL)
DoCmd.OpenQuery "TmpDistinctValues"
.QueryDefs.Delete "TmpDistinctValues"
End With
dbs.Close
qdf.Close
Exit_Command19_Click:
Exit Sub
Err_Command19_Click:
MsgBox "Please select a field"
End Sub
Surely you mean:
For Each varItem In Me!List101.ItemsSelected
strCriteria = strCriteria & "," & Me!List101.ItemData(varItem)
colcount = colcount + 1
colwidths = colwidths & ";" & "1134"
Next varItem
strCriteria = Right(strCriteria, Len(strCriteria) - 1)
strSQL = "SELECT DISTINCT " & strCriteria & " FROM Scrubbed"
''strSQL = Replace(strSQL, "'", "")
''Set rs = dbs.OpenRecordset(strSQL)
''Do Until rs.EOF
Me.List20.RowSource = strSQL
Me.List20.ColumnCount = colcount
Me.List20.ColumnWidths = Mid(colwidths, 2)
''Set Me.List13.Recordset = rs
''Loop