c# excel create a button on excel worksheet

Rakesh kumar 106 Reputation points
2022-05-16T17:18:29.56+00:00

I am trying to add a button on an excel worksheet. Could you please provide a code and its not working from my end
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");
}
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,836 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,286 questions
.NET Runtime
.NET Runtime
.NET: Microsoft Technologies based on the .NET software framework.Runtime: An environment required to run apps that aren't compiled to machine language.
1,125 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jack J Jun 24,296 Reputation points Microsoft Vendor
    2022-05-17T02:36:36.427+00:00

    @Rakesh kumar , based on my test, you could try the following code to add a button to your excel.

        Excel.Application xlApp = new Excel.Application();  
        Excel.Workbook xlBook = xlApp.Workbooks.Open(@"path");  
        Excel.Worksheet worksheet = xlBook.Worksheets[1];  
        Excel.Shape btn2 = worksheet.Shapes.AddFormControl(Excel.XlFormControl.xlButtonControl, 150, 5, 150, 22);  
        btn2.Name = "Update";  
        btn2.OLEFormat.Object.Caption = "UpdateButton";  
          
        xlBook.Save();  
        xlBook.Close();  
    

    Result:

    202561-image.png

    Best Regards,
    Jack


    If the answer is the right solution, please click "Accept Answer" and upvote it.If you have extra questions about this answer, please click "Comment".

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


0 additional answers

Sort by: Most helpful