Excel添加事件在打开新工作表后停止触发

我正在开发一个Excel插件。当我的function区加载时,我添加一个单元格上下文菜单,并在其中包含一个button。 我附加一个处理程序到button的点击事件来select一个文件。 当我运行Excel时,它可以正常工作。 但是,如果我打开一个新的表,当我点击时没有任何反应。 为什么?

我的色带加载function:

private void Ribbon1_Load(object sender, RibbonUIEventArgs e) { Helper.SetVar(Globals.ThisAddIn.Application, Globals.Factory); } 

我有几个添加在该参考工具箱的DLL。 所以这里是我的工具箱dll的公共静态助手类中的setVar函数:

  public static void SetVar(Excel.Application appSource, Microsoft.Office.Tools.Excel.ApplicationFactory FactorySource) { if(path=="") { string fullPath = typeof(Helper).Assembly.CodeBase; string theDirectory = Path.GetDirectoryName(fullPath); path = new Uri(theDirectory).LocalPath; } if (app == null) app = appSource; if (Factory == null) Factory = FactorySource; rightClickMenu(); } 

它调用rightClickMenu这是:

  public static void rightClickMenu() { bool val = false; removeRightClickMenu(ref val); Office.CommandBarPopup ctrl = (Office.CommandBarPopup)app.CommandBars["Cell"].Controls.Add(Type: Office.MsoControlType.msoControlPopup, Before: 1); ctrl.Caption = "Perso"; Office.CommandBarButton btn = (Office.CommandBarButton)ctrl.Controls.Add(Type: Office.MsoControlType.msoControlButton); btn.Caption = "Sélectionner un fichier"; btn.Click += new Office._CommandBarButtonEvents_ClickEventHandler(selectFile); } 

点击处理程序是:

  public static void selectFile(Office.CommandBarButton ctrl, ref bool Cancel) { OpenFileDialog openFileDialog1 = new OpenFileDialog(); openFileDialog1.InitialDirectory = "c:\\"; openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { var filename = openFileDialog1.FileName; //var filename = openFileDialog1.SafeFileName; app.ActiveCell.Value = filename; } }