为动态创建的按钮分配代码 [英] Assign code to a button created dynamically
问题描述
我正在尝试获取我在 excel 用户表单上动态创建的按钮,以运行我在 Module 1
中编写的名为 transfer
的宏我项目的模块"部分.
I'm trying to get a button I've created dynamically on an excel userform form to run a macro called transfer
which I've written in Module 1
of the "Modules" section of my project.
下面我粘贴了到目前为止我在用户表单中编写的代码,这些代码实际上设法在框架中创建了 Transfer to Sheet
按钮(我也动态创建了它)) 但出于某种原因,当我运行 VBA 时,我收到一条 438 错误
消息,指出 Object 不支持此属性或方法
.
Below I've pasted the code I've written so far in the userform which actually manages to create the Transfer to Sheet
button in the frame (which I've also created dynamically) but for some reason, when I run VBA I get a 438 error
message saying that Object doesn't support this property or method
.
谁能告诉我如何解决这个问题?
Can anybody tell me how I can resolve this?
代码如下:
Dim framecontrol1 As Control
Set workitemframe = Controls.Add("Forms.Frame.1")
With workitemframe
.Width = 400
.Height = 400
.Top = 160
.Left = 2
.ZOrder (1)
.Visible = True
End With
workitemframe.Caption = "Test"
Set framecontrol1 = workitemframe.Controls.Add("Forms.commandbutton.1")
With framecontrol1
.Width = 100
.Top = 70
.Left = 10
.ZOrder (1)
.Visible = True
.Caption = "Transfer to Sheet"
End With
framecontrol1.OnAction = "transfer"
推荐答案
这是一个例子.请修改它以满足您的需要:)
Here is an example. Please amend it to suit your needs :)
此示例将创建一个命令按钮并为其分配代码,以便在按下时显示Hello World".
This example will create a command button and assign code to it so that when it is pressed, it will display "Hello World".
将此代码粘贴到命令按钮的点击事件中,这将动态创建一个新的命令按钮并为其分配代码.
Paste this code in the click event of a command button which will create a new command button dynamically and assign code to it.
Option Explicit
Dim cmdArray() As New Class1
Private Sub CommandButton1_Click()
Dim ctl_Command As Control
Dim i As Long
i = 1
Set ctl_Command = Me.Controls.Add("Forms.CommandButton.1", "CmdXYZ" & i, False)
With ctl_Command
.Left = 100
.Top = 100
.Width = 255
.Caption = "Click Me " & CStr(i)
.Visible = True
End With
ReDim Preserve cmdArray(1 To i)
Set cmdArray(i).CmdEvents = ctl_Command
Set ctl_Command = Nothing
End Sub
并将此代码粘贴到类模块中
and paste this code in a class module
Option Explicit
Public WithEvents CmdEvents As MSForms.CommandButton
Private Sub CmdEvents_Click()
MsgBox "Hello Word"
End Sub
快照
这篇关于为动态创建的按钮分配代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!