Mega Code Archive

 
Categories / Delphi / Examples
 

WORD Bookmarks revisited

Title: WORD Bookmarks revisited Question: Open a WORD-document and replace Bookmarks with given Values Answer: Hi again, 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: TDocKapselWORD = class (TDocKapsel) private OleWord: OLEVariant; public function DocClose: Integer; function DocNew(VorlagenFilename: string): Integer; function ReplaceTM(TM_Name, Ergebnis: String): Integer; Procedure Test; end; function TDocKapselWORD.DocNew(TemplateFilename: string): Integer; // Opens the connection to WORD // Returns 0 when ok, -1 on Error Var LocalWordDoc : OLEVariant; rtnCode : integer; begin rtnCode := 0; // Is OLEWord still open? When yes, - Error If VarIsEmpty(OLEWord) = FALSE then rtnCode := -1 else begin try LocalWordDoc := CreateOleObject('WORD.Document'); except // OLE-connection not successful rtnCode := -1; end; If rtnCode = 0 then begin // New Document with given template LocalWordDoc.Application.Documents.Add(TemplateFilename); // Put new document in private variable OLEWord := LocalWordDoc.Application.ActiveDocument; LocalWordDoc.close(); // Everything gone ok? If OLEWord.Application.Documents.Count 0 then rtnCode := 0 else RtnCode := -1; end; end; DocNew := rtnCode; end; function TDocKapselWORD.ReplaceTM(TM_Name, Ergebnis: String): Integer; // Replaces the given Bookmark with the given Text // Returns 0 when ok, -1 on Error begin // Check if Bookmark exists If OLEWord.Bookmarks.exists('TM_Name') then begin OLEWord.Bookmarks.Items('TM_Name').Range.Text := Ergebnis; // Now bookmark should no longer exist If OLEWord.Bookmarks.exists('TM_Name') then result := -1 else result := 0; end else result := -1; end; function TDocKapselWORD.DocClose: Integer; // Closes Document and OLE-connection // Returns 0 when ok, -1 on Error Var rtnCode : integer; begin result := -1; If Not VarIsEmpty(OleWord) then try OleWord.close(); OleWord := unassigned; If VarIsEmpty(OleWord) then result := 0 else result := -1; Except OleWord := unassigned; result := -1; end; end; procedure TDocKapselWord.test; Var BMCount, BM: integer; MyBookmarks: array [1..42] of String; MyTexts: array [1..42] of String; rtnCode : integer begin rtnCode := DocNew('TestFile.DOT'); If rtnCode = 0 then begin // Go on only when Opened ... // Here You need to initialize the bookmarks: how many, what text to which // bookmark and so on. I suppose here, it's in two arrays! ... BM := 1 Repeat rtnCode := ReplaceTM(bookmarks[BM], texts[BM]); BM := BM + 1; Until (BM 42) OR (rtnCode ... // Some Processing afterwards, perhaps print or save ... rtnCode := DocClose; end; ... // Some Processing, when it was or was not successful ... end;