Excel.Application.SelectionChange仅触发一次 [英] Excel.Application.SelectionChange fires only once

查看:393
本文介绍了Excel.Application.SelectionChange仅触发一次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只收到第一个事件通知,此后什么也没发生。
有什么想法吗?

UPD:我发现了一件奇怪的事。我的事件处理程序代码如下:

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.

推荐答案

由于使用COM Interop跟踪事件处理程序的方式,垃圾收集器可以清除RCW,从而阻止您接收事件。

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

class ThisAddin
{
    WorkBook _workbook;

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

这篇关于Excel.Application.SelectionChange仅触发一次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆