将代码分配给动态创建的按钮 [英] Assign code to a button created dynamically

查看:101
本文介绍了将代码分配给动态创建的按钮的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获得一个动态创建的excel用户窗体的按钮,以运行一个名为 transfer 的宏,这个宏写在模块1 我的项目模块部分。

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.

下面我已经粘贴了我写的代码到目前为止实际上管理的用户形式在框架(动态动态创建)中创建转移到工作表按钮,但由于某些原因,我运行VBA我得到一个 438错误消息说,对象不支持此属性或方法

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

SNAPSHOT


这篇关于将代码分配给动态创建的按钮的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆