共用方式為


如何使用 Visual Basic .NET 處理 Excel 的事件

摘要

此逐步文章說明如何從您使用 Visual Basic .NET 開發的自動化用戶端處理 Microsoft Office Excel 2003 和 Microsoft Office Excel 2007 事件。

建立事件處理常式

您可以使用下列其中一種方式,使用 Microsoft Visual Basic .NET 2003 或 Visual Basic .NET 2002 建立事件處理常式。 使用 Visual Basic .NET 建立事件處理常式的方式取決於您要如何將事件處理常式與事件產生關聯:

  • 一般而言,您會使用 Handles 關鍵字搭配 WithEvents 關鍵字來建立事件處理常式。 當您使用 WithEvents 關鍵字宣告變數時,Visual Basic .NET 會在執行時間自動連接到該物件的事件。 若要處理該物件的特定事件,請在 [程式碼] 檢視中使用 Visual Studio .NET 環境的 [類別] 清單和 [方法] 清單來新增相關的處理常式。
  • Visual Basic .NET 使用 AddHandler 關鍵字,提供第二種方式來處理事件。 AddHandler 關鍵字和 RemoveHandler 關鍵字可讓您以動態方式啟動和停止特定事件的事件處理。

建立 Visual Basic .NET Automation 用戶端

下列步驟示範如何使用任一種方式,從使用 Visual Basic .NET 開發的自動化用戶端處理 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 命名空間的確切名稱可能會根據 PIA (PIA) 的 Office 主要 Interop 元件版本而有所不同,當參考新增至解決方案時, (GAC) 。 如果您在此語句上收到建置錯誤訊息,請檢查名稱,因為它出現在 [參考]) 下的 [方案總管 (中],然後視需要變更名稱。

  6. 在方案總管中,按兩下Form1.vb以在 [設計檢視] 中顯示表單。

  7. 在 [ 檢視] 功能表上,選取 [ 工具箱 ] 以顯示 [工具箱],然後將兩個按鈕新增至 Form1。 輸入 Use 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 開發的其他資訊,請造訪下列 Microsoft Developer Network (MSDN) 網站:

使用 Visual Studio 進行 Microsoft Office 開發

如需從 Visual Basic .NET 自動化 Excel 的其他資訊,請按一下下列文章編號以檢視 Microsoft 知識庫中的文章:

302094 操作說明:使用陣列從 Visual Basic .NET 將 Excel 自動化以填入或取得範圍中的資料