如何以编程方式将工具栏(带有按钮)添加到Excel(2002或更高版本)?
单击按钮时,我想要一个处理程序来创建我的COM对象并在其上调用方法?
这是应该适用于版本但不包括 Excel 2007的东西的基础,Excel 2007具有完全不同的界面.
这可以在你的ThisWorkbook模块中找到:
Private Sub Workbook_BeforeClose(Cancel As Boolean) DeleteCommandBar End Sub Private Sub Workbook_Open() ShowToolbar End Sub
这可以放在同一个模块或单独的模块中,您可以选择,但我更喜欢将它放在自己的模块中,它可以更加明显.你应该不需要一个OnClick,按钮被告知你创建按钮时要调用的例程.
Private Const TOOLBARNAME = "MyFunkyNewToolbar" Public Sub ShowToolbar() ' Assumes toolbar not already loaded ' Application.CommandBars.Add TOOLBARNAME AddButton "Button caption", "This is a tooltip", 526, "NameOfASubInYourVBACode" ' call AddButton more times for more buttons ' With Application.CommandBars(TOOLBARNAME) .Visible = True .Position = msoBarTop End With End Sub Private Sub AddButton(caption As String, tooltip As String, faceId as Long, methodName As String) Dim Btn As CommandBarButton Set Btn = Application.CommandBars(TOOLBARNAME).Controls.Add With Btn .Style = msoButtonIcon .FaceId = faceId ' choose from a world of possible images in Excel: see http://www.ozgrid.com/forum/showthread.php?t=39992 ' .OnAction = methodName .TooltipText = tooltip End With End Sub Public Sub DeleteCommandBar() Application.CommandBars(TOOLBARNAME).Delete End Sub