Excel VBA 在工作表(Worksheet)中動態新增按鈕控制元件並新增事件的示例
Sub MakeButton()
'自動新增一個Sheet
'動態生成一個按鈕控制元件
'動態生成事件
'
Dim WSheet As Worksheet
Dim MyNewbtn As OLEObject
Dim Target As Range
Dim ShtCodeName As String
Set WSheet = Worksheets.Add(After:=ActiveSheet)
'WSheet.Name = "新表"
Set Target = Cells(15, 7)
'
Set MyNewbtn = WSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", Link:=False _
, DisplayAsIcon:=False, Left:=Target.Left, Top:=Target.Top, Width:=92.25, Height:= _
30)
MyNewbtn.Name = "MyNewButton" '設定按鈕名
MyNewbtn.Object.Caption = "我的按鈕" '設定按鈕標題
ShtCodeName = WSheet.CodeName
'也可以是
'ShtCodeName = ThisWorkbook.Worksheets("新表").CodeName
'
'向新表中新增事件
'注意:
'1、新增事情的程式名一定要與新增的按鈕名稱對應
'2、如果出現"不信任到Visual Basic Project 的程式連線"的錯誤,解決方法為:
' 開啟Excel-》工具-》巨集-》安全性-》可靠發行商,選中“信任對於Visiual Basic 專案的訪問”,按確定即可。
With ThisWorkbook.VBProject.VBComponents.Item(ShtCodeName).CodeModule
.InsertLines 1, "Private Sub MyNewButton_Click()"
.InsertLines 2, "msgbox ""生成事件成功"""
.InsertLines 3, "'這是一個註釋示例"
.InsertLines 5, "End Sub"
End With
End Sub