2013-10-04 26 views
0

感謝這裏的人,我終於有一個工作循環...差不多:) 它大部分時間工作,但在某些情況下,這個錯誤出現了。收集的請求的成員不存在

代碼:

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; 

與上面的代碼的問題是,有時,伯爵將返回2但當我嘗試檢查第二項,它在被攝體輸出異常。

難道這只是我必須做一個計數-1而不是一個計數?

+0

是,AFAIK,索引從0到計數-1。 –

+0

我確定索引從1開始。 這是一件確定的事情。但它可能停在伯爵1,我不知道。 –

+0

你沒有給我們實際的錯誤。 – Johan

回答

0

你是對的。 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; 
相關問題