在 Excel 中自动添加加载项的单个菜单项

Sof*_*mur 2 excel vba excel-addins

我使用的是 Windows 版 Microsoft Excel 2010。

我已经开发了一个加载项addin.xlam,其中包含一个 sub main. addin.xlam位于正确的位置,以便通过菜单可见和选择Developer -> Add-Ins。当我打开普通工作簿test.xlsm并按 时Alt + F11,我可以看到 的代码addin.xlam已加载。

我的目标是向 Excel 的菜单栏添加一个菜单项,以允许用户main启动add-in.xlam. 通过点击此链接,我的代码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
Run Code Online (Sandbox Code Playgroud)

这段代码很好地放置在ThisWorkbookaddin.xlam,在 中也可见test.xlsm但我在菜单栏中看不到任何变化。

有谁知道会发生什么?

Cha*_*ams 5

仅当使用 Excel 插件管理器“安装”或“卸载”插件时才会触发 AddinInstall 和 AddinUninstall 事件。

恕我直言,这可能会导致问题,因此我始终建议使用 Workbook_Open 和 Workbook_BeforeClose 事件。