使用Delphi访问Word中的Fields集合
发布时间:2020-12-15 09:32:25 所属栏目:大数据 来源:网络整理
导读:我有一个小方法,试图枚举Word文档中的字段. 很长一段时间以来,我不得不做这种事情,现在我做不到 记住如何正确地做到这一点. 下面的代码是使用OleVariants,我已经尝试了一段时间和谷歌搜索 没有提出Delphi解决方案.任何人都可以建议如何解决这个问题? 代码的
我有一个小方法,试图枚举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 ); for I := 0 to WordDocument.Fields.Count - 1 do begin ShowMessage( WordDocument.Fields[ I ].Code ); end; End; end; 通过这种方式,我知道这段代码让Word打开了所有这一切. 这暂时还不错,我现在主要担心的是让事情发挥作用. 我也尝试将循环更改为: for I := 0 to WordDocument.Fields.Count -1 do begin ShowMessage( WordDocument.Fields.Item( I ).Code ); end; 但没有奏效,告诉我“物品”不是收藏品的一部分. 我已经没想完了. 解决方法
似乎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; 尝试访问WordDocument.Fields.Item(0)会导致错误: 我从here得到了这个提示 (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |