【发布时间】:2020-12-09 01:42:22
【问题描述】:
这是对我的first question 的跟进:
通过点击事件,我将一些元素(txtBox01 和cmdButton01)动态添加到之前空的(静态)UserForm1。现在我想通过cmdButton01的点击事件来改变文本框的内容。我到底要如何引用cmdButton01?
以下是我创建动态元素的方法(简化!):
Private Sub CommandButton1_Click()
Dim cmdArray() As New Class1
i = 1
'Layout for static Form
'Set Formsize / Formtitle
UserForm1.Height = 130
UserForm1.Width = 300
'Create Form-Elements (TextBox1)
Dim txtBox01 As MSForms.TextBox
Set txtBox01 = UserForm1.Controls.Add("Forms.TextBox.1", "dynTxtBox_01")
txtBox01.Top = 10
txtBox01.Left = 10
txtBox01.Width = 200
txtBox01.Text = "something"
'Create Form-Elements (Commandbutton)
Dim cmdButton01 As MSForms.CommandButton
Set cmdButton01 = UserForm13.Controls.Add("Forms.CommandButton.1", "dynCmdButton01", False)
cmdButton01.Top = 70
cmdButton01.Left = 10
cmdButton01.Width = 200
cmdButton01.Caption = "Save"
cmdButton01.Visible = True
ReDim Preserve cmdArray(1 To i)
Set cmdArray(i).CmdEvents = cmdButton01
Set cmdButton01 = Nothing
'Show Form
UserForm1.Show
End Sub
我通过以下代码为点击事件分配了代码。但我不确定如何引用静态表单上的动态元素。我尝试了一些在网上找到的示例,但没有任何效果:
Public WithEvents CmdEvents As MSForms.CommandButton
Private Sub CmdEvents_Click()
'Simple Test (works fine)
MsgBox "Test1"
'Change the Text of TextBox01 (this one is PSEUDO code to illustrate what I want to do)
UserForm1.txtBox01.Text= "123"
'=> how should I reference the dynamic form element to make this work??
'Close Form
UserForm1.Hide
End Sub
【问题讨论】:
-
可以使用以下语法
UserForm1.Controls("dynTxtBox_01").Text = "123"。 -
@BrianMStafford 工作正常,唯一的问题是我必须使用
Unload UserForm1否则 - 以修改后的形式 - 它仅适用于“第一次通话”。知道这是为什么吗? -
@BrianMStafford 顺便说一句,请随时将其发布为答案...