我使用的是Microsoft Excel 2010 for Windows。
我已经在addin.xlam
中开发了一个插件,其中包含一个子main
。CCD_ 3位于正确的位置,因此可以通过菜单CCD_。当我打开一个普通的工作簿test.xlsm
,按Alt + F11
时,我可以看到addin.xlam
的代码已经加载。
我的目标是在Excel的菜单栏中添加一个菜单项,允许用户启动add-in.xlam
的main
。按照这个链接,我在addin.xlam
中的代码如下:
Option Explicit
Dim cControl As CommandBarButtonPrivate
Sub Workbook_AddinInstall()
On Error Resume Next 'Just in case
'Delete any existing menu item that may have been left.
Application.CommandBars("Worksheet Menu Bar").Controls("Super Code").Delete
'Add the new menu item and Set a CommandBarButton Variable to it
Set cControl = Application.CommandBars("Worksheet Menu Bar").Controls.Add
'Work with the Variable
With cControl
.Caption = "Super Code"
.Style = msoButtonCaption
.OnAction = "main" 'Macro stored in a Standard Module
End With
On Error GoTo 0
End Sub
Private Sub Workbook_AddinUninstall()
On Error Resume Next 'In case it has already gone.
Application.CommandBars("Worksheet Menu Bar").Controls("Super Code").Delete
On Error GoTo 0
End Sub
该代码很好地放置在addin.xlam
的ThisWorkbook
中,在test.xlsm
中也可见但是我看不到菜单栏有什么变化
有人知道会发生什么吗?
只有当使用Excel加载项管理器"安装"或"卸载"加载项时,才会触发加载项安装和加载项卸载事件。
IMHO这可能会导致问题,所以我总是建议使用Workbook_Open和Workbook_BeforClose事件。
Charles是对的,您需要用Workbook_Open()
替换Workbook_AddinInstall()
,用Workbook_BeforeClose()
替换Workbook_AddinUninstall()
。
此外,您需要CommandBarButton
而不是CommandBarButtonPrivate
。
祝你好运!