방법: 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에서는 특정 CommandBarControl의 이벤트 처리기를 추적하기 위해 Tag 속성을 사용합니다. Tag 속성이 비어 있으면 이벤트가 올바르게 처리되지 않습니다.

메뉴 변수가 호출되는 메서드 안이 아닌 클래스 수준에서 해당 변수를 선언합니다. 이렇게 하면 응용 프로그램이 실행되는 동안 메뉴 변수를 범위에 계속 유지할 수 있습니다. 그렇지 않으면 가비지 수집으로 항목이 제거되고 이벤트 처리기 코드 실행이 중단됩니다.

참고 항목

작업

방법: Office 도구 모음 만들기

연습: 책갈피에 대한 바로 가기 메뉴 만들기

방법: Word에서 바로 가기 메뉴에 명령 추가

방법: Outlook에 사용자 지정 메뉴 및 메뉴 항목 추가

방법: 도구 모음 및 메뉴 항목에 사용자 지정 아이콘 추가

개념

Office 솔루션의 선택적 매개 변수

기타 리소스

Office UI 사용자 지정