2017-03-21 60 views
1

我想寫一個應用程序遍歷以分號分隔的內容的文本文件,並在另一個Excel文件的特定列中搜索每個值。excel.Range.Find返回錯誤值C#

我可以打開Excel中的文本文件,並以正確的方式打開(我使應用程序可見並檢查它是否格式正確)。現在,如果我遍歷文本表並使用Excel.Range.Find方法,它總是返回錯誤的行。所以應該有與工作簿或表或沒有任何問題

Microsoft.Office.Interop.Excel.Range current_find = usedRange_2.Cells[3].Find((String)(row.Cells[7]).Value2 
Microsoft.Office.Interop.Excel.Range first_find = null 

//for each row in tableOftextFile 
if (first_find == null && current_find!=null) 
    { 
      first_find = current_find; 
    } 
do 
    { 
    if (((String)current_find.Cells[3].Value2).Contains((String)row.Cells[7].Value2)) 
     { 
      //this part is never reached somehow. 
      break; 
     } 
    else 
    { 
     current_find = usedRange_2.FindNext(current_find); 
    } 
    } while (current_find!=first_find && current_find!=null); 

一切都在我的應用程序的工作就好了。

的查找操作必須找到的東西,因爲該值存在,我可以在Excel中的應用程序手動搜索他們,並得到正確的結果,但例如,如果我搜索的值「40」,並將結果返回到current_findcurrent_find.Cells[3].Value2是「42」或類似的東西,但不是我預期的結果。

如果有人可以請給我一個提示,甚至是一個很好的解決方案。謝謝:)

回答

0

對不起,我發現我的錯誤,如果別人不一樣,這裏就是答案:

我認爲Excel.Find方法返回的行與比賽,但它似乎返回細胞與比賽。所以我將current_find.Cells[3].Value2更正爲current_find.Value2,我很高興。