I am using Access 2010 on Windows 8. I was looking for a way to use a multi select listbox to delete several records from a table at once. I came accross this post on StackOverflow and it helped get me started:
Delete multiple selected record from a multiselect listbox (Access)
I adjusted the code in the solution to work with my tables and objects but for some reason it only works when one record is selected. If I select 2 or more records then nothing happens. Can anyone take a look and help help me see where I might have made a mistake?
Private Sub cmdRemoveProducts_Click()
Dim strSQL As String
Dim vItem As Variant
Dim strSet As Long
'If IsNull(lstOperationProducts) Then
'Exit Sub
'End If
With Me.lstOperationProducts
For Each vItem In .ItemsSelected
If Not IsNull(vItem) Then
strSet = strSet & "," & .ItemData(vItem)
End If
Next
End With
strSQL = "DELETE FROM tblOperationProductMM WHERE OpProdID IN (" & strSet & ")"
CurrentDb.Execute strSQL
lstProducts.Requery
lstOperationProducts.Requery
End Sub
EDIT:
Thanks for all your help, I ended up getting it to work, I think that the main problem was that strSet was declared as long instead of interger. It ended up working ok without surrounding the comma in the with statement with single quotes.
This the final product:
Private Sub cmdRemoveProducts_Click()
Dim strSQL As String
Dim vItem As Variant
Dim strSet As String
Dim i As Long
'If IsNull(lstOperationProducts) Then
'Exit Sub
'End If
strSet = ""
With Me.lstOperationProducts
For Each vItem In .ItemsSelected
If Not IsNull(vItem) Then
strSet = strSet & "," & .ItemData(vItem)
End If
Next
End With
' Remove the first comma
strSet = Mid(Trim(strSet), 2, Len(strSet) - 1)
strSQL = "DELETE FROM tblOperationProductMM WHERE OpProdID IN (" & strSet & ")"
CurrentDb.Execute strSQL
For i = 0 To lstProducts.ListCount - 1
lstProducts.Selected(i) = False
Next
For i = 0 To lstOperationProducts.ListCount - 1
lstOperationProducts.Selected(i) = False
Next
lstProducts.Requery
lstOperationProducts.Requery