为多个动态控件创建事件处理程序

时间:2014-08-19 13:25:29

标签: vba excel-vba excel

我有一个用户窗体,它创建了两个动态控制按钮,但我无法访问动态控件的.name属性,这意味着我无法正确创建事件处理程序。由于这个问题,我无法创建事件处理程序。下面显示了创建动态控件的代码以及我为事件处理程序编写的代码(无法正常运行)

Option Explicit

Public WithEvents cButton As MSForms.CommandButton


Private Sub TextBox1_Change()
  If TextBox1 <> vbNullString Then
     For i = 1 To TextBox1.Value        
        Set cButton = Me.Controls.Add("Forms.CommandButton.1")
        With cButton
            .Name = "CommandButton" & i
            .Left = 150
            .Top = buttonStartPosition
            .Width = 300
            .Height = 140
        End With
     Next i
   End If
End sub

 Private Sub cButton_Click()
    If cButton.Name = "CommandButton1" Then
      MsgBox "Button1"
    ElseIf cButton.Name = "CommandButton2" Then
      MsgBox "Button2"
    End If
 End Sub

执行此代码并且屏幕上有两个按钮后,我按下第一个按钮(button1),没有任何反应,但是当我按下第二个按钮(button2)时,我收到了消息“Button2的”。那么为什么我无法访问第一个按钮?

2 个答案:

答案 0 :(得分:1)

@ user3538102 ..您对Textbox的评论。下面是一个例子。我添加了组合框,选择CommandButton或TextBox并生成事件。代码有效但可能更好。

我添加了组合框以选择动态生成对象类型。

Combo Box

在UserForm中激活事件 - 添加组合下拉列表

Private Sub UserForm_Activate()
    ComboBox1.AddItem "CommandButton"
    ComboBox1.AddItem "TextBox"
    ComboBox1.ListIndex = 0
End Sub

在Class1 Class Module ..

ClassModule

修改了UserForm代码..

Option Explicit

Dim cObjs() As New Class1

Private Sub TextBox1_Change()
Dim i As Integer
Dim buttonStartPosition As Integer
Dim cObj As Object

buttonStartPosition = 30

If TextBox1 <> vbNullString Then
 For i = 1 To TextBox1.Value
    If ComboBox1.Value = "CommandButton" Then
        Set cObj = Me.Controls.Add("Forms.CommandButton.1")
    Else
        Set cObj = Me.Controls.Add("Forms.TextBox.1")
    End If

        With cObj
            .Name = ComboBox1.Value & i
            .Left = 15
            .Top = buttonStartPosition
            .Width = 30
            .Height = 14
        End With

    ReDim Preserve cObjs(1 To i)
    If ComboBox1.Value = "CommandButton" Then
        Set cObjs(i).ButtonGroup = cObj
    Else
        Set cObjs(i).TextGroup = cObj
    End If

    buttonStartPosition = buttonStartPosition + 14

 Next i
End If

End Sub

答案 1 :(得分:0)

我获得了多个按钮的事件,可以使用来自... JWalk Excel Tips

的帮助

以下是根据您的代码和提供的链接进行的修改。

创建一个名为“Class1”的类模块

Class1 Module

将修改后的代码添加到UserForm1 ..

Option Explicit

Dim Buttons() As New Class1

Private Sub TextBox1_Change()
Dim i As Integer
Dim buttonStartPosition As Integer
Dim cButton As CommandButton

buttonStartPosition = 30

If TextBox1 <> vbNullString Then
 For i = 1 To TextBox1.Value
    Set cButton = Me.Controls.Add("Forms.CommandButton.1")
    With cButton
        .Name = "CommandButton" & i
        .Left = 15
        .Top = buttonStartPosition
        .Width = 30
        .Height = 14
    End With

    ReDim Preserve Buttons(1 To i)
    Set Buttons(i).ButtonGroup = cButton

    buttonStartPosition = buttonStartPosition + 14

 Next i
End If

End Sub