Cómo: Crear menús de Office mediante programación

Actualización: noviembre 2007

Se aplica a

La información de este tema sólo se aplica a los proyectos y versiones especificados de Visual Studio Tools para Office de Microsoft Office.

Tipo de proyecto

  • Proyectos de nivel de documento

  • Proyectos de nivel de aplicación

Versión de Microsoft Office

  • Microsoft Office 2003

Para obtener más información, vea Características disponibles por aplicación y tipo de proyecto.

En este ejemplo, se crea un menú llamado Nuevo menú en la barra de menús de Microsoft Office Excel 2003, y se coloca antes del menú Ayuda. Contiene un comando de menú. Cuando se hace clic en el comando de menú, se inserta texto en una celda de Sheet1.

Para obtener un ejemplo de cómo personalizar la interfaz de usuario en Microsoft Office Word 2003, vea Cómo: Crear barras de herramientas de Office mediante programación y Tutorial: Crear menús de acceso directo para marcadores.

Agregue el código siguiente a la clase ThisWorkbook.

Nota:

Debe establecer la propiedad Tag de los controles cuando agregue controladores de eventos. Office utiliza la propiedad Tag para efectuar el seguimiento de controladores de eventos correspondientes a un control CommandBarControl concreto. Si la propiedad Tag está en blanco, los eventos no se controlarán correctamente.

Nota:

Declare las variables de menú en el nivel de clase en lugar de hacerlo en el método donde son llamadas. Esto garantiza que las variables de menú permanezcan en el ámbito mientras la aplicación esté en ejecución. De lo contrario, el elemento se quita mediante la recolección de elementos no utilizados y el código del controlador de eventos deja de funcionar.

Ejemplo

' Declare the menu variable at the class level.
Private WithEvents menuCommand As Office.CommandBarButton
Private menuTag As String = "A unique tag"


' Call AddMenu from the Startup event of ThisWorkbook.
Private Sub ThisWorkbook_Startup(ByVal sender As Object, ByVal e As System.EventArgs) _
    Handles Me.Startup

    CheckIfMenuBarExists()
    AddMenuBar()
End Sub


' If the menu already exists, remove it.
Private Sub CheckIfMenuBarExists()
    Try
        Dim foundMenu As Office.CommandBarPopup = _
            Me.Application.CommandBars.ActiveMenuBar.FindControl( _
                Office.MsoControlType.msoControlPopup, System.Type.Missing, menuTag, True, True)

        If foundMenu IsNot Nothing Then
            foundMenu.Delete(True)
        End If

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub


' Create the menu, if it does not exist.
Private Sub AddMenuBar()

    Try
        Dim menuBar As Office.CommandBar = Application.comm.CommandBars.ActiveMenuBar
        Dim menuCaption As String = "Ne&w Menu"

        If menuBar IsNot Nothing Then
            Dim cmdBarControl As Office.CommandBarPopup = Nothing
            Dim controlCount As Integer = menuBar.Controls.Count

            ' Add the new menu.
            cmdBarControl = CType(menuBar.Controls.Add( _
                Type:=Office.MsoControlType.msoControlPopup, Before:=controlCount, Temporary:=True),  _
                Office.CommandBarPopup)

            cmdBarControl.Caption = menuCaption

            ' Add the menu command.
            menuCommand = CType(cmdBarControl.Controls.Add( _
                Type:=Office.MsoControlType.msoControlButton, Temporary:=True),  _
                Office.CommandBarButton)

            With menuCommand
                .Caption = "&New Menu Command"
                .Tag = "NewMenuCommand"
                .FaceId = 65
            End With
        End If

    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try
End Sub


' Add text to cell A1 when the menu is clicked.
Private Sub menuCommand_Click(ByVal Ctrl As Microsoft.Office.Core.CommandBarButton, _
    ByRef CancelDefault As Boolean) Handles menuCommand.Click

    Globals.Sheet1.Range("A1").Value2 = "The menu command was clicked."
End Sub
// Declare the menu variable at the class level.
private Office.CommandBarButton menuCommand;
private string menuTag = "A unique tag";


// Call AddMenu from the Startup event of ThisWorkbook.
private void ThisWorkbook_Startup(object sender, System.EventArgs e)
{
    CheckIfMenuBarExists();
    AddMenuBar();
}


// If the menu already exists, remove it.
private void CheckIfMenuBarExists()
{
    try 
    {
        Office.CommandBarPopup foundMenu = (Office.CommandBarPopup)
            this.Application.CommandBars.ActiveMenuBar.FindControl(
            Office.MsoControlType.msoControlPopup, System.Type.Missing, menuTag, true, true);

        if (foundMenu != null)
        {
            foundMenu.Delete(true);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
}


// Create the menu, if it does not exist.
private void AddMenuBar()
{
    try
    {
        Office.CommandBarPopup cmdBarControl = null;
        Office.CommandBar menubar = (Office.CommandBar)Application.CommandBars.ActiveMenuBar;
        int controlCount = menubar.Controls.Count;
        string menuCaption = "&New Menu";

        // Add the menu.
        cmdBarControl = (Office.CommandBarPopup)menubar.Controls.Add(
            Office.MsoControlType.msoControlPopup, missing, missing, controlCount, true);

        if (cmdBarControl != null)
        {
            cmdBarControl.Caption = menuCaption;

            // Add the menu command.
            menuCommand = (Office.CommandBarButton)cmdBarControl.Controls.Add(
                Office.MsoControlType.msoControlButton, missing, missing, missing, true);

            menuCommand.Caption = "&New Menu Command";
            menuCommand.Tag = "NewMenuCommand";
            menuCommand.FaceId = 65;

            menuCommand.Click += new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler(
                menuCommand_Click);
        }
    }
    catch (Exception e)
    {
        MessageBox.Show(e.Message);
    }
}


// Add text to cell A1 when the menu is clicked.
private void menuCommand_Click(Microsoft.Office.Core.CommandBarButton Ctrl, ref bool CancelDefault)
{
    Globals.Sheet1.Range["A1", missing].Value2 = "The menu command was clicked.";
}

Vea también

Tareas

Cómo: Crear barras de herramientas de Office mediante programación

Tutorial: Crear menús de acceso directo para marcadores

Conceptos

Personalización de la interfaz de usuario de Office

Descripción de los parámetros opcionales en las soluciones de Office