Navigation Menu Search PhysiologyWeb
PhysiologyWeb Logo Search PhysiologyWeb
   
— share —
Share on Facebook    Share on X    Share on LinkedIn    Share on Pinterest    Share on Reddit    Email    Copy URL
procedure TForm1.OpenANewWordtFileAndSaveAs(Sender: TObject);
var
WordFileName: String;
WordApplication, WordFile: Variant;
begin
//be sure ComObj and Variants units are included in the "uses" clause

WordFileName := 'C:\PhysiologyWeb\delphi_code_examples\new_word_file.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 a new Word file (i.e., new Word document)
try
WordFile := WordApplication.Documents.Add; //uses the default template
//reference
//https://docs.microsoft.com/en-us/office/vba/api/word.documents.add
except
WordFile := Null;
//add error/exception handling code as desired
end;

If VarIsNull(WordFile) = False then
begin
//add some text to the new Word file
WordFile.Range.Text := 'Thank you, Microsoft, for making automation features available!!!' + #13+#10 + #13+#10 + 'Sincerely,' + #13+#10 + 'PhysiologyWeb Team';
//reference
//https://docs.microsoft.com/en-us/office/vba/api/word.range.text

WordFile.SaveAs(WordFileName);
//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: Saturday, March 26, 2022
Last updated: Tuesday, March 18, 2025
— share —
Share on Facebook    Share on X    Share on LinkedIn    Share on Pinterest    Share on Reddit    Email    Copy URL