1

I am building a Userform which contains two ListBoxes such that the user can select options from ListBox1 and add them to ListBox2 or alternatively remove options from ListBox2

What I am struggling with is how can I prevent the duplicates from being added to the ListBox2? Essentially, I want to build in a function (?) which checks if an option is already included in ListBox2

Private Sub CommandButton3_Click()

'### Adds Items from ListBox1 to ListBox2
For i = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected(i) = True Then ListBox2.AddItem ListBox1.List(i)
Next i

ListBox1.Selected

End Sub

Private Sub CommandButton4_Click()

'### Removes Items from ListBox2
Dim counter As Integer
counter = 0

For i = 0 To ListBox2.ListCount - 1
    If ListBox2.Selected(i - counter) Then
        ListBox2.RemoveItem (i - counter)
        counter = counter + 1
    End If
Next i

End Sub
3
  • Add a check using COntains function Commented Jan 23, 2015 at 11:38
  • Please post a link to your image... Commented Jan 23, 2015 at 12:07
  • Not sure how contains function would work in VBA. However, I have found another similar thread on stackoverflow which solves a similar problem and working to adjust it to my needs: stackoverflow.com/questions/19755920/… Commented Jan 23, 2015 at 13:53

1 Answer 1

1

The code below worked as a solution to the problem:

Private Sub CommandButton3_Click()

For i = 0 To ListBox1.ListCount - 1

    If ListBox1.Selected(i) = True Then
        valCheck (ListBox1.List(i))
    End If

Next i

End Sub

Private Function valCheck(str As String)

'### Adds Items from ListBox1 to ListBox2

Dim valExists As Boolean

    valExists = False


        For i = 0 To ListBox2.ListCount - 1

            If ListBox2.List(i) = str Then
                valExists = True
            End If

        Next i

        If valExists Then
            MsgBox ("already exists")
        Else
            ListBox2.AddItem str
        End If





End Function
Private Sub CommandButton4_Click()

'### Removes Items from ListBox2

For i = 0 To ListBox2.ListCount - 1

    If ListBox2.Selected(i) = True Then ListBox2.RemoveItem (i)

Next i



End Sub
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.