如何:以编程方式创建 Office 菜单

更新:2007 年 11 月

适用对象

本主题中的信息仅适用于指定的 Visual Studio Tools for Office 项目和 Microsoft Office 版本。

项目类型

  • 文档级项目

  • 应用程序级项目

Microsoft Office 版本

  • Microsoft Office 2003

有关更多信息,请参见按应用程序和项目类型提供的功能

此示例在 Microsoft Office Excel 2003 中的菜单栏上创建一个称为 New Menu 的菜单。这个新菜单位于“帮助”菜单的前面。它包含一个菜单命令。单击此菜单命令时,文本将被插入到 Sheet1 上的单元格中。

有关如何在 Microsoft Office Word 2003 中自定义用户界面的示例,请参见如何:以编程方式创建 Office 工具栏演练:创建书签的快捷菜单

向 ThisWorkbook 类中添加下面的代码。

0batekf4.alert_note(zh-cn,VS.90).gif说明:

添加事件处理程序时,必须在控件上设置 Tag 属性。Office 使用 Tag 属性跟踪特定 CommandBarControl 的事件处理程序。如果 Tag 属性为空,则没有正确地处理事件。

0batekf4.alert_note(zh-cn,VS.90).gif说明:

在类级别声明菜单变量,而不要在调用这些变量的方法内进行声明。这样可以确保只要应用程序在运行,这些菜单变量就会保持在范围内。否则,此项便会被垃圾回收移除,而事件处理程序代码也将停止工作。

示例

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

请参见

任务

如何:以编程方式创建 Office 工具栏

演练:创建书签的快捷菜单

概念

Office UI 自定义

了解 Office 解决方案中的可选参数