首页 > 解决方案 > 使用 Delphi 的 OleObject 在 Office 365 和 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 中的旧行为?

标签: exceldelphidelphi-2010

解决方案


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

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

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;

推荐阅读