vba - Excel VBA 组合框识别

标签 vba excel combobox

我的用户表单上有 4 个以上的组合框。当他们触发时,他们触发相同的事件。我想做的是找出哪个 ComboBox 触发了该事件。组合框的创建取决于组件的数量。生成组合框的代码如下所示:

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

这效果很好,我可以获取用户选择的值,但我找不到使用了哪个 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

上面的这段代码由 Doug Glancy 精心编写,以使事件与代码生成的 ComboBox 一起工作。

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

最佳答案

在搜索了 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

希望这个可以给其他有需要的人使用。

关于vba - Excel VBA 组合框识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15567989/

相关文章:

java - 无法在Android中使用apache poi解密excel文件

html - 如何将下标应用于 html 组合框中的字母

css - 如何更改组合框下拉按钮的对齐方式?

excel - 我如何知道我单击的已分配宏的图像的名称

excel - 如何编写取消按钮以不清除表单?

java - Java 中的 Excel 文件导出

winforms - 如何滚动以在 Windows 窗体应用程序的触摸屏上工作?

vba - Excel 365 公式 - 如何永久保存 LAMBDA 函数(对于所有现有文件和新文件)?

excel - 引用相对于 ActiveX 命令按钮 VBA 的单元格

VBA打印和写入命令混淆