OzGrid

Add Excel Right Click Menu

< Back to Search results

 Category: [Excel]  Demo Available 

Add Excel Right Click Menu

 

Excel VBA: Adding a Command Button to the Excel Right Click Pop-up Toolbar/Command Bar

 

Adding a Command Button to the Excel Right Click Pop-up Toolbar/Command Bar


Excel allows us to modify nearly every part of Excel. One of these parts is the standard Excel CommandBars, or Toolbars. Sometimes you may have a macro that you wish to enable users to run by right clicking in any cell and choosing your macro from the Cell shortcut pop-up menu. The code do do this is relatively simply and is shown below.

Note how the code first deletes any existing menu option called "My Macro". This stops the code adding an additional custom menu options and ensures only one custom menu option is available at any one time. The use of Temporary:=True ensures this menu option is deleted whenever Excel closes. Without it, it's possible to have you custom menu option showing in another Workbook. This is also why we make use of the Workbook_Deactivate Event. That is, if we activate another Workbook while this one is open, the custom menu option is deleted.

The macro that is run whenever this custom menu option is clicked is called "My_Macro". You should change this, and the caption, to suit your needs.

The code below should be placed in Private Module of the Workbook Object (ThisWorkbook). To get there quickly, right click on the Excel icon, top left next to File and choose View Code.

Private Sub Workbook_Deactivate()

    On Error Resume Next

            With Application

                .CommandBars("Cell").Controls("My Macro").Delete

            End With

    On Error GoTo 0

End Sub





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

Dim cBut As CommandBarButton



    On Error Resume Next

        With Application

            .CommandBars("Cell").Controls("My Macro").Delete

            Set cBut = .CommandBars("Cell").Controls.Add(Temporary:=True)

        End With

        

        With cBut

           .Caption = "My Macro"

           .Style = msoButtonCaption

           .OnAction = "My_Macro"

        End With

    On Error GoTo 0

End Sub

 

See also:

Excel: Remove Duplicates in Excel
Restricting Excel VBA Loops
Return Excel Color Index Number or Color as Text
Return an Excel Worksheet/Sheet Name to a Cell
Excel: Reverse Cell Text/Content

 

See also Index to Excel VBA Code and Index to Excel Freebies and Lesson 1 - Excel Fundamentals and Index to how to… providing a range of solutions.

 

Click here to visit our Free 24/7 Excel/VBA Help Forum where there are thousands of posts you can get information from, or you can join the Forum and post your own questions.


Gallery



stars (0 Reviews)