使用Delphi访问Word中的Fields集合

And*_*ndi 5 delphi ms-word ole-automation

我有一个小方法,试图枚举Word文档中的字段.很长一段时间以来,我不得不做这种事情,现在我不记得如何正确地做到这一点.

下面的代码是使用OleVariants,我已经尝试了一段时间,谷歌搜索没有提出德尔福解决方案.任何人都可以建议如何解决这个问题?

代码的最终目标是识别特定类型的字段并使用该信息来删除所述字段.

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;
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我知道这段代码让Word打开了所有这些.

这暂时还不错,我现在主要担心的是让事情发挥作用.

我也尝试将循环更改为:

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

但没有奏效,告诉我"物品"不是收藏品的一部分.

我已经没想完了.

kob*_*bik 7

看起来像Item集合的基本索引是1(不是0).所以你需要从1迭代到WordDocument.Fields.Count例如:

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; 
Run Code Online (Sandbox Code Playgroud)

尝试访问WordDocument.Fields.Item(0)结果时出错:
The requested member of the collection does not exist.

我从这里得到了这个暗示