2009-08-05 79 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