Edwin Yip
Edwin Yip

Reputation: 4220

MS Word OLE - How to access ActiveDocument without raising an exception?

In Word automation through OLE, when accessing the ActiveDocument property an exception will be raised if currently no visible document is available (at least in Delphi), so, my goal is to do some test like IsActiveDocumentValid, how to do that without raising an exception? Thank you!

Upvotes: 1

Views: 1805

Answers (1)

Sertac Akyuz
Sertac Akyuz

Reputation: 54812

The exception is raised by the automation server itself, you cannot prevent that. However you can get a count of open Documents before accessing ActiveDocument;

WordApplication.Documents.Count

If the 'Count' is 0 if there are no documents available.

edit: Alternatively you can handle the specific exception silently, example (Delphi code);

function ActiveDocumentExists(WordApplication: Variant): Boolean;
begin
  Result := True;
  try
    WordApplication.ActiveDocument.Activate;
  except on E: EOleException do
    if E.ErrorCode = LRESULT($800A1098) then
      Result := False;
  end;
end;

Upvotes: 2

Related Questions