运行带有嵌套var访问的Delphi程序后,Excel.exe仍然会被加载

我遇到了一个奇怪的问题, 为什么excel.exe在运行delphi客户端自动化程序后仍然被加载? 题。 问题是更深入一步。

我已经得到了Delphi 7编写的代码,并将其升级到XE2。 这样做后,我有同样的问题在XE2和build议的解决scheme在简单的testing应用程序工作,只要我使用这些行Excel.exe保持加载程序退出后:

fExcel: Variant; // Tried both as a field of a class and global variable fExcel := CreateOleObject('Excel.Application'); try fExcel.Workbooks.Open(srcPathName); fExcel.DisplayAlerts := False; ... // Offending lines fExcel.ActiveWorkBook.ActiveSheet.Range[ // fExcel.ActiveWorkBook.ActiveSheet.Cells[3, 2], // fExcel.ActiveWorkBook.ActiveSheet.Cells[3+i,1+XL_PT_Tip_FieldCount] // ].Formula := VarArr; // ... fExcel.ActiveWorkBook.SaveAs(tgtPathName, -4143, '', '', False, False); fExcel.ActiveWorkBook.Close; finally fExcel.Application.Quit; fExcel.Quit; fExcel := Unassigned; end; 

但是,如果我引入临时variablescl,ch: Variant并将其replace为:

 cl := fExcel.ActiveWorkBook.ActiveSheet.Cells[3, 2]; ch := fExcel.ActiveWorkBook.ActiveSheet.Cells[3+i,1+XL_PT_Tip_FieldCount]; fExcel.ActiveWorkBook.ActiveSheet.Range[cl, ch].Formula := VarArr; 

它神奇地开始工作,Excel.exe得到妥善处理。

如果使用一个表variables,添加临时variables治疗它会发生同样的情况:

 sheetDynamicHb := fExcel.ActiveWorkBook.Sheets['Dynamics Hb']; cl := sheetDynamicHb.Cells[52, 2]; ch := sheetDynamicHb.Cells[52+i, 2+3]; sheetDynamicHb.Range[cl, ch].Formula := VarArr; 

不知怎的,引入临时variables( cl,ch: Variant )是不可能的。 看起来像嵌套的Excelvariables访问做一些奇怪的事情(与裁判计数?)。 我无法解释为什么这样工作,但它的确如所描述的那样工作,使我发疯了一点。

是否有这样的行为的原因和解决scheme,而不是每次添加临时variables?


按要求:一个完整​​的程序:

 unit Unit1; interface uses Winapi.Windows, Winapi.Messages, System.SysUtils, System.Variants, System.Classes, Vcl.Graphics, Vcl.Controls, Vcl.Forms, Vcl.Dialogs, Vcl.StdCtrls, ActiveX, ComObj; type TForm1 = class(TForm) Button1: TButton; procedure Button1Click(Sender: TObject); end; var Form1: TForm1; implementation {$R *.dfm} procedure TForm1.Button1Click(Sender: TObject); var ex, VarArr, cl, ch: Variant; begin ex := CreateOleObject('Excel.Application'); try // Loading template XLS ex.Workbooks.Open('C:\Documents and Settings\...\TemplateCommon.xls'); ex.DisplayAlerts := False; //Selecting work sheet ex.ActiveWorkBook.Sheets['Sheet ABC'].Select; VarArr := VarArrayCreate([0, 9, 0, 12], varVariant); // This code works fine {cl := ex.ActiveWorkBook.ActiveSheet.Cells[3, 2]; ch := ex.ActiveWorkBook.ActiveSheet.Cells[3 + 9, 2 + 12]; ex.ActiveWorkBook.ActiveSheet.Range[cl, ch].Formula := VarArr;} // This code leaves Excel running ex.ActiveWorkBook.ActiveSheet.Range[ ex.ActiveWorkBook.ActiveSheet.Cells[3, 2], ex.ActiveWorkBook.ActiveSheet.Cells[3 + 9, 2 + 12] ].Formula := VarArr; ex.ActiveWorkBook.SaveAs('C:\Documents and Settings\...\out.xls', -4143, '', '', False, False); ex.ActiveWorkBook.Close; finally ex.Quit; ex := Unassigned; end; end; end. 

实际的程序要复杂得多,但即使在这个简单的testing案例中也存在这样的错误:

  • 在临时variables的情况下,Excel立即被处置。
  • 在嵌套variables的情况下,只有在程序closures的时候,Excel才会被抛弃,好像看起来东西是对某个东西的引用。

按照variables创build的相反顺序configurationexcel的各个variables,然后excel对象正确configuration。