Reputation: 31
I have a form that I'm using to gather information that will be inserted into a database table in Access 2016. My form has a multi-value combo box (called cmbContacts) that pulls values from a Contacts table (ID and Name). A user is able to select 0 or more contacts from the combo box. When a user clicks the submit button, the button_click event triggers VBA code to format the information and insert it into the table.
What I need to do is get the IDs of each selected contact from the combo box.
Here's what I have so far:
If Me.cmbContacts.ItemsSelected.Count > 0 Then 'Only run code if there are contacts selected'
'Select the most recently added entry (added right before this if statement)'
Dim rs As DAO.Recordset, Max As Integer
SQL = "SELECT MAX(ID) FROM Breweries"
Set rs = CurrentDb.OpenRecordset(SQL)
Max = rs.Fields(0)
'Insert each selected Contact ID into Breweries.[Contact Names].Value'
Dim itm As Variant
For Each itm In Me.cmbContacts.ItemsSelected
SQL = "INSERT INTO Breweries ([Contact Names].[Value]) VALUES (" + itm + ") WHERE ID=" + Max
CurrentDb.Execute (SQL)
Next itm
End If
Some issues:
Upvotes: 2
Views: 3928
Reputation: 65
After a lot of searching on MVF's and VBA all I found was working with parent/child recordsource. In my case the user has selected the values but they are not saved to the table yet. I just needed a way to loop through the control and get all the values selected. Couldn't find this anywhere - in case it's helpful to someone.
For Each Val in me.MultiValueComboBoxName.Value
'Do Action
Next
Upvotes: 1
Reputation: 1570
If a combobox has more than 1 item selected/populated, then you can use Ubound() to find out how many.
IF UBound(Me.cmbContacts.OldValue) > 0
For i = LBound(Me.cmbContacts.OldValue) To UBound(Me.cmbContacts.OldValue)
SQL = "INSERT INTO Breweries ([Contact Names].[Value]) VALUES (" + Me.cmbContacts.OldValue(i) + ") WHERE ID=" + Max
CurrentDb.Execute (SQL)
Next i
END IF
Bear in mind this will error with a Type Mismatch if only one, or no values are selected and you will have to handle this somehow.
Hope this helps..
Upvotes: 1