【问题标题】:The requested member of the collection does not exist请求的集合成员不存在
【发布时间】:2013-10-04 11:19:26
【问题描述】:

感谢这里的某个人,我终于有了一个工作循环......几乎:) 它大部分时间都有效,但在某些情况下,会出现此错误。

代码:

procedure TLetters.ReplaceDate(NewDate: String);
var I : Integer;
    ARegion : OleVariant;
    FieldType : Integer;
    FieldCount : Integer;
begin
    FieldCount := WordApp.ActiveDocument.Fields.Count;
    For I := 1 to FieldCount do
    Begin
         FieldType := WordApp.ActiveDocument.Fields.Item( I ).type;
         If FieldType IN [ 31,32 ] Then
         Begin
               ARegion := WordApp.ActiveDocument.Fields.Item( I ).Code;
               WordApp.ActiveDocument.Fields.Item( I ).Cut;
               ARegion.Text := NewDate;
         End;
    End;
end;

上述代码的问题在于,有时 Count 会返回 2,但是当我尝试检查第二个条目时,它会在主题中输出异常。

难道只是我必须做一个 Count -1 而不是 Count 吗?

【问题讨论】:

  • 是的,AFAIK,索引从 0 到 Count-1。
  • 我确信索引从 1 开始。这是肯定的。但它可能会停在 Count-1,我不知道。
  • 你没有告诉我们实际的错误。

标签: delphi ms-word ole-automation


【解决方案1】:

你是对的。 Office 中的所有计数都从 1 变为计数。

错误在您的代码中:

procedure TLetters.ReplaceDate(NewDate: String);
var I : Integer;
  ARegion : OleVariant;
  FieldType : Integer;
  FieldCount : Integer;
begin
  FieldCount := WordApp.ActiveDocument.Fields.Count;
  for I := 1 to FieldCount do begin
    FieldType := WordApp.ActiveDocument.Fields.Item( I ).type;
    If FieldType IN [ 31,32 ] then begin
      ARegion := WordApp.ActiveDocument.Fields.Item( I ).Code;
      WordApp.ActiveDocument.Fields.Item( I ).Cut;  <<--- here !!
      ARegion.Text := NewDate;
    end;
  end;
end;

当你cut 一个项目时,你将它从列表中删除,你应该将count 减少一个。

像这样重写代码:

begin
  FieldCount := WordApp.ActiveDocument.Fields.Count;
  i:= 1;
  while (i <= fieldCount) do begin
    FieldType := WordApp.ActiveDocument.Fields.Item( i ).type;
    if FieldType in [ 31,32 ] then begin
      ARegion := WordApp.ActiveDocument.Fields.Item( i ).Code;
      WordApp.ActiveDocument.Fields.Item( i ).Cut; 
      Dec(FieldCount);
      ARegion.Text := NewDate;
    end 
    else Inc(i);
  end; {while}
end;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-22
    • 1970-01-01
    • 1970-01-01
    • 2014-02-13
    相关资源
    最近更新 更多