简体   繁体   English

Excel - 将自己的宏添加到选定单元格中的“右键单击”

[英]Excel - Add Own Macro to “Right Click” in Selected Cells

I would like to add an option to the "right click" menu and attach a macro to that option.我想在“右键单击”菜单中添加一个选项并将宏附加到该选项。 Ideally I would like this option to only show on one worksheet, called "main", and only in cells "C21:C42".理想情况下,我希望此选项仅显示在一个名为“main”的工作表上,并且仅显示在单元格“C21:C42”中。

For the purpose of this example I am happy if all the macro does is:就本示例而言,如果宏所做的所有事情都是:

msgbox "Hello World"

Many thanks in advance, Alan.非常感谢,艾伦。

Please, copy the next code in the sheet module where you want it acting .请将下一个代码复制到您希望它起作用的工作表模块中

Edited :编辑

It now passes a parameter (param):它现在传递一个参数(param):

Option Explicit


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 = "TesParam" 'parameter to be sent. It can be any kind...
    With cmdBtn
        .Tag = "testBt"
        .Caption = "MyOption"
        .Style = msoButtonCaption
        .OnAction = "'TestMacro """ & param & """'"
    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

You need a "TestMacro" Sub in a standard module.您需要标准模块中的“TestMacro”子。

Sub TestMacro(str As String)
   MsgBox "It works... (" & str & ")"
End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM