How to add a macro to mutiple excel files using VBA - vba

Is there any way to write a VBA Macro to input another VBA Macro into multiple excel workbooks? If so, how do I start?
Any and all help is greatly appreciated.

you'll need a reference first
Microsoft Visual Basic For Applications Extensibility 5.3
And here you go. Have fun
Public Sub AddNewModule()
Dim proj As VBIDE.VBProject
Dim comp As VBIDE.VBComponent
Set proj = ActiveWorkbook.VBProject
Set comp = proj.VBComponents.Add(vbext_ct_StdModule)
comp.Name = "MyNewModule"
Set codeMod = comp.CodeModule
With codeMod
lineNum = .CountOfLines + 1
.InsertLines lineNum, "Public Sub ANewSub()"
lineNum = lineNum + 1
.InsertLines lineNum, " MsgBox " & """" & "I added a module!" & """"
lineNum = lineNum + 1
.InsertLines lineNum, "End Sub"
End With
End Sub
You can also just use the workbook with the code in it as a reference as well. Then you can call the module remotely.
As #BruceWayne mentioned, there is also sotring it in the personal book.
tl;dr - there's a few options that can get you there.

I recommend storing them in the Personal.xslb file which is accessible across Excel.
See this page or this page for more detail, but generally a quick way to get started is:
Press ALT+F11 to open the VBEditor.
Right click the "VBAProject (PERSONAL.XLSB)" and Add a new module
Add your code in the module.
Now, when you go to View --> Macros, you can choose to see those stored in the Personal.xlsb file:
(I "whited out" my macros for privacy, but they'll be listed by name)
Note: If you do not have a "Personal.xlsb", then you must create it. Simply record a new macro, but choose to store it in "Personal Macro Workbook". Then you should see it in the VBEditor.

I would think the easiest way to have the same code in slightly different Excel files is to have one 'template' and save it several times as several slightly different files. Or, if you want to get fancy, you can create an AddIn to make an Excel Macro available to all workbooks.
Option Explicit
Dim cControl As CommandBarButton
Private Sub Workbook_AddinInstall()
On Error Resume Next 'Just in case
'Delete any existing menu item that may have been left.
Application.CommandBars("Worksheet Menu Bar").Controls("Super Code").Delete
'Add the new menu item and Set a CommandBarButton Variable to it
Set cControl = Application.CommandBars("Worksheet Menu Bar").Controls.Add
'Work with the Variable
With cControl
.Caption = "Super Code"
.Style = msoButtonCaption
.OnAction = "MyGreatMacro"
'Macro stored in a Standard Module
End With
On Error GoTo 0
End Sub
Private Sub Workbook_AddinUninstall()
On Error Resume Next 'In case it has already gone.
Application.CommandBars("Worksheet Menu Bar").Controls("Super Code").Delete
On Error GoTo 0
End Sub
This code will be all you need to add a single menu item (called Super Code) to the end of the existing Worksheet Menu Bar as soon as the Add-in is installed by the user via Tools>Add-ins. When the Super Code menu item is clicked a macro (that is within a standard module of the add-in) is run. As mentioned earlier, the above code MUST be placed in the Private Module of ThisWorkbook for the Add-in.
If you want the Super Code menu item added, say before the Format menu item, you could use some code like this.
Option Explicit
Dim cControl As CommandBarButton
Private Sub Workbook_AddinInstall()
Dim iContIndex As Integer
On Error Resume Next 'Just in case
'Delete any existing menu item that may have been left
Application.CommandBars("Worksheet Menu Bar").Controls("SuperCode").Delete
'Pass the Index of the "Format" menu item number to a Variable.
'Use the FindControl Method to find it's Index number. ID number _
is used in case of Customization
iContIndex = Application.CommandBars.FindControl(ID:=30006).Index
'Add the new menu item and Set a CommandBarButton Variable to it.
'Use the number passed to our Integer Variable to position it.
Set cControl = Application.CommandBars("Worksheet Menu Bar").Controls.Add(Before:=iContIndex)
'Work with the Variable
With cControl
.Caption = "Super Code"
.Style = msoButtonCaption
.OnAction = "MyGreatMacro"
'Macro stored in a Standard Module
End With
On Error GoTo 0
End Sub
There would be no need to change the Workbook_AddinUninstall() code in this case.
We have covered ID numbers while working with CommandBars etc in a P rior Newsletter Issue The link to the Microsoft site that has a BIG list of all the ID numbers for working with CommandBars can be Found Here
The above examples actually have the all the menu item code in the Workbook_AddinInstall and Workbook_AddinUnInstall Not a problem when the code is only adding one menu item. If however, you will be adding more then one and perhaps even Sub menus, you should place it in a Procedure (or 2) inside a standard Module. Then use some code as shown below
Private Sub Workbook_AddinInstall()
Run "AddMenus"
End Sub
Private Sub Workbook_AddinUninstall()
Run "DeleteMenu"
End Sub
Then in the standard module put some code perhaps like this
Sub AddMenus()
Dim cMenu1 As CommandBarControl
Dim cbMainMenuBar As CommandBar
Dim iHelpMenu As Integer
Dim cbcCutomMenu As CommandBarControl
'(1)Delete any existing one.We must use On Error Resume next _
in case it does not exist.
On Error Resume Next
Application.CommandBars("Worksheet Menu Bar").Controls("&NewMenu").Delete
'(2)Set a CommandBar variable to Worksheet menu bar
Set cbMainMenuBar = Application.CommandBars("Worksheet Menu Bar")
'(3)Return the Index number of the Help menu. We can then use _
this to place a custom menu before.
iHelpMenu = cbMainMenuBar.Controls("Help").Index
'(4)Add a Control to the "Worksheet Menu Bar" before Help
'Set a CommandBarControl variable to it
Set cbcCutomMenu = cbMainMenuBar.Controls.Add(Type:=msoControlPopup, Before:=iHelpMenu)
'(5)Give the control a caption
cbcCutomMenu.Caption = "&New Menu"
'(6)Working with our new Control, add a sub control and _
give it a Caption and tell it which macro to run (OnAction).
With cbcCutomMenu.Controls.Add(Type:=msoControlButton)
.Caption = "Menu 1"
.OnAction = "MyMacro1"
End With
'(6a)Add another sub control give it a Caption _
and tell it which macro to run (OnAction)
With cbcCutomMenu.Controls.Add(Type:=msoControlButton)
.Caption = "Menu 2"
.OnAction = "MyMacro2"
End With
'Repeat step "6a" for each menu item you want to add.
'Add another menu that will lead off to another menu
'Set a CommandBarControl variable to it
Set cbcCutomMenu = cbcCutomMenu.Controls.Add(Type:=msoControlPopup)
' Give the control a caption
cbcCutomMenu.Caption = "Next Menu"
'Add a control to the sub menu, just created above
With cbcCutomMenu.Controls.Add(Type:=msoControlButton)
.Caption = "&Charts"
.FaceId = 420
.OnAction = "MyMacro2"
End With
On Error GoTo 0
End Sub
Sub DeleteMenu()
On Error Resume Next
Application.CommandBars("Worksheet Menu Bar").Controls("&NewMenu").Delete
On Error GoTo 0
End Sub
You can find all details here.
http://www.ozgrid.com/VBA/excel-add-in-create.htm

Related

How to hide a popup menu item shown for a drawing shape in Microsoft Visio?

I would like to hide a few of the items that are shown in the popup menu when right-clicking on a drawing shape in Visio.
The code I tried. There is no change seen.
Sub HideVisioMenus()
Dim uiObj As Visio.UIObject
Dim menuSetObj As Visio.MenuSet
Dim menuItemsObj As Visio.menuitems
Dim i As Integer
Set uiObj = Visio.Application.BuiltInMenus
Set menuSetObj = uiObj.MenuSets.ItemAtID(visUIObjSetDrawing)
Set menuItemsObj = menuSetObj.Menus(8).menuitems
'Get the Show ShapeSheet menu item by its CmdNum property.
For i = 0 To menuItemsObj.Count - 1
Debug.Print menuItemsObj.Item(i).Caption
If menuItemsObj(i).CmdNum = visCmdWindowShowShapeSheet Then
menuItemsObj.Item(i).Visible = False
Exit For
End If
Next i
Visio.Application.SetCustomMenus uiObj
End Sub
Maybe what you are looking for is actually disabling Developer Mode? (it's in the settings). Unchecking that will hide the "ShapeSheet" command from the context menu. Please note that developer mode is already disabled by default. You can also turn it off programmatically like this:
Application.Settings.DeveloperMode = False
FYI: There are other methods as well, like disabling by registry settings (administration policies). I have a small note on this here: https://unmanagedvisio.com/disabling-visio-built-in-commands/
Which version of Visio are you using? I've been fiddling with the RibbonUI for so long, I forgot about hiding/removing items using CommandBars.
I honestly couldn't remember if it even works with the ribbon. So I fiddled around and it does work!
I think that you need this menuset id, though:
Visio.visUIObjSetCntx_DrawObjSel
However, walking through the items in that set doesn't reveal the Show ShapeSheet item. So that item is added in some special way by Visio.
I fiddled with some code and was able to hide everything but Show ShapeSheet and Hyperlinks. No idea how to get rid of those!
Sub DinkWithRightClickShapeMenu()
'// The following example demonstrates how to retrieve
'// the currently active user interface for your document
'// without replacing the application-level custom user
'// interface, if any.
'// Check if there are document custom menus.
If ThisDocument.CustomMenus Is Nothing Then
'Check if there are Visio custom menus.
If Visio.Application.CustomMenus Is Nothing Then
'Use the built-in menus.
Set visUiObj = Visio.Application.BuiltInMenus
Else
'Use the Visio custom menus.
Set visUiObj = Visio.Application.CustomMenus.Clone
End If
Else
'Use the file custom menus
Set visUiObj = ThisDocument.CustomMenus
End If
Dim menuSetObj As Visio.MenuSet
Dim menuItemsObj As Visio.MenuItems
Dim i As Integer, j As Integer
'// This is the menu set for right-clicking a shape:
Set menuSetObj = visUiObj.MenuSets.ItemAtID(Visio.visUIObjSetCntx_DrawObjSel)
'Set menuSetObj = visUIObj.MenuSets.ItemAtID(Visio.visUIObjSetCntx_BuiltinMenus)
'// List the menu items in the menu set.
'// For Each doesn't work:
Dim mnu As Visio.Menu
Dim mnuItem As Visio.MenuItem
For i = 0 To menuSetObj.Menus.Count - 1
Set mnu = menuSetObj.Menus.Item(i)
Debug.Print "Menu: " & i & ". '" & mnu.Caption & "'"
For j = 0 To mnu.MenuItems.Count - 1
Set mnuItem = mnu.MenuItems(j)
Debug.Print j, mnuItem.Caption
'// Hide every menu item:
mnuItem.Visible = False
'// This was a test to see if I could change the menu text:
'//mnuItem.Caption = mnuItem.Caption & " woohoo"
Debug.Print vbTab & mnuItem.Caption
Next j
Next i
'// Unfortunately, there are still two items left:
'// - Show ShapeSheet
'// - Hyperlinks...
Call Visio.ActiveDocument.SetCustomMenus(visUiObj)
'ThisDocument.SetCustomMenus uiObj
'Call Visio.Application.SetCustomMenus(visUiObj)
'// Restore the normal menus running this in the
'// Immediate window:
'Visio.ActiveDocument.ClearCustomMenus
'// Cleanup:
Set mnuItem = Nothing
Set mnu = Nothing
Set menuSetObj = Nothing
Set visUiObj = Nothing
End Sub

Powerpoint VBA/Macro: Deactivate (Grey out) Button on Ribbon, if no shape is selected

I have a macro in Powerpoint that gives me Information of a Shape. To bypass the error if no shape is selected I insert an errormask. However, this is very annoying.
Is it therefore possible to grey out the button if e.g. no Shape is selected. That way the user would npot even have a chance to click it.
Custom UI XML:
http://pastebin.com/T6NQ8WF8
Assuming you are using a 2007+ version of PowerPoint, the only way to manipulate the ribbon controls, buttons, etc., is through ribbon extensibility. It is possible to do this at run-time, with a vba hook, but it is much more difficult than in previous versions of PowerPoint where you could just use VBA to manipulate the controls' .Enabled or .Visible properties.
Here is an example of using ribbon extensibility to customize the ribbon at run-time. As you can see, it is not easy. I will show this in Option 2, below.
In this case, you have an error condition that you can easily identify using the .Type property of the Selection.ShapeRange. I think that attempting to conditionally disable this button at run-time (Option 2, below) is probably more trouble than it is worth.
Update
Is there a setting that greys your all buttons that don't have an effect.
No. The macros are the "effect", even if the result of the macro is that no action is performed. What you are asking is whether there is a setting which can compile and interpret your macros, determine whether that macro performs "an action" (e.g., manipulates a shape, changes a property assignment, etc.) and then disable buttons based on this determination. There is no such setting.
OPTION 1 -- Simply Do Not Display the MsgBox; Perform No Action if Invalid Selection
I will make some edits to clean up your code and use a better method of avoiding that error:
Sub Infos()
Dim n as String
Dim w as String
Dim h as String
Dim l as String
Dim T as String
With ActiveWindow.Selection.ShapeRange
Select Case .Type
Case 0
'MsgBox ("No shape selected.")
Exit Sub
Case Else
n = .Name
w = .Width
h = .Height
l = .Left
T = .Top
MsgBox "Name: " & n & Chr$(CharCode:=13) & "Länge: " & w & _
Chr$(CharCode:=13) & "Höhe: " & h & Chr$(CharCode:=13) & _
"Linkeposition: " & l & Chr$(CharCode:=13) & "Höhenposition: " & T
End Select
End Sub
OPTION 2 -- Use an Application Event Handler and Manipulate Ribbon at Run-Time
I mentioned that this is not easy. I uploaded an example file to Google Docs Presentation1.pptm. This should get you started. You can see now how much difficult this method is. If you are creating a PPAM/Add-In file, there are further considerations and complexities you may encounter. Good luck!
There are several errors in your code.
1. Your XML is not valid when I check in Custom UI Editor. I edited it here:
http://pastebin.com/SpG0Rtqq
2. Your Infos macro contains errors. You omit the End With statement, also, your n assignment will fail (and the rest of them will produce strange result) if the selection is multiple shapes. You can fix that by:
n = IIf(.ShapeRange.Count > 1, "Multiple shapes", .ShapeRange(1).Name)
w = IIf(.ShapeRange.Count > 1, "Multiple shapes", .ShapeRange(1).Width)
h = IIf(.ShapeRange.Count > 1, "Multiple shapes", .ShapeRange(1).Height)
l = IIf(.ShapeRange.Count > 1, "Multiple shapes", .ShapeRange(1).Left)
T = IIf(.ShapeRange.Count > 1, "Multiple shapes", .ShapeRange(1).Top)
Once you have fixed those components...
Add a module called mod_EventHandler, which includes this code. This will create an application event-handler class object, cEventClass:
Option Explicit
Public cPPTObject As New cEventClass
Public TrapFlag As Boolean
Sub TrapEvents()
'Creates an instance of the application event handler
If TrapFlag = True Then
MsgBox "Relax, my friend, the EventHandler is already active.", vbInformation + vbOKOnly, "PowerPoint Event Handler Example"
Exit Sub
End If
Set cPPTObject.PPTEvent = Application
TrapFlag = True
End Sub
Sub ReleaseTrap()
If TrapFlag = True Then
Set cPPTObject.PPTEvent = Nothing
Set cPPTObject = Nothing
TrapFlag = False
End If
End Sub
Since we need this class object, add a class module to your PowerPoint file, named cEventClass. In this module, put this code below. This code forces a refresh of the ribbon. This procedure implicitly calls the EnabledBtInfo subroutine, which then tests if the current selection is Shape(s).
Option Explicit
Public WithEvents PPTEvent As Application
Private Sub PPTEvent_WindowSelectionChange(ByVal Sel As Selection)
'Force refresh of the "btInfo" button:
RefreshRibbon "btInfo"
End Sub
And finally, another standard code module with this code to control the Button's visibility/enabled. Note that EnabledBtInfo is the VBA Hook for this button, and it tests whether Selection is shapes, before refreshing the ribbon:
Option Explicit
Public Rib As IRibbonUI
Public xmlID As String
'Callback for customUI.onLoad
Sub RibbonOnLoad(ribbon As IRibbonUI)
TrapEvents 'instantiate the event handler
Set Rib = ribbon
End Sub
Sub EnabledBtInfo(control As IRibbonControl, ByRef returnedVal)
'Check the ActiveWindow.Selection.ShapeRange
returnedVal = (ActiveWindow.Selection.Type = ppSelectionShapes)
Call RefreshRibbon(control.Id)
End Sub
Sub RefreshRibbon(Id As String)
xmlID = Id
If Rib Is Nothing Then
MsgBox "Error, Save/Restart your Presentation"
Else
Rib.Invalidate
End If
End Sub
When a shape(s) is selected, the magnifying glass icon is enabled:
When shape(s) is not selected, button is disabled:
And finally, when multiple shapes are selected:

Create a right-click context menu in Outlook 2003

I'm already able to create a new menu in the top menubar of Outlook 2003 but would like to do the same when the user right-click on an email (but not anywhere else in the interface if possible).
Here is what I got:
Sub AddMenus()
Dim cbMainMenuBar As CommandBar
Dim cbcCustomMenu As CommandBarControl
Dim cbcTest As CommandBarControl
Dim iHelpMenu as Integer
Set cbMainMenuBar = Application.ActiveExplorer.CommandBars.ActiveMenuBar
iHelpMenu = cbMainMenuBar.Controls("&?").index
Set cbcCustomMenu = cbMainMenuBar.Controls.Add(Type:=msoControlPopup, before:=iHelpMenu)
cbcCustomMenu.caption = "Menu &Name"
Set cbcTest = cbcCustomMenu.Controls.Add(Type:=msoControlPopup)
cbcTest.caption = "&Test"
With cbcTest.Controls.Add(Type:=msoControlButton)
.caption = "&Submenu item"
.OnAction = "macro"
End With
With cbcTest.Controls.Add(Type:=msoControlButton)
.caption = "Another submenu item"
.OnAction = "macro"
End With
With cbcCustomMenu.Controls.Add(Type:=msoControlButton)
.caption = "About"
.OnAction = "macro"
End With
End Sub
What do I have to change to make this works when right-clicking?
The definitive answer to the problem can be found here: http://www.outlookcode.com/codedetail.aspx?id=314
Here is what I come with after removing some of the code/comments I didn't need:
Option Explicit
Private WithEvents ActiveExplorerCBars As CommandBars
Private WithEvents ContextButton As CommandBarButton
Private IgnoreCommandbarsChanges As Boolean
Private Sub Application_Startup()
Set ActiveExplorerCBars = ActiveExplorer.CommandBars
End Sub
Private Sub ActiveExplorerCBars_OnUpdate()
Dim bar As CommandBar
If IgnoreCommandbarsChanges Then Exit Sub
On Error Resume Next
Set bar = ActiveExplorerCBars.Item("Context Menu")
On Error GoTo 0
If Not bar Is Nothing Then
AddContextButton bar
End If
End Sub
Sub AddContextButton(ContextMenu As CommandBar)
Dim b As CommandBarButton
Dim subMenu As CommandBarControl
Dim cbcCustomMenu As CommandBarControl, cbcLink As CommandBarControl
Set ContextMenu = ActiveExplorerCBars.Item("Context Menu")
'Unprotect context menu
ChangingBar ContextMenu, Restore:=False
'Menu
Set cbcCustomMenu = ContextMenu.Controls.Add(Type:=msoControlPopup)
cbcCustomMenu.caption = "&Menu"
'Link in Menu
Set cbcLink = cbcCustomMenu.Controls.Add(Type:=msoControlButton)
cbcLink.caption = "Link 1"
cbcLink.OnAction = "macro"
'Reprotect context menu
ChangingBar ContextMenu, Restore:=True
End Sub
'Called once to prepare for changes to the command bar, then again with
'Restore = true once changes are complete.
Private Sub ChangingBar(bar As CommandBar, Restore As Boolean)
Static oldProtectFromCustomize, oldIgnore As Boolean
If Restore Then
'Restore the Ignore Changes flag
IgnoreCommandbarsChanges = oldIgnore
'Restore the protect-against-customization bit
If oldProtectFromCustomize Then bar.Protection = bar.Protection And msoBarNoCustomize
Else
'Store the old Ignore Changes flag
oldIgnore = IgnoreCommandbarsChanges
IgnoreCommandbarsChanges = True
'Store old protect-against-customization bit setting then clear
'CAUTION: Be careful not to alter the property if there is no need,
'as changing the Protection will cause any visible CommandBarPopup
'to disappear unless it is the popup we are altering.
oldProtectFromCustomize = bar.Protection And msoBarNoCustomize
If oldProtectFromCustomize Then bar.Protection = bar.Protection And Not msoBarNoCustomize
End If
End Sub
I no longer have Outlook 2003 installed and Outlook 2010 doesn't let you mess with right-click menus the same way. So this compiles and is, hopefully close to what you need to do.
Before writing any code, you'll want to show hidden items, I think, to get the Intellisense for a couple of objects. In 2010 the ActiveExporer and ActiveInspector objects - which are the two types of view in Outlook, e.g., looking at all you email, or looking at a single email - are hidden. To unhide them, go into the Object Explorer by clicking F2 in the VBE, and right-click just about anywhere and check "Show Hidden Items".
So now you're ready to code:
First you need a way to determine the name of the right-click menu you are interested in. This tries to add a button to every menu, with the button's caption being the name and index of the menu. It resets the menu first, so as to not create more than one such button. The button should be at the bottom of the menu. The buttons are temporary, meaning they'll be gone the next time you open Outlook:
Sub GetCommandBarNames()
Dim cbar As Office.CommandBar
Dim cbarButton As Office.CommandBarButton
For Each cbar In ActiveInspector.CommandBars
On Error Resume Next
cbar.Reset
Set cbarButton = cbar.Controls.Add(Type:=msoControlButton, temporary:=True)
With cbarButton
.Caption = cbar.Name
.Style = msoButtonCaption
.Visible = True
End With
On Error GoTo 0
Next cbar
For Each cbar In ActiveExplorer.CommandBars
On Error Resume Next
cbar.Reset
Set cbarButton = cbar.Controls.Add(Type:=msoControlButton, temporary:=True)
With cbarButton
.Caption = cbar.Name & "-" & cbar.Index
.Style = msoButtonCaption
.Visible = True
End With
On Error GoTo 0
Next cbar
End Sub
After running this, right-click in Outlook and get the name of the menu you want. It will be the part before the dash on the last button. Let's say it's "foobar".
You should then be able to do this:
Sub AddButton()
Dim cbar As Office.CommandBar
Dim cbarButton As Office.CommandBarButton
Set cbar = ActiveExplorer.CommandBars("foobar") 'or maybe it's ActiveInspector
Set cbarButton = cbar.Controls.Add(Type:=msoControlButton, temporary:=True)
With cbarButton
.Caption = "&Submenu item"
.OnAction = "macro"
.Style = msoButtonCaption
'etc.
End With
'do the next button
Set cbarButton = cbar.Controls.Add(Type:=msoControlButton, temporary:=True)
'...
End Sub
Like I say, I'm doing this a bit blind, but I've done it many times in Excel (I even wrote two addins), so if this doesn't work, I should be able to get you there.

Display right click context menu with focus in through VBA macro in Microsoft Word 2007

I would like to programmatically display the right click context menu with focus through a VBA macro in Word 2007.
This would allow me to map the macro to a hotkey and expose the menu with focus without leaving the keyboard. I assumed this would be done through the Application object's CommandBars collection, accessed along the lines of :
Application.CommandBars.'access appropriate mehod or member here'
But I do not see any method or member that seems like it would show the context menu. Is it possible to achieve this through a VBA macro?
EDIT:
As suggested I looped through each CommandBar and obtained the name and index to try and find out which CommandBar index to use:
Sub C_RightClick()
'Activates right-click context menu
'
Dim cbar As Office.CommandBar
Dim cbarIndex As Integer
Dim testString As String
Dim cBarsArray(0 To 500)
Dim arrayCounter As Integer
testString = ""
arrayCounter = 1
For Each cbar In CommandBars
'TRUE if right-click
'If LCase(cbar.Name) = 'right-click' Then
' cbarIndex = cbar.Index
'End If
testString = testString + CStr(cbar.Index) + " " + cbar.Name + " " + CStr(cbar.Type = msoBarTypePopup) + vbCrLf
Debug.Print cbar.Name; " "; cbar.Type = msoBarTypePopup
'Add name to array and increment counter
cBarsArray(arrayCounter) = cbar.Name
arrayCounter = arrayCounter + 1
Next cbar
MsgBox testString
'Application.CommandBars(cbarIndex).ShowPopup
End Sub
However, I do not see any titled 'Right-Click'. I thought it may be 'Standard' , whose index is 1, but received an error when I attempted to access it.
If anyone knows the correct name for the default right-click context menu that appears in Word 2007 when the Home tab is selected, it would be appreciated. Otherwise, I will take that question to SuperUser and research on my own. Thank you for the help.
Try something like:
Application.CommandBars(100).ShowPopup
The argument can be the Commandbar index or caption.
To execute a particular command on a commandbar, try something like:
Application.CommandBars(100).Controls("Paste").Execute
To print a list of all commandbars to the Immediate Window:
Sub test()
Dim cbar As Office.CommandBar
For Each cbar In CommandBars
'TRUE if right-click
Debug.Print cbar.Name; " "; cbar.Type = msoBarTypePopup
Next cbar
End Sub
EDIT:
In answer to your question about the right-click menu that you get over the HOME tab, I think it's a different kind of control from CommandBar.
To get a better idea of the right-click menu names and indexes, I've modified the code above slightly. This now tries to add a control to each right-click menu. The added control's caption is the menu's name and Index. The controls are temporary - they'll be gone the next time you open Word.
Sub test()
Dim cbar As Office.CommandBar
Dim ctl As Office.CommandBarControl
For Each cbar In Application.CommandBars
With cbar
On Error Resume Next
'this will delete any customizations
.Reset
Set ctl = .Controls.Add(Type:=msoControlButton, Temporary:=True)
ctl.Caption = .Index & " - " & cbar.Name
Debug.Print "Name: "; cbar.Name; " Right-click: "; cbar.Type = msoBarTypePopup; " Error descr: "; Err.Description
On Error GoTo 0
End With
Next cbar
End Sub
It also prints out the error message, if there was one, to the immediate window.
The reason I don't think you'll have luck with the "Home" context menu is that no control is added to it. Here's a pic of a menu with the control added:

Automatically add a single menu item of an add-in in Excel

I am using Microsoft Excel 2010 for Windows.
I have already developed an add-in addin.xlam, which contains a sub main. addin.xlam is at the right place so that it is visible and selectable via the menu Developer -> Add-Ins. When I open a normal workbook test.xlsm, and press Alt + F11, I can see the code of addin.xlam is loaded.
My aim is to add a single menu item to the menu bar of Excel, to allow users to launch main of add-in.xlam. By following this link, my code in addin.xlam is as follows:
Option Explicit
Dim cControl As CommandBarButtonPrivate
Sub Workbook_AddinInstall()
On Error Resume Next 'Just in case
'Delete any existing menu item that may have been left.
Application.CommandBars("Worksheet Menu Bar").Controls("Super Code").Delete
'Add the new menu item and Set a CommandBarButton Variable to it
Set cControl = Application.CommandBars("Worksheet Menu Bar").Controls.Add
'Work with the Variable
With cControl
.Caption = "Super Code"
.Style = msoButtonCaption
.OnAction = "main" 'Macro stored in a Standard Module
End With
On Error GoTo 0
End Sub
Private Sub Workbook_AddinUninstall()
On Error Resume Next 'In case it has already gone.
Application.CommandBars("Worksheet Menu Bar").Controls("Super Code").Delete
On Error GoTo 0
End Sub
This code is well placed in ThisWorkbook of addin.xlam, it is also visible in test.xlsm. But I can't see any change in the menu bar.
Does anyone know what happens?
The AddinInstall and AddinUninstall events are only fired when the the addin is "installed" or "uninstalled" using the Excel Addin Manager.
IMHO this can lead to problems, so I always recommend using the Workbook_Open and Workbook_BeforeClose events instead.
Charles is right, you need to replace Workbook_AddinInstall() with Workbook_Open(), and replace Workbook_AddinUninstall() with Workbook_BeforeClose().
furthermore, you need CommandBarButton not CommandBarButtonPrivate.
good luck!