为指定范围创建Excel VBA自定义右键单击菜单

ruarlubt  于 2023-06-25  发布在  其他
关注(0)|答案(1)|浏览(227)

是否有一种方法可以在Excel工作表中创建一个自定义的右键单击菜单项,该菜单项将触发一个宏,并限制该菜单项只能在预定义的范围内可见(例如A1:B2)?
下面的代码将创建自定义菜单项,但它还没有被限制在范围A1:B2。如何调整此代码,使自定义菜单仅出现在预定义的范围内?

Private Sub Workbook_Open()   
    
    Dim MyMenu As Object        
    
    Set MyMenu = Application.ShortcutMenus(xlWorksheetCell) _
                    .MenuItems.AddMenu("This is my Custom Menu", 1)

    With MyMenu.MenuItems    
        .Add "MyMacro1", "MyMacro1", , 1, , ""    
        .Add "MyMacro2", "MyMacro2", , 2, , ""    
    End With  
    Set MyMenu = Nothing
End Sub

Public Sub mymacro1()
    MsgBox "Macro1 from a right click menu"
End Sub
    
Public Sub mymacro2()
    MsgBox "Macro2 from a right click menu"
End Sub

是否可以同时删除相同范围的右键菜单中的标准项?
如果是的话,你能帮我写代码吗?
谢谢你。
亲切问候Jan

tp5buhyn

tp5buhyn1#

AFAIK,右键单击单元格可触发单元格菜单弹出窗口。任何单元格,但它是表的一部分的情况除外。从理论上讲,您可以将新添加的命令所需的范围转换为上下文菜单中的一部分**。但是在这种情况下,您必须自定义的菜单应该是List Range Popup。有两个不便之处,分别是:从两行的范围中,其中一行必须是标题(如果需要,这不是那么容易改变的),并且所需的命令将是上下文菜单的一部分对于所有表('listObjects )... 因此,我将尝试展示一个解决方案,只有在右键单击相应的单元格时才能放置命令,并删除其他单元格。 1.请在ThisWorkbook`代码模块中复制以下事件代码:

Private Sub Workbook_SheetBeforeRightClick(ByVal Sh As Object, ByVal Target As Range, Cancel As Boolean)
    Dim cB1 As CommandBarButton, cB2 As CommandBarButton
    
    DelCommands 'delete the custom commands for all cells...
    
    If Not Intersect(Target, Sh.Range("A1:B2")) Is Nothing Then 'if right click is applied to the necessary range:
        'add the two necessary commands:
        Set cB1 = Application.CommandBars("Cell").Controls.Add(Type:=msoControlButton, Temporary:=True)
          cB1.Caption = "MyMacro1": cB1.OnAction = "MyMacroA"
            
        Set cB2 = Application.CommandBars("Cell").Controls.Add(Type:=msoControlButton, Temporary:=True)
          cB2.Caption = "MyMacro2": cB2.OnAction = "MyMacroB"
    End If
End Sub

Private Sub DelCommands()
    On Error Resume Next
      Application.CommandBars("Cell").Controls("MyMacro1").Delete
      Application.CommandBars("Cell").Controls("MyMacro2").Delete
    On Error GoTo 0
End Sub

1.而标准模块中的被调用Subs:

Sub MyMacroA()
   MsgBox ActiveCell.address, vbInformation, "MyMacroA"
End Sub

Sub MyMacroB()
   MsgBox ActiveCell.address(0, 0), vbInformation, "MyMacroB"
End Sub

此调整后的上下文菜单将出现(在相应范围内)在所有工作表中。如果你只想把它限制在特定的,你应该玩sh.name,太。

相关问题