我遇到了reasons why excel.exe remains loaded after running a delphi client automation program?问题的奇怪问题。问题是更进一步。
我有用Delphi 7编写的代码并将其升级到XE2。在这样做后,我在XE2中遇到了同样的问题,虽然建议的解决方案在简单的测试应用程序中工作,但只要我使用这些行,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;
但是,如果我引入临时变量cl,ch: Variant
并将上面替换为:
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被妥善处理。
如果使用工作表变量,则会发生相同的情况,添加临时变量可以解决它:
sheetDynamicHb := fExcel.ActiveWorkBook.Sheets['Dynamics Hb'];
cl := sheetDynamicHb.Cells[52, 2];
ch := sheetDynamicHb.Cells[52+i, 2+3];
sheetDynamicHb.Range[cl, ch].Formula := VarArr;
以某种方式引入临时变量(cl,ch: Variant
)就可以了。似乎嵌套的Excel
变量访问做了奇怪的事情(使用ref计数?)。我无法解释为什么会这样,但它确实如所描述的那样起作用并让我疯狂一点。
除了每次添加临时变量之外,是否存在此类行为和解决方案的原因?
根据要求:完整的计划:
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.
实际程序要复杂得多,但即使在这个简单的测试用例中,也存在错误:
答案 0 :(得分:-1)
以与创建变量相反的顺序处理excel的每个变量,然后excel对象进行正确处理。