1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| Type
TWordReplaceFlags = set of (wrfReplaceAll, wrfMatchCase, wrfMatchWildcards);
Function Word_StringReplace(ADocument: TFileName; SearchString, ReplaceString: string; Flags: TWordReplaceFlags): Boolean;
const
wdFindContinue = 1;
wdReplaceOne = 1;
wdReplaceAll = 2;
wdDoNotSaveChanges = 0;
var
WordApp: OLEVariant;
begin
Result := False;
if not FileExists(ADocument) then
begin
ShowMessage('Le fichier spécifié est introuvable.');
Exit;
end;
try
WordApp := CreateOLEObject('Word.Application');
except
on E: Exception do
begin
E.Message := 'Word n''est pas disponible.';
raise;
end;
end;
try
WordApp.Visible := true;
WordApp.Documents.Open(ADocument);
WordApp.Selection.Find.ClearFormatting;
WordApp.Selection.Find.Text := SearchString;
WordApp.Selection.Find.Replacement.Text := ReplaceString;
WordApp.Selection.Find.Forward := True;
WordApp.Selection.Find.Wrap := wdFindContinue;
WordApp.Selection.Find.Format := False;
WordApp.Selection.Find.MatchCase := wrfMatchCase in Flags;
WordApp.Selection.Find.MatchWholeWord := False;
WordApp.Selection.Find.MatchWildcards := wrfMatchWildcards in Flags;
WordApp.Selection.Find.MatchSoundsLike := False;
WordApp.Selection.Find.MatchAllWordForms := False;
if wrfReplaceAll in Flags then
WordApp.Selection.Find.Execute(Replace := wdReplaceAll)
else
WordApp.Selection.Find.Execute(Replace := wdReplaceOne);
WordApp.ActiveDocument.SaveAs(ADocument); // Sauvegarde du document
Result := True;
WordApp.ActiveDocument.Close(wdDoNotSaveChanges);
finally
WordApp.Quit; / Quitter Word
WordApp := Unassigned;
end;
end;
//----------------------------------------------------------------------------
Utilisation :
procedure TForm1.LMDButton1Click(Sender: TObject);
begin
Word_StringReplace('C:\Test.doc' , 'xxx2' , 'Nouveau mot' , [wrfReplaceAll]); // Test.doc ou Test.Rtf
end; |
Partager