我正在VBA中编写一个程序,我在Userform中使用多个列表框。是否可以为多个列表框编写一个程序(一个程序来控制Private Sub Listbox1_Click,Private Sub Listbox2_Click和Private Sub Listbox4_Click)
由于
答案 0 :(得分:2)
您可以创建一个类来处理Listbox事件,并使用类级别数组或集合来保存对Listbox的引用。
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