views:

18

answers:

1

Hi,

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!

A: 

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;
Sertac Akyuz
Hi Sertac, thanks, but if 'Count' is 1 and that document is invisible, ActiveDocument is still nil.
Edwin
@Edwin - I didn't know the `Documents` collection included invisible documents. Anyway, see if the update on the answer suits your needs..
Sertac Akyuz
Hi Sertac, thanks for the help, but I tried that trick before already wanted to ignore that exception, the try..except block can't catch that exception.
Edwin
@Edwin - There's a probability that the error code I've hard-coded might be different between various office versions. But, otherwise, if there's an exception then you should be able to catch it. Good luck!
Sertac Akyuz
Hi Sertac, thank you so much! I tried again, it worked! I don't know why the exception is not captured the last time I tried, does the compiler/linker setting has anything to do with this?
Edwin
@Edwin - Maybe you've clicked "Ignore this exception type" in the Exception Notification and this created a confusion, or maybe a slight code change, who knows!.. Glad that it's working now. :)
Sertac Akyuz