PDA

View Full Version : [SOLVED:] Selecting List Box Items When Index Unknown



GenuineGin
01-09-2015, 03:53 PM
Hello,

I have a userform with a number of check boxes and a list box.

What I'm trying to achieve:

1) Click any selection of check boxes

2) Click a command button ("cmdRefresh")

3) Items are added to the list box to be displayed as a summary of what has been selected.

4) If a check box is unchecked, when the command button is pressed again the related list box entry is removed.

My issue is that there could be any number of entries in any order, so I don't know how I would reference specific list box items.

The order that the items are added to the list box can be fixed (i.e. they don't need to show in the order that they were clicked).

Is there a way to assign a 'permanent' index to list box items based on the check box clicked, regardless of how many are added to the list box or the order they are added? If not, how can I select them?

Many thanks

gmaxey
01-09-2015, 04:23 PM
It would probably be easier just to clear the listbox and repopulate it.


Private Sub CommandButton1_Click()
Dim oCtr As Control
Me.ListBox1.Clear
For Each oCtr In Me.Controls
If TypeName(oCtr) = "CheckBox" Then
If oCtr.Value = True Then Me.ListBox1.AddItem oCtr.Caption
End If
Next
End Sub

GenuineGin
01-10-2015, 05:36 AM
Ah! So simple and works perfectly! Thank you!

Sometimes I get so wrapped in trying to fix the code I forget to consider fixing my approach!

I also wanted to say a general thank you to you. Your website was the first and is still the most useful resource I've found for someone learning VBA from scratch and your answers to other people's queries have resolved almost all of my issues.

gmaxey
01-10-2015, 07:13 AM
Glad I could help and thanks for your approbation. To be thorough, I suppose if order checked were important, then something like this might do:


Private Sub CheckBox1_Click()
ProcessClicks "CheckBox1", "Red", 1
End Sub

Private Sub CheckBox2_Click()
ProcessClicks "CheckBox2", "Blue", 2
End Sub
Private Sub CheckBox3_Click()
ProcessClicks "CheckBox3", "Green", 3
End Sub
Private Sub CheckBox4_Click()
ProcessClicks "CheckBox4", "Orange", 4
End Sub
Private Sub CheckBox5_Click()
ProcessClicks "CheckBox5", "Purple", 5
End Sub
Sub ProcessClicks(strName As String, strValue As String, x As Long)
Dim lngIndex As Long
With ListBox1
'.ColumnCount = 2
'.ColumnWidths = "50;0"
If Me.Controls(strName).Value = True Then
.AddItem
.List(.ListCount - 1, 0) = strValue
.List(.ListCount - 1, 1) = x
Else
For lngIndex = .ListCount - 1 To 0 Step -1
If .List(lngIndex, 1) = x Then
.RemoveItem (lngIndex)
End If
Next
End If
End With
End Sub