如何从Delphi修改现有 excel形状的文本?
我可以创建一个 new 形状并设置其文本
procedure TForm1.Button1Click(Sender: TObject);
var
excel, xlShape : variant;
begin
olecontainer1.CreateObject('Excel.Application',false);
excel := olecontainer1.OleObject;
excel.workbooks.open('C:\test.xls');
XlShape := excel.application.worksheets[1].Shapes.AddShape(1, 0, 0, 450, 200);
XlShape.textframe.characters.text:='new shape created from Delphi';
但是如果形状已经存在,我该如何选择它来改变它的文本属性?类似的东西:
excel.application.worksheets[1].Shapes('shape1').textframe.characters.text := 'This gives error';
答案 0 :(得分:1)
试试此代码
procedure TForm1.ButtonClick(Sender: TObject);
var
excel, xlShape : variant;
begin
olecontainer1.CreateObject('Excel.Application',false);
excel := olecontainer1.OleObject;
excel.workbooks.open('C:\test.xls');
XlShape:=excel.ActiveSheet.Shapes.Item(1);// or like this .Item('Rectangle 1');
if VarIsEmpty(xlShape) then
begin
XlShape := excel.application.worksheets[1].Shapes.AddShape(1, 0, 0, 450, 200);
XlShape.textframe.characters.text:='new shape created from Delphi';
end
else
ShowMessage(XlShape.textframe.characters.text);
excel.activeworkbook.close;
xlShape:=Unassigned;
excel:=Unassigned;
OleContainer1.DestroyObject;
end;
答案 1 :(得分:0)
XlShape := excel.application.worksheets[1].Shapes.AddShape(1, 0, 0, 450, 200);
XlShape.Name := "mycustomshape";
因此,当您知道形状的名称时,可以使用名称
来引用它excel.application.worksheets[1].Shapes('mycustomshape').textframe.characters.text := 'This doesnt gives error';
OR,您可以使用索引(基于0)来引用它。我假设它是工作表中的第一个形状对象。
excel.application.worksheets[1].Shapes(0).textframe.characters.text := 'This doesnt gives error';
编辑:我不确定Delphi在语法方面有何不同
看看是否使用方括号(而不是常规括号)
excel.application.worksheets[1].Shapes['mycustomshape'].textframe.characters.text := 'This doesnt gives error';
OR
excel.application.worksheets[1].Shapes[0].textframe.characters.text := 'This doesnt gives error';