Excel VBA组合框识别

NoL*_*r92 8 excel vba combobox excel-vba

我在用户表单上有4个以上的ComboBox.当他们开火时,他们会开火.我想要做的是找出哪个ComboBox触发了该事件.组合框是根据有多少组件创建的.生成ComboBoxes的代码如下所示:

For j = 0 To UBound(ComponentList) - 1
'Set Label
num = j + 1
Set control = UserForm1.Controls.Add("Forms.Label.1", "ComponentLabel" & CStr(num) & ":", True)
With control
    .Caption = "Component " & CStr(num)
    .Left = 30
    .Top = Height
    .Height = 20
    .Width = 100
    .Visible = True
End With
'set ComboBox
Set combo = UserForm1.Controls.Add("Forms.ComboBox.1", "Component" & num & ":", True)
With combo
    .List = ComponentList()
    .Left = 150
    .Top = Height
    .Height = 20
    .Width = 50
    .Visible = True
    Set cButton = New clsButton
    Set cButton.combobox = combo
    coll.Add cButton
End With
Height = Height + 30
Next j
Run Code Online (Sandbox Code Playgroud)

这很好用,我可以得到用户选择的值,但我找不到使用的ComboBox.下面的代码是它触发的事件(clsButton):

Public WithEvents btn As MSForms.CommandButton
Public WithEvents combobox As MSForms.combobox
Private combolist() As String

Private Sub btn_Click()
    If btn.Caption = "Cancel" Then
        MsgBox "Cancel"
        Unload UserForm1
        Variables.ComponentSelectionError = False
    ElseIf btn.Caption = "Enter" Then
        MsgBox "enter"
        Unload UserForm1
        Variables.ComponentSelectionError = True
    End If
End Sub

Private Sub combobox_Click()
    MsgBox combobox.Value
End Sub
Run Code Online (Sandbox Code Playgroud)

上面的这段代码由Doug Glancy友好地处理,以使事件与代码生成的ComboBox一起使用.

如何获取触发事件的ComboBox?即名称或其他形式的身份证明.

NoL*_*r92 5

搜索了超过500个网页后,我终于回答了自己的问题(花了很长时间)

这是我使用的,当点击某些组合框时它可以工作和触发:

Private Sub combobox_Click()
MsgBox combobox.Value
If combobox = UserForm1.Controls("Component0") Then
    MsgBox "Success1"
End If
If combobox = UserForm1.Controls("Component1") Then
    MsgBox "Success2"
End If
End Sub
Run Code Online (Sandbox Code Playgroud)

希望这可以用于其他需要它的人.


Ale*_* K. 4

该类内.Name不会出现在组合框的智能感知列表中,因为MSForms.ComboBox它本身实际上没有名称属性(在 F2 对象浏览器中查看它),而是由基Control类提供该属性:

Private Sub combobox_Click()

    MsgBox combobox.Value
    MsgBox combobox.Name '// no hint but still works

    '//cast to a Control to get the formal control interface with .Name
    Dim ctrl As Control: Set ctrl = combobox
    MsgBox ctrl.Name

End Sub
Run Code Online (Sandbox Code Playgroud)