开发者

Excel.Application.SelectionChange fires only once

开发者 https://www.devze.com 2023-03-07 12:38 出处:网络
I\'m getting only the first event notification, and nothing happens after. Any idea开发者_StackOverflow中文版s?

I'm getting only the first event notification, and nothing happens after. Any idea开发者_StackOverflow中文版s?

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.


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 += ....
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号