0

我正在使用 Delphi 7 来处理邮件合并文档,该文档已经在 delphi 外部创建并使用合并字段进行了修复,我的目标是通过 delphi 7 编辑(更改)那些合并字段。

假设我有名为“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;
4

1 回答 1

1

我有一个 Word 2007 文档,其中包含两个邮件合并字段,Title并且Last_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;
于 2016-12-22T19:00:31.563 回答