Condividi tramite


Procedura: creare menu di Office a livello di codice

Aggiornamento: novembre 2007

Si applica a

Le informazioni contenute in questo argomento riguardano solo i progetti Visual Studio Tools per Office e le versioni di Microsoft Office specificati.

Tipo di progetto

  • Progetti a livello di documento

  • Progetti a livello di applicazione

Versione Microsoft Office

  • Microsoft Office 2003

Per ulteriori informazioni, vedere Funzionalità disponibili in base ai tipi di progetto e applicazione.

In questo esempio viene creato un menu denominato New Menu sulla barra dei menu di Microsoft Office Excel. Il nuovo menu verrà collocato prima del menu Guida. e conterrà un comando. Quando l'utente farà clic sul comando del menu, verrà inserito del testo in una cella di Sheet1.

Per un esempio su come personalizzare l'interfaccia utente di Microsoft Office Word 2003, vedere Procedura: creare barre degli strumenti di Office a livello di codice e Procedura dettagliata: creazione di menu di scelta rapida per segnalibri.

Aggiungere il seguente codice alla classe ThisWorkbook.

Nota:

È necessario impostare la proprietà Tag dei controlli quando si aggiungono gestori eventi. La proprietà Tag è utilizzata da Office per tenere traccia dei gestori eventi per uno specifico controllo CommandBarControl. Se la proprietà Tag viene lasciata vuota, gli eventi non verranno gestiti correttamente.

Nota:

Dichiarare le variabili di menu a livello di classe anziché all'interno del metodo in cui sono chiamate. In questo modo, le variabili resteranno nell'ambito per tutta la durata dell'esecuzione dell'applicazione. In caso contrario, l'elemento verrà rimosso dalla procedura di Garbage Collection e il codice del gestore eventi smetterà di funzionare.

Esempio

' 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.";
}

Vedere anche

Attività

Procedura: creare barre degli strumenti di Office a livello di codice

Procedura dettagliata: creazione di menu di scelta rapida per segnalibri

Concetti

Personalizzazione dell'interfaccia utente di Office

Informazioni sui parametri facoltativi nelle soluzioni Office