簡體   English   中英

從Delphi修改Excel形狀

[英]Modify an Excel Shape from Delphi

如何從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';

試試這個代碼

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

編輯:我不確定Delphi在語法上有何不同。
查看是否使用方括號 (而不是常規括號)是否有效

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

要么

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM