以编程方式编辑 Word 文档中的合并字段

Edit Merge Field in Word Document Programmatically

我正在使用 Delphi 7 来处理邮件合并文档,该文档已经在 delphi 之外创建并固定了合并字段,我的目标是通过编辑(更改)这些合并字段delphi7.

假设我有一个名为 'field1' 的合并字段,我必须编辑以使合并字段名称为 'field2'。

我尝试了以下方法来打开和替换(编辑)合并字段,但我只能替换文本,合并字段实际上与替换前相同。

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;

我有一个包含两个邮件合并字段的 Word 2007 文档,TitleLast_Name。以下 D7 代码将其中第一个的名称更改为 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;