2009-08-05 83 views
2

如何从Delphi中修改现有 excel形状的文本?从Delphi修改Excel形状

我可以创建一个新形状并设置其文本

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

但是,如果形状已经存在,我怎么能选择它来改变其text属性?喜欢的东西:

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

通常情况下,最简单的方法找出如何做事OLE自动化是在Excel中记录宏,然后查看它生成的代码。将其转换为Delphi语法非常简单。 – 2009-08-05 03:43:04

回答

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

或者,您可以使用索引来引用它(0基于)。我假设它是工作表中的第一个形状对象。

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

编辑:我不知道德尔福是如何在语法方面不同。
看看是否使用括号(而不是常规的支架)工作

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

谢谢,我试过两个选项(使用名称和索引),但我得到错误“找不到成员”。我错过了什么吗? – 2009-08-05 14:57:09

+0

查看使用方括号是否有帮助。这是我想Delphi的索引方式进入一个集合。 – shahkalpesh 2009-08-06 03:45:04