Microsoft Office Tutorials and References
In Depth Information
Figure 14-12 shows a dialog box with two ListBoxes. The Add button adds the item selected in
the left ListBox to the right ListBox. The Remove button removes the selected item from the list
on the right. A check box determines the behavior when a duplicate item is added to the list:
Namely, if the Allow Duplicates check box isn’t marked, a message box appears if the user
attempts to add an item that’s already on the list.
Figure 14-12: Building a list from another list.
The code for this example is relatively simple. Here’s the procedure that is executed when the
user clicks the Add button:
Private Sub AddButton_Click()
If ListBox1.ListIndex = -1 Then Exit Sub
If Not cbDuplicates Then
‘ See if item already exists
For i = 0 To ListBox2.ListCount - 1
If ListBox1.Value = ListBox2.List(i) Then
The code for the Remove button is even simpler:
Private Sub RemoveButton_Click()
If ListBox2.ListIndex = -1 Then Exit Sub
Notice that both of these routines check to make sure that an item is actually selected. If the
ListBox’s ListIndex property is –1 , no items are selected, and the procedure ends.