PhysiologyWeb Logo  Search
PhysiologyWeb Loading...

Delphi Code - Open an Existing Word File and Save with a New Name (Save As)
Here is a simple Delphi procedure that opens an existing Microsoft Word file, saves the file with a new name (save as), and finally closes the file. No changes are made to the file before saving with a new name. This is useful when utilizing a Word template file (with company logo and other brand formatting already included) to start a new document. The most relevant parts of the code are highlighted. Comments are included to explain the code. If you copy and paste the code into your program, be sure to change the form and procedure names to match your setup. For additional Word automation solutions, see Microsoft Word Automation with Delphi.
procedure TForm1.OpenAnExistingWordtFileAndSaveAs(Sender: TObject);
var
WordFileName, WordFileNameNew: String;
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

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.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;






Posted: Sunday, March 20, 2022