I need to test if I can use Excel OLE from my program since it can be launched on PCs without Excel. Code samples on the net assume Excel is installed, but what if not?
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;
Would that be correct code to find if Excel is installed?
//Try to create Excel OLE
try
XLApp := CreateOleObject('Excel.Application');
except
ShowMessage('Error opening Excel');
Exit;
end;
You can use a code based on the Scalabium's tip to check whether Excel is available. Or something like:
uses ComObj, ActiveX;
function IsObjectAvailable(const ClassName: string): Boolean;
var
ClassID: TCLSID;
begin
Result := Succeeded(CLSIDFromProgID(PWideChar(WideString(ClassName)),
ClassID));
end;
You can also check if Excel is running by using following code:
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;
And then in some procedure or event:
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With