Author: Andreas Heidenreich
An Example how to Open a WORD-Document and replace the bookmarks inside of it.
Answer:
here I try to give a detailed Example how to Open an existing WORD-document from
the background of an application an replace bookmarks in this document with given
text.
Global declarations:
1 TDocKapselWORD = class(TDocKapsel)
2 private3 OleWord: OLEVariant;
4 public5 function DocClose: Integer;
6 function DocNew(VorlagenFilename: string): Integer;
7 function ReplaceTM(TM_Name, Ergebnis: string): Integer;
8 procedure Test;
9 end;
10 11 function TDocKapselWORD.DocNew(TemplateFilename: string): Integer;
12 // Opens the connection to WORD13 // Returns 0 when ok, -1 on Error14 var15 LocalWordDoc: OLEVariant;
16 rtnCode: integer;
17 begin18 rtnCode := 0;
19 // Is OLEWord still open? When yes, -> Error20 if VarIsEmpty(OLEWord) = FALSE then21 rtnCode := -1
22 else23 begin24 try25 LocalWordDoc := CreateOleObject('WORD.Document');
26 except27 // OLE-connection not successful28 rtnCode := -1;
29 end;
30 if rtnCode >= 0 then31 begin32 // New Document with given template33 LocalWordDoc.Application.Documents.Add(TemplateFilename);
34 // Put new document in private variable35 OLEWord := LocalWordDoc.Application.ActiveDocument;
36 LocalWordDoc.close();
37 // Everything gone ok?38 if OLEWord.Application.Documents.Count > 0 then39 rtnCode := 0
40 else41 RtnCode := -1;
42 end;
43 end;
44 DocNew := rtnCode;
45 end;
46 47 function TDocKapselWORD.ReplaceTM(TM_Name, Ergebnis: string): Integer;
48 // Replaces Bookmark TM_Name with String Ergebnis49 // returns 0 when ok, -1 on error.50 begin51 if OLEWord.Bookmarks.exists(TM_Name) then52 begin53 OLEWord.Bookmarks.Item(TM_Name).Range.Text := Ergebnis;
54 if OLEWord.Bookmarks.exists(TM_Name) then55 result := -1
56 else57 result := 0
58 end59 else60 result := -1;
61 end;
62 63 function TDocKapselWORD.DocClose: Integer;
64 // Closes Document and OLE-connection65 // Returns 0 when ok, -1 on Error66 var67 rtnCode: integer;
68 begin69 result := -1;
70 ifnot VarIsEmpty(OleWord) then71 try72 OleWord.close();
73 OleWord := unassigned;
74 if VarIsEmpty(OleWord) then75 result := 0
76 else77 result := -1;
78 except79 OleWord := unassigned;
80 result := -1;
81 end;
82 end;
83 84 procedure TDocKapselWord.test;
85 var86 BMCount, BM: integer;
87 MyBookmarks: array[1..42] ofstring;
88 MyTexts: array[1..42] ofstring;
89 rtnCode: integer
90 begin91 rtnCode := DocNew('TestFile.DOT');
92 if rtnCode = 0 then93 begin// Go on only when Opened94 ...
95 // Here You need to initialize the bookmarks: how many, what text to which96 // bookmark and so on. I suppose here, it's in two arrays!97 ...
98 BM := 1
99 repeat100 rtnCode := ReplaceTM(bookmarks[BM], texts[BM]);
101 BM := BM + 1;
102 until (BM > 42) or (rtnCode < 0);
103 ...
104 // Some Processing afterwards, perhaps print or save105 ...
106 rtnCode := DocClose;
107 end;
108 ...
109 // Some Processing, when it was or was not successful110 ...
111 end;