How can I create a button (or a shape) on an Excel worksheet using C#? I am currently doing it with the code below, but I encounter two problems:
- the button gets moved when the columns to its left are resized
- the button does not respond when you select or right-click it, so there is no obvious way for a user to manually delete it from the sheet after it's been auto-added
EDIT: As Lance reminds me, #2 is due to my own misunderstanding -- in order to delete form buttons, you have to use Design Mode, which you can access through the Developer tab on the ribbon bar.
Is there a better way of generating buttons that will avoid these two problems?
// prior code is equivalent to:
// var name = "MyButton";
// var row = 2;
// var buttonCol = 5;
Range cell = sh.Cells[row, buttonCol];
var width = cell.Width;
var height = 25;
var left = cell.Left;
var top = Math.Max(cell.Top + cell.Height - height, 0);
var items = sh.Shapes;
var btn = items.AddOLEObject("Forms.CommandButton.1",
null, null, null, null,
null, null,
left, top, width, height);
btn.Name = name;
OLEObject sheetBtn = sh.OLEObjects(name);
sheetBtn.Object.Caption = isSubmit ? "Send" : "Cancel";