Home » excel » c# excel create a button on excel worksheet

c# excel create a button on excel worksheet

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am trying to add a button on an excel worksheet.
According to the example from internet, I am trying to do following code.

  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;

}

But it keeps saying Excel does not contain Button
What reference should I include to use Button property

Thanks in advance.

How to&Answers:

As far as I can tell, Excel.Buttons and Excel.Button do not exist. Instead it is suggested that the correct reference is Microsoft.Office.Tools.Excel.Controls.Button (not Microsoft.Office.Interop.Excel as you are using). This example is from the source below

    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");
    }

Source: Adding Controls to a Worksheet at Run Time in an Application-Level Project http://msdn.microsoft.com/en-us/library/cc442817.aspx

Answer:

Using Lesley.Oakey’s method requires you to be using the VSTO extension methods in Microsoft.Tools.Office.Excel.

If you are not using them, then you will not be able to access the Worksheet.Controls property.

Best to just use the Worksheet.Shapes container and add a new shape. There’s a great post about this here:

Add excel vba code to button using c#