I will preface this question by saying I am new to Access VBA though I am quite experienced with Excel VBA.
I have added a listbox to the main form. The user can select multiple names from the list box. I have a sub that forms a comma delimited string of the selection(s) and saves directly to a table to which the form is bound. I call this sub when the form is closed and unloaded and it works just fine (code is listed below).
The problem is that if the user clicks for the next record instead of closing the form, the value is not saved to the table. I have tried adding a call to the save sub from the listbox's AfterUpdate event (and several other listbox events) but it doesn't work properly. The field in the table is empty instead of containing the selected values. Also, I get "Write Error Another user has modified the record...", I assume that is because a second attempt is being made to save the selection because I am calling the save sub too many times. How can I make this work? Thanks.
Code:
Public Sub SaveSelectedResponsibility()
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim varItem As Variant
Dim strCriteria As String
Dim strSQL As String
Set db = CurrentDb() 'set a pointer to the database
Set qdf = db.QueryDefs("qryMultiSelect") 'set a pointer to the query
For Each varItem In Me!LBResponsibility.ItemsSelected 'loop on all selected items
strCriteria = strCriteria & "," & Me!LBResponsibility.ItemData(varItem) 'build a string of all the selected entries
Next varItem
If Len(strCriteria) = 0 Then Exit Sub 'check to see that at least one entry was selected
strCriteria = Right(strCriteria, Len(strCriteria) - 1) 'strip off the leading comma
strCriteria = "'" & strCriteria & "'" 'enclose the string of names with single quotes for SQL
strSQL = "Update tblActionItems set Responsibility=" & strCriteria & " where ActionItemID=" & Me!ActionItemID.Value 'build the SQL string
qdf.SQL = strSQL 'update the query with the SQL
DoCmd.SetWarnings False 'turn off the warnings so no popups confirming the actions appear
DoCmd.OpenQuery "qryMultiSelect" 'execute the update command
DoCmd.SetWarnings True 'turn warnings back on
Set db = Nothing 'delete the db object
Set qdf = Nothing 'delete the qdf object
End Sub