1
我想这样做或多或少笔者在这里意:生成具有预先分配的代码工作表按钮
http://ccm.net/faq/1105-adding-a-vba-commandbutton-with-its-respective-the-code
遗憾的是,尽管该代码被写入正确的表在Microsoft Excel对象,一旦按下按钮,代码就不会运行。该_Click()
是在这里:
Sub ButtonTest_Click()
MsgBox "I am supposed to work!" 'but i dont, i actually do nothing
End Sub
和代码的其余部分如下:
Sub CreateButton()
Dim Obj As Object
Dim Code As String
Sheets("Sheet1").Select
'create button
Set Obj = ActiveSheet.OLEObjects.Add(ClassType:="Forms.CommandButton.1", _
Link:=False, DisplayAsIcon:=False, Left:=200, Top:=100, Width:=100, Height:=35)
Obj.Name = "TestButton"
'buttonn text
ActiveSheet.OLEObjects(1).Object.Caption = "Test Button"
'macro text
Code = "Sub ButtonTest_Click()" & vbCrLf
Code = Code & "Msgbox ""I am supposed to work!""" & vbCrLf
Code = Code & "End Sub"
'add macro at the end of the sheet module
With ActiveWorkbook.VBProject.VBComponents(ActiveSheet.Name).CodeModule
.insertlines .CountOfLines + 1, Code
end With
End Sub
什么也不会发生当按钮pressed-在我看来,它看起来像它应该触发预期事件作为作家,任何想法为什么没有?
'TestButton'和'ButtonTest_Click'不匹配。重命名按钮或过程,然后重试。 – Mikegrann
将'Obj.Name =“TestButton”'更改为'Obj.Name =“ButtonTest”'。按钮的名称和子组的名称必须与ActiveX组件一致。 – Ralph
不能相信我错过了,添加一个答案麦克和大绿色的蜱是你的。 – User632716