我正在开发一个 excel 插件。当我的功能区加载时,我添加了一个带有按钮的单元格上下文菜单。我将处理程序附加到按钮的单击事件以选择文件。当我运行 excel 时,它适用于默认的第一张工作表。但是,如果我打开一个新工作表,单击时没有任何反应。为什么?
我的色带加载功能:
private void Ribbon1_Load(object sender, RibbonUIEventArgs e)
{
Helper.SetVar(Globals.ThisAddIn.Application, Globals.Factory);
}
我有几个在那个引用中添加了一个工具箱 dll。所以这是我的 Toolbox dll 的公共静态 Helper 类中的 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;
}
}