Ama
Ama

Reputation: 1565

Unable to perform simple Excel.Application event handling

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:

.

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:

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

Answers (1)

Ama
Ama

Reputation: 1565

For whoever might be interested:

MyEvents.vb

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

ThisAddIn.vb

Public Class ThisAddIn

    Private Sub ThisAddIn_Startup() Handles Me.Startup
        MyEvents.StartEvents(Globals.ThisAddIn.Application)
    End Sub

End Class

Upvotes: 1

Related Questions