Open and edit a Word template from Delphi

13,318

Solution 1

As I understand it, you are using the wrong method. The Add method is used to create a new document. You can pass a template file name to make the new document be based on that template.

But you want to open an existing document and edit it. It doesn't matter that the document is a template. You still need to open it. And for that you need the Open method. Here's a rather trivial example.

var
  WordApp, Doc: Variant;
begin
  WordApp := CreateOleObject('Word.Application');
  WordApp.Visible := True;
  Doc := WordApp.Documents.Open('path\to\my\template.dotx');
  Doc.Range.Text := 'Merry Christmas everyone';
  Doc.Save;
  WordApp.Quit;
end;

I've used late binding because I found that easier for this example. But you should stick to your early binding approach. You'll have to navigate the fact that the open method takes loads of parameters. I think you can simply pass EmptyParam to all but the first parameter.

Solution 2

Here there are thousands of Delphi functions to work with Word: http://delphimagic.blogspot.com.es/2013/03/funciones-para-trabajar-con-word.html

Share:
13,318
OZ8HP
Author by

OZ8HP

Mainly VBA and Delphi

Updated on June 04, 2022

Comments

  • OZ8HP
    OZ8HP almost 2 years

    I need to be able to open and edit a Word template from Delphi (using Word) I can open the template OK but Word assumes it to be a document and not a template.

    The problem is that I need to edit the template and not use it as template for a new document. I use the templates as part of a documenthandling system and I want the users to be able to edit the templates from my app. As it is now they have to open Word and then open the template from there and edit it - doing it from my app would be easier and more secure.

    Experimental code

    fWordApp: WordApplication;
    TempName: OleVariant;
    WordDoc: WordDocument;
    TemplateFile: string;
    begin
      TemplateFile := Settings.Directories.RootInsert(qryTemplates.FieldByName('fldtemplate_path').AsString);
      if TemplateFile <> '' then
        begin
          if not Assigned(fWordApp) then
            begin
              fWordApp := CreateOleObject('Word.Application') as WordApplication;
              while fWordApp.Templates.Count = 0 do
                Sleep(200);                                 // Normal.dot must be loaded
            end;
          if Assigned(fWordApp) then
            fWordApp.Visible := True
          else
            raise Exception.Create('Cannot initialize Word application');
          TempName := TemplateFile;
          WordDoc := fWordApp.Documents.Add(TempName, EmptyParam, wdFormatTemplate, EmptyParam);