Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing the Fields collection in Word by using Delphi

I have a small method which is trying to enumerate the fields in a Word document. A lot of time has passed since I had to do this kind of thing and now I can't remember how to do it properly.

The code below is using OleVariants, I've been trying for a while and googling didn't come up with a Delphi solution. Anybody can suggest how to fix this?

The final goal of the code is to identify a specific kind of field and use that information to delete said field.

procedure TForm2.Button1Click(Sender: TObject);
var
   I: Integer;
begin
     If OpenDialog1.Execute Then
     Begin
          WordApp := CreateOLEObject( 'Word.Application' );
          WordDocument := WordApp.Documents.Open( OpenDialog1.FileName, EmptyParam,
                                                  EmptyParam, EmptyParam,
                                                  EmptyParam, EmptyParam,
                                                  EmptyParam, EmptyParam,
                                                  EmptyParam, EmptyParam,
                                                  EmptyParam, EmptyParam,
                                                  EmptyParam, EmptyParam,
                                                  EmptyParam );
          for I := 0 to WordDocument.Fields.Count - 1 do
          begin
               ShowMessage( WordDocument.Fields[ I ].Code );
          end;
      End;
end;

By The way, I know that this code leaves Word open and all that.

That is fine for the time being, my main concern at the moment is getting the thing to work.

I have also tried to change the loop to this:

for I := 0 to WordDocument.Fields.Count -1 do
begin
     ShowMessage( WordDocument.Fields.Item( I ).Code );
end;

But didn't work, told me that "Item" isn't part of the collection.

I have run out of ideas.

like image 447
Andrea Raimondi Avatar asked Oct 03 '13 08:10

Andrea Raimondi


1 Answers

Seems like the base index of the Item collection is 1 (not 0). So you need to iterate from 1 to WordDocument.Fields.Count e.g.:

procedure TForm1.Button1Click(Sender: TObject);
var
  WordApp, WordDocument, Field: OleVariant;
  I: Integer;
begin
  WordApp := CreateOleObject('Word.Application');
  try
    WordDocument := WordApp.Documents.Open('C:\MyDoc.doc');
    if WordDocument.Fields.Count >= 1 then 
      for I := 1 to WordDocument.Fields.Count do
      begin
        Field := WordDocument.Fields.Item(I);
        ShowMessage(Field.Code);
      end;
  finally
    WordApp.Quit;
  end;
end; 

Trying to access WordDocument.Fields.Item(0) results an error:
The requested member of the collection does not exist.

I got that hint from here

like image 57
kobik Avatar answered Nov 16 '22 17:11

kobik