进行列表框选择,将值添加到其他列表框,不允许重复

时间:2020-09-01 17:01:25

标签: vba ms-access ms-access-2016 ms-access-forms

我正在制作的表单上有两个列表框。第一个列表框链接到具有各种公司名称的表。我追求的目标是双击公司名称,然后将值插入第二个列表框中。

在我尝试添加代码以防止重复项出现在第二个列表框中之前,它一直运行良好,因此您不会无意间两次插入同一家公司。我尝试了几次不同的迭代,但是没有运气。有人能帮忙吗?我的最终目标是弹出msgbox,警告用户不允许重复。

Private Sub ContractorLstbx_DblClick(Cancel As Integer)
    Dim found As Boolean
    found = False
    Dim ID As Long
    Dim Contractor As String
    
    For Each newItem In Me.ContractorLstbx.ItemsSelected
        For j = 0 To Me.SelectedContractorLst.ListCount - 1
            If (Me!ContractorLstbx.ItemData(newItem).Column(1) = Me.SelectedContractorLst.ItemData(j).Column(1)) Then
                found = True
                Exit For
            End If
        Next j
        If found = False Then
            ID = Me.ContractorLstbx.ItemData(newItem)
            Me.SelectedContractorLst.AddItem ContractorLstbx!.ItemData(newItem).Column(0) & ";" & Me!ContractorLstbx.ItemData(newItem).Column(1)
            
        End If
        found = False
    Next newItem
End Sub

1 个答案:

答案 0 :(得分:2)

这是您的解决方案的完整代码。我在测试样本上尝试过,并且工作正常。只需复制并粘贴代码即可。如果您需要比较时区分大小写(我是说A <> a),请使用Option Compare Binary,如下面的代码所示。如果要求不区分大小写(A = a),则保留默认值Option Compare Database,或者最好使用Option Compare Text

Option Compare Binary

Private Sub ContractorLstbx_DblClick(Cancel As Integer)
    Dim found As Boolean
    found = False
    Dim ID As Long
    Dim Contractor As String

    For i = 0 To Me.ContractorLstbx.ItemsSelected.Count - 1
        For j = 0 To Me.SelectedContractorLst.ListCount - 1
            If (Me.ContractorLstbx.Column(1, Me.ContractorLstbx.ItemsSelected(i)) = Me.SelectedContractorLst.Column(1, j)) Then
                found = True
                Exit For
            End If
        Next j
        If found = False Then
            ID = Me.ContractorLstbx.ItemData(Me.ContractorLstbx.ItemsSelected(i))
            Me.SelectedContractorLst.AddItem (ContractorLstbx.Column(0, Me.ContractorLstbx.ItemsSelected(i)) & ";" & Me.ContractorLstbx.Column(1, Me.ContractorLstbx.ItemsSelected(i)))
        
        End If
        found = False
    Next i
End Sub