如何以编程方式将工具栏button(和OnClick处理程序)添加到Excel

如何以编程方式将工具栏(包含button)添加到Excel(2002或更高版本)?

当button被点击时,我想要一个处理程序来创build我的COM对象,并调用它的方法?

这是在应用程序版本的基础上, 但不包括具有完全不同接口的Excel 2007。

这在你的ThisWorkbook模块:

Private Sub Workbook_BeforeClose(Cancel As Boolean) DeleteCommandBar End Sub Private Sub Workbook_Open() ShowToolbar End Sub 

这可以在同一模块或单独的模块中进行select,尽pipe我更喜欢将它放在自己的模块中,使其更加明显。 你不应该需要一个OnClick,当你创buildbutton时,该button被告知要调用什么例程。

 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 

您可以编写一个Excel加载项,用您的button和COM调用代码创build一个工具栏 ,然后将您创build的.xla文件放到用户的XLStart文件夹中 。