Search code examples
c#excelvstoexcel-addins

Add new button to worksheet with Excel Add-in


I am trying to programatically add a new button to worksheet.

I have create a new button in ribbon. On click, that button should create a new button on the worksheet and assign some macro/functionality to it.

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

    }

I followed THIS but somehow for me it says that "The type or namespace 'Controls' does not exist in Microsoft.Office.Tools.Excel."

I am not sure how to fix this. I have installed the Microsoft.Office.Interop.Excel through NuGet package manager. Is there something else I need?


Solution

  • Create new Add-In project: enter image description here

    Ensure your project has references: enter image description here

    Code which adds button to Excel sheet:

    using Microsoft.Office.Tools.Ribbon;
    using Microsoft.Office.Interop.Excel;
    
    var ws1 = Globals.ThisAddIn.Application.ActiveWorkbook.Worksheets[1];
    Microsoft.Office.Tools.Excel.Worksheet worksheet = Globals.Factory.GetVstoObject(ws1);
    
    if (Globals.ThisAddIn.Application.Selection is Range selectedCell)
    {
        Microsoft.Office.Tools.Excel.Controls.Button excelButton = new Microsoft.Office.Tools.Excel.Controls.Button();
        excelButton.Text = @"Excel button";
    
        worksheet.Controls.AddControl(excelButton, selectedCell, "MyButton");
    }
    

    Result: enter image description here