我需要删除从 Access 列表框中选择的多条记录。我有 SQL 和 VBA 可以从非多选列表框中删除一条选定的记录,但我似乎无法调整代码以从多选列表框中删除多条选定的记录。这是目前的代码;它附加到按钮 On_Click 事件,列表框称为列表框名称:
Private Sub DeleteSelected_Click()
Dim lngID As Long
Dim strSQL As String
If IsNull(ListBoxName) Then
Exit Sub
End If
With Me.ListBoxName
lngID = ListBoxName.Value
strSQL = "DELETE * FROM [tablename] WHERE [tablefieldname] =" & lngID
CurrentDb.Execute strSQL
ListBoxName.Requery
End With
End Sub
我试过设置
lngID = ListBoxName.Value
至
lngID = ListBoxName.ItemsSelected(0)
或者
lngID = ListBoxName.Columns(0)
无济于事。似乎 SQL 一定有问题,但我不知道如何修复它。有任何想法吗?
编辑:这很酷 :) 干杯 Belial。这是更新的代码
Private Sub DeleteSelected_Click()
Dim strSQL As String
Dim vItem As Variant
Dim strSet As Long
If IsNull(ListBoxName) Then
Exit Sub
End If
With Me.ListBoxName
For Each vItem In .ItemsSelected
If Not IsNull(vItem) Then
strSet = strSet & "," & .ItemData(vItem)
End If
Next
End With
strSQL = "DELETE FROM Carers WHERE Carer_ID IN (" & strSet & ")"
CurrentDb.Execute strSQL
ListBoxName.Requery
End Sub
希望我做对了