Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

vba - Assign code to a button created dynamically

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.

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?

Here's the code:

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"
Question&Answers:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Here is an example. Please amend it to suit your needs :)

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

enter image description here enter image description here


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...