特定的命令栏不会在上下文菜单中关闭

时间:2016-08-11 15:52:33

标签: excel excel-vba vba

我编写了一个脚本,在上下文菜单中显示特定的脚本。 编程之后,contextmenu显示我想要启动的脚本,脚本运行良好。

'SCRIPT POUR MENU CONTEXTUEL
Sub AddToCellMenu()
    Dim ContextMenu As CommandBar
    Dim MySubMenu As CommandBarControl

    ' Delete the controls first to avoid duplicates.
    Call DeleteFromCellMenu

    ' Set ContextMenu to the Cell context menu.
    Set ContextMenu = Application.CommandBars("Cell")

    ' Add one custom button to the Cell context menu "BL OK".
    With ContextMenu.Controls.Add(Type:=msoControlButton, before:=20)
        .OnAction = "'" & ThisWorkbook.Name & "'!" & "Bouton_BonLivraisonOK"
        .FaceId = 71
        .Caption = "Bon Livraison OK"
        .Tag = "My_Cell_Control_Tag"
    End With

    ' Add one custom button to the Cell context menu "LIVRAISON OK".
    With ContextMenu.Controls.Add(Type:=msoControlButton, before:=21)
        .OnAction = "'" & ThisWorkbook.Name & "'!" & "Bouton_LivraisonOK"
        .FaceId = 72
        .Caption = "Expédition OK"
        .Tag = "My_Cell_Control_Tag"
    End With

    ' Add one custom button to the Cell context menu "Livraison avec RELIQUAT".
    With ContextMenu.Controls.Add(Type:=msoControlButton, before:=22)
        .OnAction = "'" & ThisWorkbook.Name & "'!" & "Bouton_LivraisonReliquat"
        .FaceId = 73
        .Caption = "Expédition avec RELIQUAT"
        .Tag = "My_Cell_Control_Tag"
    End With

    ' Add one custom button to the Cell context menu "RAZ".
    With ContextMenu.Controls.Add(Type:=msoControlButton, before:=23)
        .OnAction = "'" & ThisWorkbook.Name & "'!" & "Bouton_CellBlank"
        .FaceId = 70
        .Caption = "RAZ"
        .Tag = "My_Cell_Control_Tag"
    End With

    ' Add a separator to the Cell context menu.
    ContextMenu.Controls(20).BeginGroup = True

End Sub

问题是关闭文件后contextmenu仍然在其他excel文件中运行。 当我处理其他Excel文件时,我需要你的帮助来关闭上下文中的函数。

Sub DeleteFromCellMenu()
    Dim ContextMenu As CommandBar
    Dim ctrl As CommandBarControl

    ' Set ContextMenu to the Cell context menu.
    Set ContextMenu = Application.CommandBars("Cell")

    ' Delete the custom controls with the Tag : My_Cell_Control_Tag.
    For Each ctrl In ContextMenu.Controls
        If ctrl.Tag = "My_Cell_Control_Tag" Then
            ctrl.Delete
        End If
    Next ctrl

    ' Delete the custom built-in Save button.
    On Error Resume Next
    ContextMenu.FindControl(ID:=3).Delete
    On Error GoTo 0
End Sub

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。 我必须在工作簿中声明CellMenu的打开/关闭。 请参考以下代码:

 Private Sub Workbook_Activate()
    Call AddToCellMenu
End Sub

Private Sub Workbook_Deactivate()
    Call DeleteFromCellMenu
End Subenter code here
相关问题