Visual Basic .NET을 사용하여 Excel의 이벤트를 처리하는 방법

요약

이 단계별 문서에서는 Visual Basic .NET을 사용하여 개발하는 Automation 클라이언트에서 Microsoft Office Excel 2003 및 Microsoft Office Excel 2007 이벤트를 처리하는 방법을 설명합니다.

이벤트 처리기 만들기

다음 방법 중 하나를 사용하여 Microsoft Visual Basic .NET 2003 또는 Visual Basic .NET 2002를 사용하여 이벤트 처리기를 만들 수 있습니다. Visual Basic .NET을 사용하여 이벤트 처리기를 만드는 방법은 이벤트 처리기를 이벤트와 연결하는 방법에 따라 달라집니다.

  • 일반적으로 WithEvents 키워드와 함께 Handles 키워드를 사용하여 이벤트 처리기를 만듭니다. WithEvents 키워드를 사용하여 변수를 선언하면 Visual Basic .NET은 런타임에 해당 개체의 이벤트에 자동으로 연결됩니다. 해당 개체에 대한 특정 이벤트를 처리하려면 코드 보기에 있는 동안 Visual Studio .NET 환경의 클래스 목록 및 메서드 목록을 사용하여 관련 처리기를 추가합니다.
  • AddHandler 키워드를 사용하여 Visual Basic .NET은 이벤트를 처리하는 두 번째 방법을 제공합니다. AddHandler 키워드 및 RemoveHandler 키워드를 사용하면 특정 이벤트에 대한 이벤트 처리를 동적으로 시작하고 중지할 수 있습니다.

Visual Basic .NET Automation 클라이언트 만들기

다음 단계에서는 Visual Basic .NET을 사용하여 개발된 Automation 클라이언트에서 Excel 이벤트를 처리하는 방법을 보여 줍니다.

  1. Visual Studio .NET 2002 또는 Visual Studio .NET 2003을 시작합니다. [파일] 메뉴에서 [새로 만들기]를 클릭한 다음 [프로젝트]를 클릭합니다. Visual Basic 프로젝트 아래에서 Windows 애플리케이션을 선택합니다.

    기본적으로 Form1이 만들어집니다.

  2. Microsoft Excel 개체 라이브러리에 대한 참조를 추가합니다. 이렇게 하려면 다음과 같이 하십시오.

    1. 프로젝트 메뉴에서 참조 추가를 클릭합니다.
    2. COM 탭에서 Microsoft Excel 11.0 개체 라이브러리를 찾은 다음 선택을 클릭합니다.
    3. [참조 추가] 대화 상자에서 [확인]을 클릭하여 선택 내용을 적용합니다. 선택한 라이브러리에 대한 래퍼를 생성하라는 메시지가 표시되면 [예]를 클릭합니다.
  3. 프로젝트 메뉴에서 모듈 추가를 선택합니다. 템플릿 목록에서 모듈을 선택한 다음 열기를 클릭합니다. 새 모듈에 다음 코드를 붙여넣습니다.

       '==================================================================
       'Demonstrates Using a Delegate for Event Handling
       '==================================================================
    
    Private xlApp As Excel.Application
       Private xlBook As Excel.Workbook
       Private xlSheet1 As Excel.Worksheet
       Private xlSheet2 As Excel.Worksheet
       Private xlSheet3 As Excel.Worksheet
       Private EventDel_BeforeBookClose As Excel.AppEvents_WorkbookBeforeCloseEventHandler
       Private EventDel_CellsChange As Excel.DocEvents_ChangeEventHandler
    
    Public Sub UseDelegate()
          'Start Excel and then create a new workbook.
          xlApp = CreateObject("Excel.Application")
          xlBook = xlApp.Workbooks.Add()
          xlBook.Windows(1).Caption = "Uses WithEvents"
    
    'Get references to the three worksheets.
          xlSheet1 = xlBook.Worksheets.Item(1)
          xlSheet2 = xlBook.Worksheets.Item(2)
          xlSheet3 = xlBook.Worksheets.Item(3)
          CType(xlSheet1, Excel._Worksheet).Activate()
    
    'Add an event handler for the WorkbookBeforeClose event of the
          'Application object.
          EventDel_BeforeBookClose = New Excel.AppEvents_WorkbookBeforeCloseEventHandler( _
                AddressOf BeforeBookClose)
          AddHandler xlApp.WorkbookBeforeClose, EventDel_BeforeBookClose
    
    'Add an event handler for the Change event of both Worksheet 
          'objects.
          EventDel_CellsChange = New Excel.DocEvents_ChangeEventHandler( _
                AddressOf CellsChange)
          AddHandler xlSheet1.Change, EventDel_CellsChange
          AddHandler xlSheet2.Change, EventDel_CellsChange
          AddHandler xlSheet3.Change, EventDel_CellsChange
    
    'Make Excel visible and give the user control.
          xlApp.Visible = True
          xlApp.UserControl = True
       End Sub
    
    Private Sub CellsChange(ByVal Target As Excel.Range)
          'This is called when a cell or cells on a worksheet are changed.
          Debug.WriteLine("Delegate: You Changed Cells " + Target.Address + " on " + _
                            Target.Worksheet.Name())
       End Sub
    
    Private Sub BeforeBookClose(ByVal Wb As Excel.Workbook, ByRef Cancel As Boolean)
          'This is called when you choose to close the workbook in Excel.
          'The event handlers are removed and then the workbook is closed 
          'without saving changes.
          Debug.WriteLine("Delegate: Closing the workbook and removing event handlers.")
          RemoveHandler xlSheet1.Change, EventDel_CellsChange
          RemoveHandler xlSheet2.Change, EventDel_CellsChange
          RemoveHandler xlSheet3.Change, EventDel_CellsChange
          RemoveHandler xlApp.WorkbookBeforeClose, EventDel_BeforeBookClose
          Wb.Saved = True 'Set the dirty flag to true so there is no prompt to save.
       End Sub
    
  4. 프로젝트에 다른 모듈을 추가한 다음 모듈에 다음 코드를 붙여넣습니다.

       '==================================================================
       'Demonstrates Using WithEvents for Event Handling
       '==================================================================
    
    Private WithEvents xlApp As Excel.Application
       Private xlBook As Excel.Workbook
       Private WithEvents xlSheet1 As Excel.Worksheet
       Private WithEvents xlSheet2 As Excel.Worksheet
       Private WithEvents xlSheet3 As Excel.Worksheet
    
    Public Sub UseWithEvents()
          'Start Excel and then create a new workbook.
          xlApp = CreateObject("Excel.Application")
          xlBook = xlApp.Workbooks.Add()
          xlBook.Windows(1).Caption = "Uses WithEvents"
    
    'Get references to the three worksheets.
          xlSheet1 = xlBook.Worksheets.Item(1)
          xlSheet2 = xlBook.Worksheets.Item(2)
          xlSheet3 = xlBook.Worksheets.Item(3)
          CType(xlSheet1, Excel._Worksheet).Activate()
    
    'Make Excel visible and give the user control.
          xlApp.Visible = True
          xlApp.UserControl = True
       End Sub
    
    Private Sub xlApp_WorkbookBeforeClose(ByVal Wb As Excel.Workbook, _
         ByRef Cancel As Boolean) Handles xlApp.WorkbookBeforeClose
          Debug.WriteLine("WithEvents: Closing the workbook.")
          Wb.Saved = True 'Set the dirty flag to true so there is no prompt to save
       End Sub
    
    Private Sub xlSheet1_Change(ByVal Target As Excel.Range) Handles xlSheet1.Change
          Debug.WriteLine("WithEvents: You Changed Cells " + Target.Address + " on Sheet1")
       End Sub
    
    Private Sub xlSheet2_Change(ByVal Target As Excel.Range) Handles xlSheet2.Change
          Debug.WriteLine("WithEvents: You Changed Cells " + Target.Address + " on Sheet2")
       End Sub
    
    Private Sub xlSheet3_Change(ByVal Target As Excel.Range) Handles xlSheet3.Change
          Debug.WriteLine("WithEvents: You Changed Cells " + Target.Address + " on Sheet3")
       End Sub
    
  5. Module1.vb 및 Module2.vb의 맨 위에 다음을 추가합니다.

    Imports Microsoft.Office.Interop
    

    참고 Office 네임스페이스의 정확한 이름은 참조가 솔루션에 추가될 때 GAC(전역 어셈블리 캐시)에 등록된 Office PIA(기본 Interop 어셈블리)의 버전에 따라 다를 수 있습니다. 이 문에 빌드 오류 메시지가 표시되면 솔루션 탐색기 표시되는 이름을 확인한 다음(참조 아래) 이름을 적절하게 변경합니다.

  6. 솔루션 탐색기 Form1.vb를 두 번 클릭하여 폼을 디자인 보기에 표시합니다.

  7. 보기 메뉴에서 도구 상자를 선택하여 도구 상자를 표시한 다음 Form1에 두 개의 단추를 추가합니다. WithEvents 사용을 입력하여 Button1의 Text 속성을 변경합니다. 그런 다음 대리자 사용을 입력하여 Button2의 Text 속성을 변경합니다.

  8. 보기 메뉴에서 코드를 선택하여 양식의 코드 창을 표시합니다. 단추의 Click 이벤트 처리기에 다음 코드를 추가합니다.

    Private Sub Button1_Click(ByVal sender As System.Object, _
          ByVal e As System.EventArgs) Handles Button1.Click
            UseWithEvents()
        End Sub
    
    Private Sub Button2_Click(ByVal sender As System.Object, _
          ByVal e As System.EventArgs) Handles Button2.Click
            UseDelegate()
        End Sub
    

코드 테스트

  1. Ctrl+Alt+O를 눌러 출력 창을 표시합니다.

  2. F5 키를 눌러 프로그램을 빌드하고 실행합니다.

  3. 양식에서 WithEvents 사용을 클릭합니다.

    이 프로그램은 Excel을 시작한 다음 세 개의 워크시트가 있는 통합 문서를 만듭니다.

  4. 하나 이상의 워크시트의 셀에 데이터를 추가합니다. 변경 후 ENTER 키를 누릅니다. Visual Studio .NET의 출력 창을 검사하여 이벤트 처리기가 호출되었는지 확인합니다.

  5. Excel을 종료합니다.

  6. 양식에서 대리자 사용을 클릭합니다.

    프로그램이 Excel을 시작한 다음 여러 워크시트가 있는 통합 문서를 만듭니다.

  7. 하나 이상의 워크시트의 셀에 데이터를 추가합니다. 변경 후 ENTER 키를 누릅니다. Visual Studio .NET의 출력 창을 검사하여 이벤트 처리기가 호출되었는지 확인합니다.

  8. Excel을 종료한 다음 양식을 닫아 디버그 세션을 종료합니다.

문제 해결

코드를 테스트할 때 다음 오류 메시지가 표시될 수 있습니다.

interop.excel.dll'System.InvalidCastException' 형식의 처리되지 않은 예외가 발생했습니다.

추가 정보: 이러한 인터페이스가 지원되지 않음

참조

Visual Studio .NET을 사용한 Microsoft Office 개발에 대한 자세한 내용은 다음 MSDN(Microsoft Developer Network) 웹 사이트를 참조하세요.

Visual Studio를 사용한 Microsoft Office 개발

Visual Basic .NET에서 Excel을 자동화하는 방법에 대한 자세한 내용은 다음 문서 번호를 클릭하여 Microsoft 기술 자료의 문서를 확인합니다.

302094 HOWTO: Visual Basic .NET에서 Excel을 자동화하여 배열을 사용하여 범위에서 데이터를 채우거나 가져옵니다.