Come gestire gli eventi per Excel usando Visual Basic .NET
Riepilogo
Questo articolo dettagliato descrive come gestire gli eventi di Microsoft Office Excel 2003 e Microsoft Office Excel 2007 da un client di automazione sviluppato tramite Visual Basic .NET.
Creare un gestore eventi
È possibile creare un gestore eventi con Microsoft Visual Basic .NET 2003 o Visual Basic .NET 2002 in uno dei modi seguenti. La modalità di creazione di un gestore eventi con Visual Basic .NET dipende dal modo in cui si vuole associare il gestore eventi agli eventi:
- In genere, si crea un gestore eventi usando la parola chiave Handles con la parola chiave WithEvents. Quando si dichiara una variabile usando la parola chiave WithEvents, Visual Basic .NET si connette automaticamente agli eventi di tale oggetto in fase di esecuzione. Per gestire un evento specifico per tale oggetto, aggiungere il gestore pertinente usando l'elenco Classe e l'elenco Metodo dell'ambiente Visual Studio .NET mentre si è in visualizzazione Codice.
- Con la parola chiave AddHandler, Visual Basic .NET offre un secondo modo per gestire gli eventi. La parola chiave AddHandler e la parola chiave RemoveHandler consentono di avviare e arrestare la gestione degli eventi per un evento specifico in modo dinamico.
Creare il client di automazione .NET di Visual Basic
I passaggi seguenti illustrano come usare entrambi i modi per gestire gli eventi di Excel da un client di automazione sviluppato tramite Visual Basic .NET:
Avviare Visual Studio .NET 2002 o Visual Studio .NET 2003. Scegliere Nuovo dal menu File e quindi fare clic su Progetto. In Progetti di Visual Basic selezionare Applicazione Windows.
Per impostazione predefinita, viene creato Form1.
Aggiungere un riferimento alla libreria di oggetti di Microsoft Excel. A tal fine, attenersi alla seguente procedura:
- Scegliere Aggiungi riferimento dal menu Progetto.
- Nella scheda COM individuare Libreria oggetti di Microsoft Excel 11.0 e quindi fare clic su Seleziona.
- Fare clic su OK nella finestra di dialogo Aggiungi riferimenti per accettare le selezioni. Se viene richiesto di generare wrapper per le librerie selezionate, fare clic su Sì.
Scegliere Aggiungi modulo dal menu Progetto. Nell'elenco dei modelli selezionare Modulo e quindi fare clic su Apri. Incollare il codice seguente nel nuovo modulo:
'================================================================== '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
Aggiungere un altro modulo al progetto e quindi incollare il codice seguente nel modulo:
'================================================================== '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
Aggiungere quanto segue all'inizio di Module1.vb e Module2.vb:
Imports Microsoft.Office.Interop
Nota Il nome esatto per lo spazio dei nomi di Office può variare a seconda della versione dell'assembly di interoperabilità primario di Office registrato nella Global Assembly Cache (GAC) quando il riferimento viene aggiunto alla soluzione. Se viene visualizzato un messaggio di errore di compilazione in questa istruzione, controllare il nome visualizzato in Esplora soluzioni (in Riferimenti) e quindi modificare il nome in base alle esigenze.
In Esplora soluzioni fare doppio clic su Form1.vb per visualizzare il modulo in visualizzazione Struttura.
Nel menu Visualizza selezionare Casella degli strumenti per visualizzare la casella degli strumenti e quindi aggiungere due pulsanti a Form1. Modificare la proprietà Text di Button1 digitando Use WithEvents. Modificare quindi la proprietà Text di Button2 digitando Use Delegates .Then change the Text property of Button2 by typing Use Delegates.
Scegliere Codice dal menu Visualizza per visualizzare la finestra Codice per il modulo. Aggiungere il codice seguente ai gestori eventi Click per i pulsanti:
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
Eseguire il test del codice
Premere CTRL+ALT+O per visualizzare la finestra Output.
Premere F5 per compilare ed eseguire il programma.
Nel modulo fare clic su Usa conEventi.
Il programma avvia Excel e quindi crea una cartella di lavoro con tre fogli di lavoro.
Aggiungere dati alle celle in uno o più fogli di lavoro. Premere INVIO dopo ogni modifica. Esaminare la finestra Output in Visual Studio .NET per verificare che vengano chiamati i gestori eventi.
Uscire da Excel.
Nel modulo fare clic su Usa delegati.
Anche in questo caso, il programma avvia Excel e quindi crea una cartella di lavoro con più fogli di lavoro.
Aggiungere dati alle celle in uno o più fogli di lavoro. Premere INVIO dopo ogni modifica. Esaminare la finestra Output in Visual Studio .NET per verificare che vengano chiamati i gestori eventi.
Chiudere Excel e quindi chiudere il modulo per terminare la sessione di debug.
Risoluzione dei problemi
Quando si testa il codice, è possibile che venga visualizzato il messaggio di errore seguente:
Eccezione non gestita di tipo 'System.InvalidCastException' in interop.excel.dll
Informazioni aggiuntive: Nessuna interfaccia supportata
Riferimenti
Per altre informazioni sullo sviluppo di Microsoft Office con Visual Studio .NET, visitare il seguente sito Web Microsoft Developer Network (MSDN):
Sviluppo di Microsoft Office con Visual Studio
Per altre informazioni sull'automazione di Excel da Visual Basic .NET, fare clic sul numero dell'articolo della Microsoft Knowledge Base seguente:
302094 HOWTO: Automatizzare Excel da Visual Basic .NET per compilare o ottenere dati in un intervallo usando matrici