delphims-worddelphi-7oleole-automation

Edit Merge Field in Word Document Programmatically


I'm using Delphi 7 to process mail merge document, the document already created outside delphi and is fixed with merge fields, my goal is to edit (change) those merge field through delphi 7.

Let just say i have merge field named 'field1', i have to edit to make the merge field name 'field2'.

I have tried the following to open and replace (edit) the merge field, but i only get to replace the text, the merge field is actually still the same from before replacement.

procedure openword;
var
  WordApp: OleVariant;
begin
  WordApp := CreateOleObject('Word.Application');
  WordApp.Visible := True;
  WordApp.Documents.Open('C:\Test.doc');
end;

procedure editmergefield; //replace
Var
  WordApp : OleVariant;
begin
  WordApp := GetActiveOleObject('Word.Application');
  WordApp.Selection.Find.ClearFormatting;
  WordApp.Selection.Find.Replacement.ClearFormatting;
  WordApp.Selection.Find.Execute(
  'Field1',True,True,False,False,False,False,1,False,'Field2',2);
end;

Solution

  • I have a Word 2007 document containing two mailmerge fields, Title and Last_Name. The following D7 code changes the name of the first of them to First_name.

    procedure TForm1.Button1Click(Sender: TObject);
    var
      AFileName : String;
      MSWord,
      Document : OleVariant;
      S : String;
      mmFields : MailMergeFields;
      mmField : MailMergeField;
    begin
      AFileName := 'd:\aaad7\officeauto\Dear.Docx';
    
      MSWord := CreateOleObject('Word.Application');
      MSWord.Visible := True;
      Document := MSWord.Documents.Open(AFileName);
    
      //  The MSWord and Document objects are wrapped in OleVariants
      //  For debugging purposes, I find it easier to work with the objects
      //  defined in the MS Word type library import unit, e.g. Word2000.Pas
      //  So, the following lines access the document's MailMerge object
      //  and its mailmerge fields as interface objects
    
      mmFields := IDispatch(Document.MailMerge.Fields) as MailMergeFields;
      Assert(mmFields <> Nil);  // checks that the mmFields object is not Nil
    
      mmField := mmFields.Item(1);  //  This is the first mail merge field in the document
    
      //  The mmField's Code field is a Range object, and the field name
      //   is contained in the range's Text property
    
      S := mmField.Code.Text; // Should contain 'MERGEFIELD "Title"'    
      S := StringReplace(S, 'Title', 'First_Name', []);
      mmField.Code.Text := S;
      Caption := S;
    end;