Reputation: 3
I am writing a program in VBA where I use multiple listboxes in a Userform. Is it possible to write one program for more than one listbox (a single program to control Private Sub Listbox1_Click, Private Sub Listbox2_Click, and Private Sub Listbox4_Click)
Thanks
Upvotes: 0
Views: 918
Reputation:
You can create a class to handle the Listbox Events and use a class level array or collection to hold references to the Listboxes.
Public WithEvents lBox As MSForms.ListBox
Private Sub lBox_Click()
MsgBox "You clicked: " & lBox.Name _
& vbCrLf & "Value: " & lBox.Value
End Sub
Private lBoxes(3) As ListboxEventsClass
Private Sub UserForm_Initialize()
Set lBoxes(0) = New ListboxEventsClass
Set lBoxes(1) = New ListboxEventsClass
Set lBoxes(2) = New ListboxEventsClass
Set lBoxes(0).lBox = ListBox1
Set lBoxes(1).lBox = ListBox2
Set lBoxes(2).lBox = ListBox3
ListBox1.List = Array("Red", "White", "Blue")
ListBox2.List = Array("Dog", "Cat", "Horse")
ListBox3.List = Array("VBA", "Java", "C++")
End Sub
Upvotes: 2