MS访问 - 多选择列表框中删除表中的记录(MS Access - Multi Select Lis

2019-10-19 16:36发布

我使用的是Access 2010在Windows 8.我一直在寻找一种方式来使用多选择列表框中一次从表中删除几条记录。 我来到翻过这个职位上的StackOverflow它帮助让我开始:

从多选列表框中删除多个选择的记录(访问)

我调整了代码与溶液中的我的表和对象的工作,但由于某种原因,它只是在选择一个记录工作。 如果我选择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宣布只要不是整数的。 它结束了没有用单引号声明周边在逗号好的工作。

这最终的产品:

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

Answer 1:

替换此:

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为长。 你不能这样做,因为龙是一个整数 。 你必须昏暗它作为一个字符串。



文章来源: MS Access - Multi Select Listbox to delete records from table