c#excel在excel工作表上创build一个button

我想在Excel工作表上添加一个button。 根据互联网的例子,我试图做下面的代码。

using Excel = Microsoft.Office.Interop.Excel; using VBIDE = Microsoft.Vbe.Interop; private static void excelAddButtonWithVBA() { Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlBook = xlApp.Workbooks.Open(@"PATH_TO_EXCEL_FILE"); Excel.Worksheet wrkSheet = xlBook.Worksheets[1]; Excel.Range range; try { //set range for insert cell range = wrkSheet.get_Range("A1:A1"); //insert the dropdown into the cell Excel.Buttons xlButtons = wrkSheet.Buttons(); Excel.Button xlButton = xlButtons.Add((double)range.Left, (double)range.Top, (double)range.Width, (double)range.Height); //set the name of the new button xlButton.Name = "btnDoSomething"; xlButton.Text = "Click me!"; xlButton.OnAction = "btnDoSomething_Click"; buttonMacro(xlButton.Name, xlApp, xlBook, wrkSheet); } catch (Exception ex) { Debug.WriteLine(ex.Message); } xlApp.Visible = true; 

}

但它一直说Excel不包含button我应该包括什么参考使用Button属性

提前致谢。

据我所知,Excel.Buttons和Excel.Button不存在。 而是build议正确的引用是Microsoft.Office.Tools.Excel.Controls.Button(而不是像您使用的Microsoft.Office.Interop.Excel)。 这个例子来自下面的源代码

  Excel.Application xlApp = new Excel.Application(); Excel.Workbook xlBook = xlApp.Workbooks.Open(@"PATH_TO_EXCEL_FILE"); Excel.Worksheet worksheet = xlBook.Worksheets[1]; Excel.Range selection = Globals.ThisAddIn.Application.Selection as Excel.Range; if (selection != null) { Microsoft.Office.Tools.Excel.Controls.Button button = new Microsoft.Office.Tools.Excel.Controls.Button(); worksheet.Controls.AddControl(button, selection, "Button"); } 

源:在运行时将应用程序级别项目中的控件添加到工作表http://msdn.microsoft.com/en-us/library/cc442817.aspx

使用Lesley.Oakey的方法要求您在Microsoft.Tools.Office.Excel中使用VSTO扩展方法 。

如果您不使用它们,那么您将无法访问Worksheet.Controls属性。

最好只使用Worksheet.Shapes容器并添加一个新的形状。 这里有一个伟大的post:

使用c#添加excel vba代码到button