我有一个创建两个动态控制按钮的用户窗体,但我很难访问.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”。那么为什么我无法访问第一个按钮呢?
@user3538102 ..对于您关于文本框的评论。下面是一个例子。我添加了组合框选择 CommandButton 或 TextBox 并生成事件。该代码可以工作,但还可以更好。
我添加了组合框来选择动态生成对象类型。
在用户窗体激活事件中 - 添加组合下拉列表
Private Sub UserForm_Activate()
ComboBox1.AddItem "CommandButton"
ComboBox1.AddItem "TextBox"
ComboBox1.ListIndex = 0
End Sub
在 Class1 类模块中..
修改后的用户窗体代码..
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)