Microsoft Word Form Integration

Giganews Newsgroups
Subject:Microsoft Word Form Integration
Posted by: Bruce Norton
Date:Tue, 29 Dec 2009

Okay, I know this should be easy but it is evading me at the moment.

All I want to do is to be able to fill in forms developed in Microsoft Word through my Delphi application.

First, I tried to simply use mail merge type fields in Word but there is no documentation to show how to populate those fields.  So I am using what I consider to be a less attractive alternative - using bookmarks and ref fields.  The problem is updating the ref fields.  The problem is when I select the whole document and update the fields, the data in my bookmarks go away.  If I try to iterate through the fields, I get an error that "Fields" is not a method.

My code is:

procedure TForm1.Button1Click(Sender: TObject);
var
  Word: OLEVariant;
  Range,Selection,Doc,Table,TheCell,View : Variant;
  i: Integer;
begin

  try
    Word := CreateOleObject('Word.Application');
  except
    ShowMessage('Cannot start Word !');
    Exit;
  end;
  try
    Doc:=Word.Documents.Open('D:\Hello.docx',Null, True);
    Word.Visible := True;
    if Word.ActiveDocument.Bookmarks.Exists('FirstName') then
      Word.ActiveDocument.FormFields.Item('FirstName').Result := 'Bruce';
    for i := 1 to Word.ActiveDocument.Fields.Count do
    begin
      Word.ActiveDocument.Fields(i).Select;
      Word.ActiveDocument.Fields(i).Update;
    end;

    Word := Unassigned;
    Screen.Cursor := crDefault;
  finally
    Word := Unassigned;
    Screen.Cursor := crDefault;
  end;
end;

Someone please help!

Bruce..

Replies