procedure TForm1.SearchAndReplaceTextInMicrosoftWord(Sender: TObject);
var
WordFileName, WordFileNameNew, TargetText, ReplacementText: String;
FoundAndReplaced: Boolean;
WordApplication, WordFile: Variant;
begin
//be sure ComObj and Variants units are included in the "uses" clause
WordFileName := 'C:\PhysiologyWeb\delphi_code_examples\word_file.docx'; //replace file name with the name of your file
WordFileNameNew := 'C:\PhysiologyWeb\delphi_code_examples\word_file_new.docx'; //replace file name with the name of your file
TargetText := '';
ReplacementText := '';
FoundAndReplaced := False;
WordApplication := Null;
WordFile := Null;
try
//create Word OLE
WordApplication := CreateOleObject('Word.Application');
except
WordApplication := Null;
//add error/exception handling code as desired
end;
If VarIsNull(WordApplication) = False then
begin
try
WordApplication.Visible := True; //set to False if you do not want to see the activity in the background
WordApplication.DisplayAlerts := False; //ensures message dialogs do not interrupt the flow of your automation process. May be helpful to set to True during testing and debugging.
//Open Word File
try
WordFile := WordApplication.Documents.Open(WordFileName);
//reference
//https://docs.microsoft.com/en-us/office/vba/api/word.documents.open
except
WordFile := Null;
//add error/exception handling code as desired
end;
If VarIsNull(WordFile) = False then
begin
WordFile.Content.Find.ClearFormatting;
WordFile.Content.Find.Replacement.ClearFormatting;
TargetText := 'target text';
ReplacementText := 'replacement text';
FoundAndReplaced := False;
FoundAndReplaced := WordFile.Content.Find.Execute(TargetText,True,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,EmptyParam,ReplacementText,2,EmptyParam,EmptyParam,EmptyParam,EmptyParam);
//reference
//https://docs.microsoft.com/en-us/office/vba/api/word.find.execute
//here are all the optional parameters
//FindText, MatchCase, MatchWholeWord, MatchWildcards, MatchSoundsLike, MatchAllWordForms, Forward, Wrap, Format, ReplaceWith, Replace, MatchKashida, MatchDiacritics, MatchAlefHamza, MatchControl
If FoundAndReplaced = False then
begin
//insert relevant code
end;
WordFile.SaveAs(WordFileNameNew);
//reference
//https://docs.microsoft.com/en-us/office/vba/api/word.documents.save
end;
finally
WordFile.Close;
WordApplication.DisplayAlerts := True;
WordApplication.Quit;
WordFile := Unassigned;
WordApplication := Unassigned;
end;
end;
end;