List Box item transfer

Some applications require a user to select several items from a list. It's often useful to create a new list of the selected items and display the new list in another ListBox. For an example of this situation, check out the Customization tab of the Excel Options dialog box.

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 Delete 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 is not marked, a message box appears if the user attempts to add an item that's already on the list.

A

£

C □

E

F

G

M

llvPoii TiJiiMltf Ocmo

y

3

fr«

SsM

5

gl»

]ruïv

Lfcsr* I

Hfi"

s

Ma,

J

ät-fvt

«

5

Z.

i

in

"

UMdOUlF

13

Li

14

15

shiwtl

>

Figure 14-12: Building a list from another 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 Ad button:

Private Sub AddButton_Click()

If ListBoxl.ListIndex = -1 Then Exit Sub If Not cbDuplicates Then ' See if item already exists

For i = 0 To ListBox2.ListCount - 1

If ListBoxl.Value = ListBox2.List(i) Then Beep

Exit Sub End If Next i End If

ListBox2.AddItem ListBoxl.Value End Sub

The code for the Remove button is even simpler:

Private Sub RemoveButton_Click()

If ListBox2.ListIndex = -1 Then Exit Sub ListBox2.RemoveItem ListBox2.ListIndex End 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.

This example has two additional procedures that control whether the Remove button is enabled or disabled. These events are triggered when the ListBox is entered (either via a keystroke or a mouse click). The net effec is that the Remove button is enabled only when the user is working in ListBox2 .

Private Sub ListBox1_Enter()

RemoveButton.Enabled = False End Sub

Private Sub ListBox2_Enter()

RemoveButton.Enabled = True End Sub

CD-ROM

This example, named ■■*■ listbox item transfer.xlsm , is available on the companion CD-ROM.

0 0

Post a comment