2014-11-03 113 views
1

我想在excel工作表上添加一个按钮。 根据互联网的例子,我试图做下面的代码。c#excel在excel工作表上创建一个按钮

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不包含按钮 我应该包括使用按钮属性

预先感谢什么参考。

+0

wrkSheet.Buttons();你可以试试wrkSheet.Buttons; ? – Eric 2014-11-03 08:24:48

+0

工作表没有按钮功能。要使用工作表按钮,我需要包含哪些参考? – user3289230 2014-11-04 12:12:28

回答

2

据我所知,Excel.Buttons和Excel.Button不存在。相反,它建议正确的引用是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

+0

谢谢你的回复。我包括Microsoft.Office.Tools.Excel.v4.0.Utilities.dll,但我找不到Microsoft.Office.Tools.Excel.Controls。我不知道我错过了什么。 – user3289230 2014-11-04 12:22:40

+0

我找到了!对不起,我只是失明。谢谢! – user3289230 2014-11-04 12:31:26

+0

OH。我找不到worksheet.Controls ...我需要包含哪些参考?我将工作表声明为Microsoft.Office.Interop.Excel.Worksheet。 – user3289230 2014-11-04 12:45:19

0

使用Lesley.Oakey的方法需要您使用Microsoft的VSTO extension methods是。 Tools.Office.Excel。

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

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

Add excel vba code to button using c#