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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With