views:

695

answers:

2

How can I modify the text of an existing excel shape from Delphi?

I can create a new shape and set its text

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

But if the shape already exists, how can I select it to change its text property? Something like:

excel.application.worksheets[1].Shapes('shape1').textframe.characters.text := 'This gives error';
A: 
XlShape := excel.application.worksheets[1].Shapes.AddShape(1, 0, 0, 450, 200); 
XlShape.Name := "mycustomshape";

So, when you know the name of the shape, you can refer to it with the name

excel.application.worksheets[1].Shapes('mycustomshape').textframe.characters.text := 'This doesnt gives error';

OR, you can refer to it using index (0 based). I am assuming that it is the 1st shape object in the worksheet.

excel.application.worksheets[1].Shapes(0).textframe.characters.text := 'This doesnt gives error';

EDIT: I am not sure how Delphi is different in terms of syntax.
See if using square bracket (instead of regular bracket) works

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';
shahkalpesh
Thanks, I tried both options (using name and index) but I get the error "Member not found". Am I missing something?
Carlos Torres
See if using square brackets help. This is what I guess Delphi way of indexing into a collection.
shahkalpesh
+1  A: 

Try this code

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;
Thanks! excel.ActiveSheet.Shapes.Item(1) did the trick.
Carlos Torres