我需要测试是否可以从我的程序中使用Excel OLE,因为它可以在没有Excel的PC上启动。网上的代码示例假定安装了Excel,但如果没有安装,那么该怎么办?
XLApp := CreateOleObject('Excel.Application');
try
// Hide Excel
XLApp.Visible := False;
// Open the Workbook
XLApp.Workbooks.Open(aPath);
...snip...
finally
// Quit Excel
if not VarIsEmpty(XLApp) then
begin
XLApp.Quit;
XLAPP := Unassigned;
end;
end;
这是否是正确的代码,以确定是否安装了Excel?
//Try to create Excel OLE
try
XLApp := CreateOleObject('Excel.Application');
except
ShowMessage('Error opening Excel');
Exit;
end;
答案 0 :(得分:16)
您可以使用基于Scalabium's tip的代码来检查Excel是否可用。或类似的东西:
uses ComObj, ActiveX;
function IsObjectAvailable(const ClassName: string): Boolean;
var
ClassID: TCLSID;
begin
Result := Succeeded(CLSIDFromProgID(PWideChar(WideString(ClassName)),
ClassID));
end;
您还可以使用以下代码检查Excel是否正在运行:
function IsObjectActive(const ClassName: string): Boolean;
var
ClassID: TCLSID;
Unknown: IUnknown;
begin
Result := False;
if Succeeded(CLSIDFromProgID(PWideChar(WideString(ClassName)), ClassID)) then
Result := Succeeded(GetActiveObject(ClassID, nil, Unknown));
end;
然后在某些程序或事件中:
procedure TForm1.Button1Click(Sender: TObject);
begin
if IsObjectAvailable('Excel.Application') then
ShowMessage('Excel is available');
if IsObjectActive('Excel.Application') then
ShowMessage('Excel is running');
end;