Gewusst wie: Programmgesteuertes Erstellen von Office-Menüs

Aktualisiert: November 2007

Betrifft

Die Informationen in diesem Thema gelten nur für die angegebenen Visual Studio Tools for Office-Projekte und Versionen von Microsoft Office.

Projekttyp

  • Projekte auf Dokumentebene

  • Projekte auf Anwendungsebene

Microsoft Office-Version

  • Microsoft Office 2003

Weitere Informationen finden Sie unter Verfügbare Features nach Anwendung und Projekttyp.

In diesem Beispiel wird auf der Menüleiste von Microsoft Office Excel 2003 ein Menü mit dem Namen New Menu erstellt. Das neue Menü wird vor dem Menü Hilfe platziert. Es enthält einen Menübefehl. Wenn auf den Menübefehl geklickt wird, wird Text in eine Zelle von Sheet1 eingefügt.

Ein Beispiel für das Anpassen der Benutzeroberfläche von Microsoft Office Word 2003 finden Sie unter Gewusst wie: Programmgesteuertes Erstellen von Office-Symbolleisten und Exemplarische Vorgehensweise: Erstellen von Kontextmenüs für Lesezeichen.

Fügen Sie der ThisWorkbook-Klasse folgenden Code hinzu.

Hinweis:

Sie müssen beim Hinzufügen von Ereignishandlern die Tag-Eigenschaft der Steuerelemente festlegen. Office verwendet die Tag-Eigenschaft, um Ereignishandler für ein bestimmtes CommandBarControl-Objekt zu verfolgen. Wenn die Tag-Eigenschaft leer ist, werden Ereignisse nicht ordnungsgemäß behandelt.

Hinweis:

Deklarieren Sie die Menüvariablen auf Klassenebene und nicht in der Methode, in der sie aufgerufen werden. Damit ist sichergestellt, dass die Menüvariablen so lange im Gültigkeitsbereich bleiben, wie die Anwendung ausgeführt wird. Ansonsten wird das Element von der Garbage Collection entfernt, und die Ausführung des Codes im Ereignishandler wird angehalten.

Beispiel

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

Siehe auch

Aufgaben

Gewusst wie: Programmgesteuertes Erstellen von Office-Symbolleisten

Exemplarische Vorgehensweise: Erstellen von Kontextmenüs für Lesezeichen

Konzepte

Anpassung der Office-Benutzeroberfläche

Optionale Parametern in Office-Projektmappen