Kromster
Kromster

Reputation: 7425

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

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;

Upvotes: 12

Views: 7526

Answers (1)

Guillem Vicens
Guillem Vicens

Reputation: 3996

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;

Upvotes: 17

Related Questions