Excel.Application.SelectionChange fires only once

放肆的年华 提交于 2019-12-24 09:47:59

问题


I'm getting only the first event notification, and nothing happens after. Any ideas?
UPD: I've found a strange thing. My code for event handler looked like this:

                    var cell = range.Cells[1, 1];
                    var rangeName = cell.Address[false, false, XlReferenceStyle.xlA1, Type.Missing, Type.Missing];

I've changed it in this way, adding explicit type cast:

                    var cell = (Range)range.Cells[1, 1];
                    var rangeName = cell.Address[false, false, XlReferenceStyle.xlA1, Type.Missing, Type.Missing];

And now my event handler gets called several times, and only then stops getting called.


回答1:


Because of the way event handlers are tracked with COM Interop, the garbage collector can clean up the RCW's which stops you from receiving events.

Make sure you keep a reference to the object that has the event handler, for instance instead of writing:

Application.CurrentWorkbook.SelectionChanged += ....

write

class ThisAddin
{
    WorkBook _workbook;

    void AddinLoaded()
    {
        _workbook.SelectionChanged += ....
    }
}


来源:https://stackoverflow.com/questions/6092618/excel-application-selectionchange-fires-only-once

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!