我有一个宏代码,它将根据工作簿中工作表中称为“公司代码”的sheet2中的数据在用户窗体中创建按钮(这是使用循环功能完成的动态按钮)。现在的问题是我例如,无法将事件分配给此新创建的按钮,一旦运行了名为1,2,3,4,5的宏5按钮,就会在用户窗体中创建,现在我需要向Button1添加一些操作,以便在单击时应在其上执行操作项。
下面是我用来创建按钮的代码。请帮助我提供有助于将任务分配给按钮的代码。
Option Explicit
Public Form As UserForm1
Public myform As UserForm, fraMain As MSForms.Frame
Public WithEvents Cancel2 As MSForms.CommandButton
Private Sub UserForm_Initialize()
With Me
.Width = 500
.Height = 500
End With
Dim NewBtn As Control, Cancel As Control
Dim Code As String
Dim NextLine, LeftPos, lastrow, Gap, i As Long, r As Long, c As Variant
Dim pt As Point
lastrow = Sheets("Company code").Cells(Rows.Count, 2).End(xlUp).Row
LeftPos = 30
NextLine = 100
Gap = 15
r = 7
i = 1
Set Cancel2 = Controls.Add("Forms.CommandButton.1")
With Cancel2
.Top = 400
.Left = 190
.Width = 130
.Height = 30
.Caption = "Cancel"
.Visible = True
.Font.Size = 10
.Font.Name = "Times New Roman"
End With
Do While i <= lastrow
Do While i <= r
Set NewBtn = Controls.Add("Forms.CommandButton.1")
With NewBtn
.Left = LeftPos
.Top = NextLine
.Width = 45
.Height = 20
.Name = Sheets("Company code").Cells(i + 1, 2)
.Caption = Sheets("Company code").Cells(i + 1, 2)
c = Sheets("Company code").Cells(i + 1, 2)
If Len(c) = 0 Then
NewBtn.Visible = False
Else
NewBtn.Visible = True
End If
.Font.Size = 10
.Font.Name = "Times New Roman"
End With
LeftPos = LeftPos + NewBtn.Width + Gap
i = i + 1
Loop
NextLine = NextLine + 30
LeftPos = 30
r = r + 7
Loop
End Sub
Private Sub Cancel2_click()
UserForm2.Hide
UserForm1.Hide
End Sub