Reputation: 961
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".
For the purpose of this example I am happy if all the macro does is:
msgbox "Hello World"
Many thanks in advance, Alan.
Upvotes: 0
Views: 1408
Reputation: 42236
Please, copy the next code in the sheet module where you want it acting.
Edited:
It now passes a parameter (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.
Sub TestMacro(str As String)
MsgBox "It works... (" & str & ")"
End Sub
Upvotes: 3