问题描述
我创建了一个用户窗体,它显示了表格中的一些值(在文本框中),可以编辑,还有一个命令按钮可以将这些更改保存回表格中.
I created a Userform, that shows a few values from the table (within textboxes) that can be edited and a command button to save those changes back into the table.
因为我对各种值使用相同的模板,所以我决定在运行时动态创建用户表单.但我根本无法让命令按钮工作.我交叉检查了各种示例(在 StackOverflow 和其他网站上,例如 here 和 这里),但我找不到问题.
Since I use the same template for various values I decided to dynamically create the Userform at runtime. But I can't get the command button to work at all. I cross-checked with various examples (on StackOverflow and other sites, e.g. here and here), but I can't find the problem.
这是我的(简化)代码.该过程由按钮单击事件本身调用 (CommandButton1
).作为一种解决方法,我创建了一个静态(空)用户窗体 UserForm1
,我将其用作在运行时动态创建表单的特定配置的起点.从本质上讲,这意味着只有表单元素是动态创建的.至少现在是这样,但这很好,因为我只需要在任何给定时间显示一个表单实例.最后,我也想在运行时创建表单:
This is my (simplified) code. The procedure is being called by a button click event itself (CommandButton1
). As a workaround, I created a static (empty) UserForm UserForm1
which I use as a starting point to create a specific configuration of the form dynamically during runtime. Essentially it means that just the form elements are created dynamically. At least for now, but that's fine since I only need one single instance of the form to be displayed at any given time. Eventually, I would like to create the form at runtime too:
Private Sub CommandButton1_Click()
'Set Form
UserForm1.Caption = "Test"
'Create Form-Elements (Commandbutton)
Dim cmdButton01 As MSForms.CommandButton
Set cmdButton01 = UserForm1.Controls.Add("Forms.CommandButton.1", "dynCmdButton01")
cmdButton01.Width = 50
cmdButton01.Caption = "Save"
'Show Form
UserForm1.Show
End Sub
Private Sub dynCmdButton01_click()
MsgBox "Test"
End Sub
推荐答案
您应该创建一个类模块并通过它分配事件:
You should create a class module and assign the event through it:
这篇关于在运行时通过 VBA 创建动态按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!