Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the proper way to check if Excel OLE is available?

Tags:

excel

delphi

ole

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;
like image 667
Kromster Avatar asked Feb 22 '13 05:02

Kromster


1 Answers

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;
like image 97
Guillem Vicens Avatar answered Sep 19 '22 23:09

Guillem Vicens