Search code examples
vbams-accessms-access-2016ms-access-forms

Take list box selection, add value to other list box without allowing duplicates


I have two list boxes on a form I am making. The first list box is linked to a table with various company names. The goal I am after is after double clicking a companies name, the value is inserted in the second list box.

It worked fine until I tried to add code to prevent duplicates from appearing in the second list box, so you couldn't accidentally insert the same company twice. I have tried several different iterations, but with no luck. Anyone able to help with this one? My end goal would be for a msgbox to pop up alerting the user that duplicates are not allowed.

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

Solution

  • This is the full code for your solution. I tried it on test sample and working fine. just copy and paste the code. If you need your comparison to be case sensitive (I mean A <> a) then use Option Compare Binary as in my code below. If it is required to be case insensitive (A = a) just leave the default Option Compare Database or better force it using 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