Delphi/Excel - 工作表未实例化

Delphi/Excel - Worksheets not instantiated

Delphi RIO / Excel 2016。我正在使用 Delphi 开始 Excel,然后创建一个新的点差 sheet,我将稍后更新....我用 Delphi/Excel 做了很多编码,我看到了我以前从未见过的行为。我创建 Excel,然后执行 ExcelApp.Worksheets.Add... 以创建新作品 sheet。由于我刚刚开始 Excel,Worksheets 对象为 nil,随后,当我尝试添加新的 Worksheet 时出现 OLE 错误 (800A03EC)。如果我单步执行代码,并在 ExcelApp.Worksheets.Add 行之前,我会转到 Excel,然后执行 File/New,这样就会显示一个空的 sheet,我的代码工作正常。所以问题是,当 ExcelApp.Worksheets 为 nil 时,我该如何实例化它?我可以发誓 'Add' 例程会自动完成。

function glib_TestExcel: Integer;
var
  myAPP: OleVariant;
  oExcel : ExcelApplication;
  thisSheet: _Worksheet;
begin
  if not Assigned(oExcel) then
  begin
    myAPP := CreateOleObject('Excel.Application');
    oExcel := IDispatch(myAPP) as ExcelApplication;

    oExcel.Visible[LOCALE_USER_DEFAULT] := True;
    oExcel.ScreenUpdating[LOCALE_USER_DEFAULT] := True;

    // THIS IS THE PROBLEM LINE BELOW
     oExcel.Worksheets.Add(EmptyParam, EmptyParam,1, xlWorksheet, LOCALE_USER_DEFAULT );

     // Get a handle to the new sheet and set the Sheet Name
     thisSheet := oExcel.ActiveSheet as _Worksheet;
     thisSheet.Name := 'New Sheet1';
     result := glib_SUCCESS;
  end;
end;

您忘记先创建一个 WorkBook 来托管 Worksheet