MS Access - 多选列表框以从表中删除记录

时间:2014-03-28 17:30:34

标签: vba ms-access listbox multi-select

我在Windows 8上使用Access 2010.我一直在寻找一种方法来使用多选列表框一次从表中删除多个记录。我在StackOverflow上发表了这篇文章,它帮助我开始了:

Delete multiple selected record from a multiselect listbox (Access)

我调整了解决方案中的代码以使用我的表和对象,但由于某种原因,它仅在选择一个记录时才有效。如果我选择2个或更多记录,则没有任何反应。任何人都可以看看并帮助我看看我可能犯了什么错误吗?

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

编辑:

感谢你的帮助,我最终得到它的工作,我认为主要问题是strSet被声明为long而不是interger。它最终正常工作,没有用带引号括起来的with语句中的逗号。

这是最终产品:

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

1 个答案:

答案 0 :(得分:2)

替换它:

With Me.lstOperationProducts
    For Each vItem In .ItemsSelected
        If Not IsNull(vItem) Then
            strSet = strSet & "," & .ItemData(vItem)
        End If
    Next
End With

使用:

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)

另外,请记住,如果相关项目是文本,则需要用单引号括起来。所以这一行:

            strSet = strSet & "," & .ItemData(vItem)

将是:

            strSet = strSet & "','" & .ItemData(vItem)

最后一行需要更改为:

strSet = Mid(Trim(strSet), 3, Len(strSet) - 2) & "'"

编辑:我刚看到你也将变量 strSet 定为LONG。你不能这样做,因为LONG is an Integer。你必须把它变成一个字符串。