首页 > 解决方案 > Excel CustomUI 按钮链接

问题描述

好的,我知道这是一个持续存在的问题,我似乎到处寻找答案。如果我不知何故错过了这里的答案,我深表歉意,所以如果你知道一个,请指教!

我使用“CustomUI 编辑器”在 Excel 中创建了一个自定义功能区。我的宏目前仅从工作表上的按钮直接运行,而不是在 UI 上。我读到这是因为原始文件的链接。所以我创建了一个新的新工作簿,创建新宏(未导入),创建自定义 UI 按钮,并将宏链接到新按钮。按钮仍然给我错误,即宏无法运行并且可能不可用。我在这里可能缺少什么?我还读到它可以创建一个宏来在打开工作簿时更新链接。有人成功了吗?我希望在功能区上有按钮并将它们从我的工作表中删除!感谢您提供的任何帮助你可以提供!

标签: excelvbauser-interfaceribbonx

解决方案


您可以使用以下子添加自定义菜单项。只需将 .OnAction 值替换为您希望控件运行的宏的名称。

Sub AddCustomMenu()
    Dim cbMainMenuBar As CommandBar
    Dim iHelpMenu As Integer
    Dim cbcCutomMenu As CommandBarControl

    'Delete the menu item if it already exists. Use On Error Resume Next in case it doesn't exist.
    On Error Resume Next
    Application.CommandBars("Worksheet Menu Bar").Controls("&My Tools").Delete
    On Error GoTo 0

    Set cbMainMenuBar = Application.CommandBars("Worksheet Menu Bar")   'Set a CommandBar variable to Worksheet menu bar

    iHelpMenu = cbMainMenuBar.Controls("Help").Index    'Return the Index number of the Help menu. We can then use this to place a custom menu before.
    Set cbcCutomMenu = cbMainMenuBar.Controls.Add(Type:=msoControlPopup, Before:=iHelpMenu) 'Add a Control to the "Worksheet Menu Bar" before Help.
    cbcCutomMenu.Caption = "&My Tools"  'Give the control a caption

    'Working with our new Control, add a sub control and give it a Caption and tell it which macro to run (OnAction).
    With cbcCutomMenu.Controls.Add(Type:=msoControlButton)
        .Caption = "Run Macro 1"
        .OnAction = "Macro1"
    End With

    With cbcCutomMenu.Controls.Add(Type:=msoControlButton)
        .Caption = "Run Macro 2"
        .OnAction = "Macro2"
    End With
End Sub

如果您希望在打开工作簿时添加自定义菜单,请转到 ThisWorkbook 模块并添加以下子项:

Private Sub Workbook_Open()
    AddCustomMenu
End Sub

推荐阅读