简体   繁体   中英

Excel Interop Worksheet SelectionChange not attaching on the open work book

In excel 2010, using excel dna and excel interop I am attaching to selection change of each work sheet.
I am using app.WorkbookActivate and also trying to enumerate the open workbooks.

It works fine for new books / sheets via workbook activate. However - For the open workbook its not attaching. There are no errors , it just does not work

It will attach to that original workbook if you open a new work book and then toggle back

Anyone know why?

Here is the code.

using ExcelDna.Integration;
using XL = Microsoft.Office.Interop.Excel; 

....
/// in an init method
//add event listeners to open work books and on new work books
XL.Application xlapp = (XL.Application)ExcelDnaUtil.Application;
xlapp.WorkbookActivate += Xlapp_WorkbookActivate;
ListenOnOpenWorkBooks();

private static void ListenOnOpenWorkBooks()
{
    XL.Application xlapp = (XL.Application)ExcelDnaUtil.Application;
    foreach (XL.Workbook wb in xlapp.Workbooks)
    {
        foreach (XL.Worksheet s in wb.Sheets)
        {
            s.SelectionChange += S_SelectionChange;
        }
    }
}

private static void Xlapp_WorkbookActivate(XL.Workbook Wb)
{
    //TODOL check if already listening
    foreach (XL.Worksheet s in Wb.Sheets)
    {
        s.SelectionChange += S_SelectionChange;
    }
}

private static void S_SelectionChange(XL.Range range)
{
     ///do something
}

I found work around that I can listen to all sheet changes using an application event handler instead. Posting here in case anyone else experiences this issue.

XL.Application xlapp = (XL.Application) ExcelDnaUtil.Application;
xlapp.SheetSelectionChange += Xlapp_SheetSelectionChange;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM