【问题标题】:Modify an Excel Shape from Delphi从 Delphi 修改 Excel 形状
【发布时间】:2010-11-16 21:20:57
【问题描述】:

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

但是如果形状已经存在,我该如何选择它来改变它的文本属性呢?比如:

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

【问题讨论】:

  • 通常,了解如何使用 OLE 自动化执行操作的最简单方法是在 Excel 中记录一个宏,然后查看它生成的代码。然后将其转换为 Delphi 语法相当容易。

标签: delphi excel vba


【解决方案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;

【讨论】:

    【解决方案2】:
    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';
    

    【讨论】:

    • 谢谢,我尝试了这两个选项(使用名称和索引),但我收到错误“未找到成员”。我错过了什么吗?
    • 看看使用方括号是否有帮助。我猜这就是 Delphi 索引集合的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-11-05
    • 1970-01-01
    相关资源
    最近更新 更多