2009-08-05 5 views
2

Comment puis-je modifier le texte d'une forme excel existant de Delphi?Modifier une forme Excel à partir de Delphi

Je peux créer une nouvelle forme et définir son texte

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

Mais si la forme existe déjà, comment puis-je sélectionner pour changer sa propriété de texte? Quelque chose comme:

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

Souvent, la meilleure façon de trouver comment faire les choses avec OLE automation est d'enregistrer une macro dans Excel, puis regardez le code qu'il génère. Convertir ceci en syntaxe Delphi est alors raisonnablement facile. –

Répondre

1

Essayez ce 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; 
+0

Merci! excel.ActiveSheet.Shapes.Item (1) a fait l'affaire. –

0
XlShape := excel.application.worksheets[1].Shapes.AddShape(1, 0, 0, 450, 200); 
XlShape.Name := "mycustomshape"; 

Donc, quand vous connaissez le nom de la forme, vous pouvez vous référer avec le nom

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

OU, vous pouvez vous référer à elle index à l'aide (0 basé). Je suppose que c'est le premier objet de forme dans la feuille de calcul.

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

EDIT: Je ne suis pas sûr de la différence de Delphi en termes de syntaxe.
Voir si vous utilisez crochets (au lieu du support régulier) fonctionne

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

OU

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

Merci, j'ai essayé les deux options (en utilisant le nom et l'index) mais j'ai l'erreur "Membre introuvable". Est-ce que je manque quelque chose? –

+0

Voir si l'utilisation de crochets aide. C'est ce que j'imagine Delphi façon d'indexer dans une collection. – shahkalpesh

Questions connexes