使用 Delphi 的 OleObject 在 Office 365 和 Office 2013 中的工作方式不同

OleObject using Delphi works differently in Office 365 and Office 2013

我正在开发一个使用 Delphi Pascal 来打开 XLSX 文件并在其上写入单元格的小工具。它在使用 Office 2013 和 Office 365 的计算机上表现不同。

代码如下:

var
  ExcelApp: OleVariant;
  anExcelFileName: String;
begin
  try
    ExcelApp := CreateOleObject('Excel.Application');
    anExcelFileName := 'D:\sample.xlsx';

    ExcelApp.Workbooks.Open(anExcelFileName);
    ExcelApp.Visible := True;

    ExcelApp.Workbooks[1].Sheets[1].Range['A1'].Value := 'HELLO';
  except
    on E: Exception do
      showMessage('Error on something: ' + E.Message);
  end;
end;

在 Office 2013 中,代码将访问驱动器 D 中的文件 sample.xlsx,打开它,并在单元格 A1 中写入 HELLO。

在 Office 365 中,代码将打开两个文件。首先它会打开 sample.xlsx 并打开一个新的空白工作簿,并在新的空白工作簿中写入 HELLO。

如何获取 Office 365 中的旧行为?

您的代码失败是因为它假设您打开的工作簿将是工作簿集合中的第一个工作簿,而该假设并不总是成立。

Workbooks.Open returns 新打开的工作簿。将该对象用于将来对该工作簿的引用。像这样:

var
  ExcelApp, Workbook: OleVariant;
  anExcelFileName: String;
begin
  try
    ExcelApp := CreateOleObject('Excel.Application');
    anExcelFileName := 'D:\sample.xlsx';

    Workbook := ExcelApp.Workbooks.Open(anExcelFileName);
    ExcelApp.Visible := True;

    Workbook.Sheets[1].Range['A1'].Value := 'HELLO';
  except
    on E: Exception do
      showMessage('Error on something: ' + E.Message);
  end;
end;