1

我需要删除从 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

希望我做对了

4

2 回答 2

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 & ")"
于 2013-02-27T09:32:21.543 回答
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
于 2013-02-27T09:30:47.157 回答