Author: Jonas Bilinkevicius
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):
1 { ... }
2 uses
3 ComObj, ActiveX, Word2000;
4
5 type
6 TStorageResult = (srNotOpen, srOpen, srNotStorageFile, srFileNotFound,
7 srNotOpenButNotWordDocument, srNotOpenButUnsureWordDocument);
8
9 function CheckWordDocument(const AWordDocument: WideString): TStorageResult;
10 var
11 vResult: HRESULT;
12 vStatStg: TSTATSTG;
13 oStorage: IStorage;
14 begin
15 Result := srOpen;
16 if FileExists(AWordDocument) then
17 begin
18 if StgIsStorageFile(PWideChar(AWordDocument)) = S_OK then
19 {Must check for S_OK...cannot use Succeeded().}
20 begin
21 vResult := StgOpenStorage(PWideChar(AWordDocument), nil, STGM_SHARE_EXCLUSIVE
22 or STGM_READWRITE, nil, 0, oStorage);
23 if Succeeded(vResult) then
24 begin
25 Result := srNotOpen;
26 if oStorage.Stat(vStatStg, 0) = S_OK then
27 begin
28 if not IsEqualCLSID(CLASS_WordDocument, vStatStg.clsid) then
29 Result := srNotOpenButNotWordDocument;
30 end
31 else
32 Result := srNotOpenButUnsureWordDocument;
33 oStorage := nil;
34 end;
35 end
36 else
37 Result := srNotStorageFile;
38 end
39 else
40 Result := srFileNotFound;
41 end;
42
43 procedure TForm1.Button1Click(Sender: TObject);
44 var
45 vStorageResult: TStorageResult;
46 begin
47 vStorageResult := CheckWordDocument('C:\Your.doc');
48 case vStorageResult of
49 srNotOpen:
50 ShowMessage('The document is not open.');
51 srOpen:
52 ShowMessage('The document is open.');
53 srNotStorageFile:
54 ShowMessage('The document is not a storage document.');
55 srFileNotFound:
56 ShowMessage('The document was not found.');
57 srNotOpenButNotWordDocument:
58 ShowMessage('The document is not open, but it is not a Word document.');
59 srNotOpenButUnsureWordDocument:
60 ShowMessage('The document is not open, but it does not look like a Word
61 document.'
62 end;
63 end;
|