Reputation: 1565
I am new to Events Handling on a VSTO. I did som extensive reserch online, including digging the Microsoft documentation and trying to apply a practical but old example from the support center.
The problem with this example is that it does not work on the Excel.Application
instance which calls ThisAddin
. So I tried one of my own:
MyEvents.vb
, which contains the following:.
Imports Microsoft.Office.Interop.Excel
Module MyEvents
WithEvents ThisApp As Excel.Application '= Globals.ThisAddIn.Application
Private Sub ThisApp_SheetBeforeDoubleClick(Sh As Object, Target As Range, ByRef Cancel As Boolean) Handles ThisApp.SheetBeforeDoubleClick
Dim FromSheet As Excel.Worksheet = Sh
System.Diagnostics.Debug.Print("Event triggered: ThisApp_SheetBeforeDoubleClick in {0} or {1}", FromSheet, Target.Worksheet.Name)
End Sub
Private Sub ThisApp_WorkbookActivate(Wb As Workbook) Handles ThisApp.WorkbookActivate
System.Diagnostics.Debug.Print("Event triggered: ThisApp_WorkbookActivate")
End Sub
End Module
When I compile, open a new workbook and try double clicking or activating another workbook: nothing happens. I must be missing something obvious.. I feel I lack some fundamentals on events handling via VSTO, and I would be glad to be proposed some extra reading on the matter.
For example:
WithEvents ThisApp As Excel.Application =
Globals.ThisAddIn.Application
or just WithEvents ThisApp As
Excel.Application
? i.e. can I bind the event to a given object (Application, Worksheet, etc) or do I need to check the caller in my Sub
once the event has been triggered, and why?Module
in a Namespace
? Does/can it be linked to a Shared WithEvents ThisApp
?Shared Class
? Will it run my handling Sub
as many time as I currently have instances of that Class
?As one can see, I am a little lost here.. I wanted to run all these tests by myself but I am not event able to do something which should be pretty basic.. !
Upvotes: 0
Views: 298
Reputation: 1565
For whoever might be interested:
Imports Microsoft.Office.Interop.Excel
Module MyEvents
WithEvents ThisApp As Excel.Application
'Start listening to Events thrown by ExcelApp
Sub StartEvents(ExcelApp as Excel.Application)
ThisApp = ExcelApp
End Sub
Private Sub ThisApp_SheetBeforeDoubleClick(Sh As Object, Target As Range, ByRef Cancel As Boolean) Handles ThisApp.SheetBeforeDoubleClick
Dim FromSheet As Excel.Worksheet = Sh
System.Diagnostics.Debug.Print("Event triggered: ThisApp_SheetBeforeDoubleClick in {0} or {1}", FromSheet, Target.Worksheet.Name)
End Sub
Private Sub ThisApp_WorkbookActivate(Wb As Workbook) Handles ThisApp.WorkbookActivate
System.Diagnostics.Debug.Print("Event triggered: ThisApp_WorkbookActivate")
End Sub
End Module
Public Class ThisAddIn
Private Sub ThisAddIn_Startup() Handles Me.Startup
MyEvents.StartEvents(Globals.ThisAddIn.Application)
End Sub
End Class
Upvotes: 1