我需要删除从Access中的列表框中选择的多个记录。我有SQL和VBA从非多选列表框中删除一个选定的记录,但我似乎无法调整代码从多选列表框中删除多个选定的记录。这是现在的代码;它附加到按钮On_Click事件,列表框名为listboxname:
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
希望我做对了
答案 0 :(得分:1)
以下是您的查询中的一个SQL错误:
strSQL = "DELETE FROM [tablename] WHERE [tablefieldname] =" & lngID
不需要*
。
无论如何,这是另一种方法:
将选择项添加到由,
逗号分隔的字符串中,然后使用IN
运算符一次删除所有项目。
Dim vItem as Variant
Dim strSet as String
//Loop through the ItemsSelected in the list box
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 [tablename] WHERE [tablefieldname] IN (" & strSet & ")"
答案 1 :(得分:0)
从DELETE语句中删除*。
strSQL = "DELETE FROM [tablename] WHERE [tablefieldname] =" & lngID
迭代选定的项目使用类似
的内容For i = 0 To ListBox1.ListCount - 1
If ListBox1.Selected(i) Then
Msg = Msg & ListBox1.List(i) & vbNewLine
End If
Next i
见
迭代:http://www.java2s.com/Code/VBA-Excel-Access-Word/Forms/GettheselecteditemsinaListBox.htm
删除声明:http://msdn.microsoft.com/en-us/library/office/ff845201(v=office.14).aspx
现在有效吗?
修改强>
我认为没有任何反应,因为在我看来这一切都是正确的(尝试过)。
If IsNull(ListBoxName) Then
Exit Sub
End If
试试这个
Dim strSQL As String
Dim vItem As Variant
With Me.ListBoxName
For Each vItem In .ItemsSelected
If Not IsNull(vItem) And Not CStr(vItem) = vbNullString Then
strSQL = "DELETE FROM Carers WHERE Carer_ID = " & CLng(vItem)
CurrentDb.Execute strSQL
End If
Next
End With
ListBoxName.Requery