什么是检查Excel OLE是否可用的正确方法?

我需要testing我的程序是否可以使用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; 

您可以使用基于Scalabium的提示代码来检查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;