Excel VB 点击按钮在现有的Userform上创建一个按钮并保存新增的按钮的代码在VBA内
时间: 2024-06-06 10:11:29 浏览: 250
EXCEL按钮制作
可以使用以下代码来实现:
Private Sub CommandButton1_Click()
Dim newBtn As MSForms.CommandButton
Set newBtn = Me.Controls.Add("Forms.CommandButton.1", "DynamicBtn")
newBtn.Left = 100
newBtn.Top = 50
newBtn.Caption = "Dynamic Button"
'将新增的按钮的代码保存在VBA内
Dim btnCode As String
btnCode = "Private Sub DynamicBtn_Click()" & vbCrLf
btnCode = btnCode & " MsgBox ""You clicked the dynamic button!""" & vbCrLf
btnCode = btnCode & "End Sub" & vbCrLf
ThisWorkbook.VBProject.VBComponents("UserForm1").CodeModule.AddFromString btnCode
End Sub
这段代码在用户窗体上创建一个名为"DynamicBtn"的按钮,并将相应的代码保存在VBA内。此外,您也可以根据需要更改按钮的位置和标题。
阅读全文