excel - 使用 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 中的旧行为?
解决方案
您的代码失败,因为它假设您打开的工作簿将是工作簿集合中的第一个,并且该假设并不总是成立。
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;
推荐阅读
- java - Unable to run project app from Android Studio to my external device
- typescript - Destructuring objects with typescript
- git - How can I incrementally mirror a Git repository via bundle files?
- javascript - package-lock.json is not working in heroku
- javascript - Gatsbyjs & localStorage: Persisting state
- javascript - (node:10196) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'filename' of undefined
- qt - Drag and Drop mechanism in qml
- f# - 如何在 F# 中组合 Result<> 列表?
- r - R - 在不同的箱线图中为每个组保持相同的颜色
- android - mediaMetaDataRetriver.setDataSource(字符串路径)在 Android Studio 中不起作用