2013-02-22 92 views
11

我需要測試我的程序是否可以使用Excel OLE,因爲它可以在沒有Excel的PC上啓動。網上的代碼示例假設安裝了Excel,但如果不安裝呢?什麼是檢查Excel OLE是否可用的正確方法?

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; 
+5

似乎是合理的我。 – Joe 2013-02-22 05:48:34

回答

15

您可以使用基於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; 
+7

+1但是我會繼續在我的應用程序中嘗試使用'CreateOleObject except',因爲我相信這是唯一可靠的方法來確保我可以*創建*一個對象實例(通過'CoCreateInstance')。上述方法可以作爲初步測試來檢查班級是否正確註冊。 – kobik 2013-02-22 11:55:33

+0

@kobik,我同意。在我的答案中,我假設OP只需要知道如何檢查正在安裝的Excel,並且'嘗試CreateOleObject'將被用於對象實例創建部分。 – 2013-02-22 12:28:41

+1

@Guilem,'CreateOleObject'也會做'OleCheck(CLSIDFromProgID ...'('ProgIDToClassID'),所以如果你打算嘗試一下,我並沒有真正意識到這一點。 CreateOleObject'在任何情況下...... – kobik 2013-02-22 12:33:03

相關問題