从右键菜单中删除临时选项

问题描述

以下代码位于名为“SPG 摘要”的工作表中

    Private Sub Worksheet_BeforeRightClick(ByVal Target As Range,Cancel As Boolean)
      Dim cmdBtn As CommandBarButton,param As String
      
      Set cmdBtn = Application.CommandBars("Cell").FindControl(,"testBt")
      If Intersect(Target,Range("C21:C42")) Is nothing Then
        If Not cmdBtn Is nothing Then cmdBtn.Delete
        Exit Sub
      End If
        
        If Not cmdBtn Is nothing Then Exit Sub
        Set cmdBtn = Application.CommandBars("Cell").Controls.Add(Temporary:=True)
        param = "test param"
        With cmdBtn
            .Tag = "testBt"
            .Caption = "MyOption"
            .Style = msoButtonCaption
            .OnAction = "TestMacro"
        End With
    End Sub

Private Sub Worksheet_Deactivate()
    Dim cmdBtn As CommandBarButton
    Set cmdBtn = Application.CommandBars("Cell").FindControl(,"testBt")
    If Not cmdBtn Is nothing Then cmdBtn.Delete
End Sub

TestMacro 代码如下:

Sub TestMacro()
    
    Sheets("UPC Summary").Range("A21").Value = ActiveCell.Value
    Application.Goto Sheets("UPC Summary").Range("A1"),True

End Sub

如果我删除“Sub Worksheet_Deactivate”,代码将起作用,但这意味着右键单击选项在我们已经访问的工作表上仍然可用,我想停止,因为右键单击菜单选项应该只在“SPG 俱乐部摘要”表。

如果我尝试按原样运行它,则会收到以下错误

enter image description here

以及带有粗斜体的错误是excel将黄色作为问题的原因“如果不是cmdBtn什么都没有,那么cmdBtn.Delete

非常感谢艾伦。

解决方法

似乎您无法在其代码仍在执行时删除右键单击选项。

您可以在 ThisWorkbook 模块中使用类似的东西:

Private Sub Workbook_SheetBeforeRightClick(ByVal Sh As Object,ByVal Target As Range,Cancel As Boolean)

    Dim cmdBtn As CommandBarButton,param As String
    
    Set cmdBtn = Application.CommandBars("Cell").FindControl(,"testBt")
    
    'adjust sheet name/range to suit
    If Sh.Name = "Data" And Not Intersect(Target,Sh.Range("C21:C42")) Is Nothing Then
        If cmdBtn Is Nothing Then
            Set cmdBtn = Application.CommandBars("Cell").Controls.Add(Temporary:=True)
            param = "test param"
            With cmdBtn
                .Tag = "testBt"
                .Caption = "MyOption"
                .Style = msoButtonCaption
                .OnAction = "TestMacro"
            End With
        End If
    Else
        If Not cmdBtn Is Nothing Then cmdBtn.Delete
    End If
      
End Sub