Share via


HOW TO:將命令加入到 Excel 的捷徑功能表

在這個範例中,會示範如何使用應用程式層級增益集,將命令加入至 Excel 的捷徑功能表。 當您以滑鼠右鍵按一下工作表儲存格時,會出現捷徑功能表。 當使用者按一下命令時,所有已選取之儲存格中包含的文字會寫入至文字檔。

**適用於:**本主題中的資訊適用於 Excel 2007 和 Excel 2010 的文件層級專案和應用程式層級專案。如需詳細資訊,請參閱依 Office 應用程式和專案類型提供的功能

將下列程式碼加入至 Excel 應用程式層級專案中的 ThisAddIn 類別。

範例

Private WithEvents writeToText As Office.CommandBarButton
Private selectedCells As Excel.Range

Private Sub ThisAddIn_Startup(ByVal sender _
    As Object, ByVal e As System.EventArgs) Handles Me.Startup

    DefineShortcutMenu()
End Sub

Private Sub DefineShortcutMenu()

    Dim menuItem As Office.MsoControlType = Office.MsoControlType.msoControlButton
    writeToText = Application.CommandBars("Cell").Controls.Add(Type:=menuItem, _
        Before:=1, Temporary:=True)

    writeToText.Style = Office.MsoButtonStyle.msoButtonCaption
    writeToText.Caption = "Write to a Text File"
    writeToText.Tag = "0"
End Sub

Private Sub Application_SheetBeforeRightClick(ByVal Sh _
    As Object, ByVal Target As Excel.Range, _
    ByRef Cancel As Boolean) Handles Application.SheetBeforeRightClick

    selectedCells = Target
End Sub

Private Sub writeToText_Click(ByVal Ctrl As Office.CommandBarButton, _
    ByRef CancelDefault As Boolean) Handles writeToText.Click

    Try
        Dim currentDateTime As System.DateTime = _
            System.DateTime.Now
        Dim dateStamp As String = _
            currentDateTime.ToString("dMMMMyyyy_hh.mm.ss")

        Dim fileName As String = System.Environment.GetFolderPath( _
            Environment.SpecialFolder.MyDocuments) & "\\" & _
            dateStamp & ".txt"
        Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(fileName)

        For Each cell As Excel.Range In selectedCells.Cells
            If cell.Value2 IsNot Nothing Then
                sw.WriteLine(cell.Value2.ToString())
            End If
        Next
        sw.Close()
    Catch ex As Exception
        System.Windows.Forms.MessageBox.Show(ex.Message)
    End Try

End Sub
private Office.CommandBarButton writeToText;
private Excel.Range selectedCells;

private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
    DefineShortcutMenu();
    Application.SheetBeforeRightClick +=
        new Excel.AppEvents_SheetBeforeRightClickEventHandler
            (Application_SheetBeforeRightClick);
    writeToText.Click +=
        new Microsoft.Office.Core._CommandBarButtonEvents_ClickEventHandler
            (writeToText_Click);
}

void writeToText_Click(Office.CommandBarButton Ctrl,
    ref bool CancelDefault)
{
    try
    {
        System.DateTime currentDateTime = System.DateTime.Now;
        string dateStamp = currentDateTime.ToString("dMMMMyyyy_hh.mm.ss");

        string fileName =
            System.Environment.GetFolderPath
            (Environment.SpecialFolder.MyDocuments) + "\\\\" + dateStamp + ".txt";
        System.IO.StreamWriter sw = new System.IO.StreamWriter(fileName);

        foreach (Excel.Range cell in selectedCells.Cells)
        {
            if (cell.Value2 != null)
            {
                sw.WriteLine(cell.Value2.ToString());
            }
        }
        sw.Close();
    }
    catch (Exception ex)
    {
        System.Windows.Forms.MessageBox.Show(ex.Message);
    }
}
void Application_SheetBeforeRightClick(object Sh,
    Excel.Range Target, ref bool Cancel)
{
    selectedCells = Target;
}

private void DefineShortcutMenu()
{

    Office.MsoControlType menuItem = Office.MsoControlType.msoControlButton;
    writeToText = (Office.CommandBarButton)Application.CommandBars["Cell"].
        Controls.Add(menuItem, missing, missing, 1, true);

    writeToText.Style = Office.MsoButtonStyle.msoButtonCaption;
    writeToText.Caption = "Write to a Text File";
    writeToText.Tag = "0";
}

穩固程式設計

加入事件處理常式時,您必須設定控制項的 Tag 屬性。 Office 使用 Tag 屬性,追蹤特定 CommandBarControl 的事件處理常式。 如果 Tag 屬性為空白,則不會適當地處理事件。

在類別層級宣告您的功能表變數,而不是在呼叫變數的方法內宣告變數。 這可確保功能表變數在應用程式執行時始終位於範圍內。 否則,記憶體回收會移除項目,而且您的事件處理常式也會停止運作。

請參閱

工作

HOW TO:建立 Office 工具列

逐步解說:建立書籤的快速鍵功能表

HOW TO:將命令加入到 Word 的捷徑功能表

HOW TO:將自訂功能表和功能表項目加入至 Outlook

HOW TO:將自訂圖示加入至工具列和功能表項目

概念

Office 方案中的選擇性參數

其他資源

Office UI 自訂