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 はイベントを処理する 2 番目の方法を提供します。 AddHandler キーワードと RemoveHandler キーワードを使用すると、特定のイベントのイベント処理を動的に開始および停止できます。
Visual Basic .NET Automation クライアントを作成する
次の手順では、Visual Basic .NET を使用して開発された Automation クライアントから Excel イベントを処理する方法を示します。
Visual Studio .NET 2002 または Visual Studio .NET 2003 を起動します。 [ファイル] メニューの [新規作成] をクリックし、[プロジェクト] をクリックします。 Visual Basic プロジェクトで、Windows アプリケーションを選択します。
既定では、Form1 が作成されます。
Microsoft Excel オブジェクト ライブラリへの参照を追加します。 これを行うには、次の手順を実行します。
- [ プロジェクト] メニューの [ 参照の追加] をクリックします。
- [COM] タブで、Microsoft Excel 11.0 オブジェクト ライブラリを探し、[選択] をクリックします。
- [参照の追加] ダイアログ ボックスで [OK] をクリックして、選択内容を受け入れます。 選択したライブラリのラッパーを生成するように求めるメッセージが表示されたら、[ はい] をクリックします。
[ プロジェクト ] メニューの [ モジュールの追加] を選択します。 テンプレートの一覧で [ モジュール] を選択し、[ 開く] をクリックします。 新しいモジュールに次のコードを貼り付けます。
'================================================================== '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
別のモジュールをプロジェクトに追加し、次のコードをモジュールに貼り付けます。
'================================================================== '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
Module1.vb と Module2.vb の両方の上部に次を追加します。
Imports Microsoft.Office.Interop
メモ Office 名前空間の正確な名前は、参照がソリューションに追加されるときにグローバル アセンブリ キャッシュ (GAC) に登録されている Office プライマリ相互運用機能アセンブリ (PIA) のバージョンによって異なる場合があります。 このステートメントに対してビルド エラー メッセージが表示された場合は、ソリューション エクスプローラー ([参照] の下) に表示される名前を確認し、必要に応じて名前を変更します。
ソリューション エクスプローラーで Form1.vb をダブルクリックして、デザイン ビューにフォームを表示します。
[ 表示 ] メニューの [ ツールボックス] を選択してツールボックスを表示し、Form1 に 2 つのボタンを追加します。 「WithEvents を使用する」と入力して、Button1 の Text プロパティを変更します。 次に、「デリゲートを使用する」と入力して、Button2 の Text プロパティを変更します。
[ 表示 ] メニューの [ コード ] を選択して、フォームの [コード] ウィンドウを表示します。 ボタンの 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
コードをテストする
Ctrl キーを押しながら Alt キーを押しながら O キーを押すと、[出力] ウィンドウが表示されます。
F5 キーを押してビルドし、プログラムを実行します。
フォームで、[ WithEvents の使用] をクリックします。
プログラムは Excel を起動し、3 つのワークシートを含むブックを作成します。
1 つまたは複数のワークシートのセルにデータを追加します。 変更後に Enter キーを押します。 Visual Studio .NET の [出力] ウィンドウを調べて、イベント ハンドラーが呼び出されることを確認します。
Excel を終了します。
フォームで、[代理人の 使用] をクリックします。
繰り返しになりますが、プログラムは Excel を起動し、複数のワークシートを含むブックを作成します。
1 つまたは複数のワークシートのセルにデータを追加します。 変更後に Enter キーを押します。 Visual Studio .NET の [出力] ウィンドウを調べて、イベント ハンドラーが呼び出されることを確認します。
Excel を終了し、フォームを閉じてデバッグ セッションを終了します。
トラブルシューティング
コードをテストすると、次のエラー メッセージが表示される場合があります。
'System.InvalidCastException' 型のハンドルされない例外がinterop.excel.dllで発生しました
追加情報: そのようなインターフェイスはサポートされていません
関連情報
Visual Studio .NET を使用した Microsoft Office 開発の詳細については、次の Microsoft Developer Network (MSDN) Web サイトを参照してください。
Visual Studio を使用した Microsoft Office Development
Visual Basic .NET から Excel を自動化する方法の詳細については、次の記事番号をクリックして、Microsoft サポート技術情報の記事を表示してください。
302094 HOWTO: Visual Basic .NET から Excel を自動化して、配列を使用して範囲内のデータを入力または取得する