我正在尝试以编程方式向工作表添加一个新按钮。
我在功能区中创建了一个新按钮。单击时,该按钮应在工作表上创建一个新按钮并为其分配一些宏/功能。
private void createCheckFileButton_Click(object sender, RibbonControlEventArgs e) // This is the ribbon button.
{
Microsoft.Office.Interop.Excel.Worksheet worksheet = (Microsoft.Office.Interop.Excel.Worksheet)Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet;
Microsoft.Office.Tools.Excel.Worksheet vstoSheet = Globals.Factory.GetVstoObject(worksheet);
// Add button to worksheet.
Microsoft.Office.Tools.Excel.Controls.Button button1 = this.Controls.AddButton(this.Range["A1"], "button1");
button1.Text = "OK";
}
我遵循了THIS,但不知何故对我来说它说“类型或命名空间'Controls'在Microsoft.Office.Tools.Excel中不存在。”
我不知道如何解决这个问题。我已通过 NuGet 包管理器安装了 Microsoft.Office.Interop.Excel。我还需要什么吗?
确保您已安装包含 Microsoft.Office.Tools.Excel 的正确 NuGet 包。
安装包 Microsoft.VisualStudio.Tools.Office
private void createCheckFileButton_Click(object sender, RibbonControlEventArgs e)
{
Microsoft.Office.Interop.Excel.Worksheet worksheet =
(Microsoft.Office.Interop.Excel.Worksheet)Globals.ThisAddIn.Application.ActiveWorkbook.ActiveSheet;
Microsoft.Office.Tools.Excel.Worksheet vstoSheet =
Globals.Factory.GetVstoObject(worksheet);
var button1 = vstoSheet.Controls.AddButton(vstoSheet.Range["A1"], "button1");
button1.Text = "OK";
button1.Click += new EventHandler(Button1_Click);
}
// Example event handler for the button click event.
private void Button1_Click(object sender, EventArgs e)
{
MessageBox.Show("Button on worksheet clicked!");
}