一个Sub用于多个VBA Userform项目

时间:2017-07-06 01:30:28

标签: vba function listbox

我正在VBA中编写一个程序,我在Userform中使用多个列表框。是否可以为多个列表框编写一个程序(一个程序来控制Private Sub Listbox1_Click,Private Sub Listbox2_Click和Private Sub Listbox4_Click)

由于

1 个答案:

答案 0 :(得分:2)

您可以创建一个类来处理Listbox事件,并使用类级别数组或集合来保存对Listbox的引用。 enter image description here

ListboxEventsClass代码

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