user8262126
user8262126

Reputation: 3

One Sub for multiple VBA Userform Items

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

Answers (1)

user6432984
user6432984

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. enter image description here

ListboxEventsClass Code

Public WithEvents lBox As MSForms.ListBox

Private Sub lBox_Click()
    MsgBox "You clicked: " & lBox.Name _
    & vbCrLf & "Value: " & lBox.Value
End Sub

Userform Code

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

Related Questions