如何使用C#在Excel工作表上创建按钮(或形状)?我目前正在使用下面的代码,但我遇到两个问题:
有没有更好的方法来生成可以避免这两个问题的按钮?
// 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";
答案 0 :(得分:1)
您也可以尝试使用带有.Add方法的OLEObjects集合创建它,它使用与Shapes集合的AddOLEObject方法相同的参数。虽然我尝试了你在VBA中使用的AddOLEObject代码但它工作得很好。我能够进入设计模式并选择按钮,并且列没有调整大小,如下所示:
Public Sub Test()
Dim btn As Shape
Set btn = Sheets("Sheet1").Shapes.AddOLEObject("Forms.CommandButton.1", , , , , , , 1, 1, 100, 100)
End Sub
答案 1 :(得分:1)
要防止按钮在调整其大小之前移动,请设置:
btn.Placement = XlPlacement.xlFreeFloating;
作为创建按钮的替代方法,您可以使用形状:
var items = sh.Shapes;
var shape = sh.Shapes.AddShape(MsoAutoShapeType.msoShapeRectangle, left, top, width, height);
shape.Name = name;
shape.Placement = XlPlacement.xlFreeFloating;
shape.TextFrame.Characters().Text = isSubmit ? "Send" : "Cancel";
// an use this to assign a macro to it (won't happen by default as with a button)
shape.OnAction = xl.Name + "!"+ sh.Name + "." + subName;
请注意,MsoAutoShapeType
的定义不包含在常规Office.Interop DLL中。我通过使用“添加引用”的COM选项卡并添加对“Microsoft.Office 12.0对象库”的引用来找到它。