Mirror

Work with MS Word DisplayAlerts (Views: 100)


Problem/Question/Abstract:

I have the following code:

MsWord.DisplayAlerts := wdAlertsNone;
MsWord.ScreenUpdating := False;
WordDoc := MsWord.Documents.Add(Template, False);

When the file referenced by "Template" is already in use by another document, I will still get a "File in use" dialog (which is bad enough as it is only a template. It shouldn't be opened for editing anyway. But Documents.Add does this by default: there is no readonly option). Isn't DisplayAlerts supposed to supress this dialog?

Answer:

You can check the file yourself before passing it off to Word (not tested with Office 11):

{ ... }
uses
  ComObj, ActiveX, Word2000;

type
  TStorageResult = (srNotOpen, srOpen, srNotStorageFile, srFileNotFound,
    srNotOpenButNotWordDocument, srNotOpenButUnsureWordDocument);

function CheckWordDocument(const AWordDocument: WideString): TStorageResult;
var
  vResult: HRESULT;
  vStatStg: TSTATSTG;
  oStorage: IStorage;
begin
  Result := srOpen;
  if FileExists(AWordDocument) then
  begin
    if StgIsStorageFile(PWideChar(AWordDocument)) = S_OK then
      {Must check for S_OK...cannot use Succeeded().}
    begin
      vResult := StgOpenStorage(PWideChar(AWordDocument), nil, STGM_SHARE_EXCLUSIVE
        or STGM_READWRITE, nil, 0, oStorage);
      if Succeeded(vResult) then
      begin
        Result := srNotOpen;
        if oStorage.Stat(vStatStg, 0) = S_OK then
        begin
          if not IsEqualCLSID(CLASS_WordDocument, vStatStg.clsid) then
            Result := srNotOpenButNotWordDocument;
        end
        else
          Result := srNotOpenButUnsureWordDocument;
        oStorage := nil;
      end;
    end
    else
      Result := srNotStorageFile;
  end
  else
    Result := srFileNotFound;
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  vStorageResult: TStorageResult;
begin
  vStorageResult := CheckWordDocument('C:\Your.doc');
  case vStorageResult of
    srNotOpen:
      ShowMessage('The document is not open.');
    srOpen:
      ShowMessage('The document is open.');
    srNotStorageFile:
      ShowMessage('The document is not a storage document.');
    srFileNotFound:
      ShowMessage('The document was not found.');
    srNotOpenButNotWordDocument:
      ShowMessage('The document is not open, but it is not a Word document.');
    srNotOpenButUnsureWordDocument:
      ShowMessage('The document is not open, but it does not look like a Word document.');
  end;
end;

<< Back to main page