2015-10-15 85 views
2

我想在Excel工作表中查找字符串。 Excel單元格值使用公式計算。當我運行這段代碼:從「查找」結果中獲取「下標超出範圍」錯誤

Set firstExcel = CreateObject("Excel.application") 
firstExcel.Workbooks.Open "C:\Myroute\excelName.xls" 
Set oSht = firstExcel.Worksheets("Input Data") 
str="hello" 
Set aCell = oSht.Range("A1:E15").Find(str, , xlValues) 
MsgBox aCell.row 

我有一個錯誤,指出:

Error: Subscript out of range
Code: 800A0009

回答

2

你上了.Find行錯誤消息的原因是,VBScript不承認擅長常量,所以你需要用-4163代替xlValues。 (所有的Excel常量值都可以在VBA對象瀏覽器中找到)。

而且,行,你寫Set oSht = firstExcel.Worksheets("Input Data")無厘頭到VB因爲firstExcel是Excel應用程序本身並沒有與Excel應用程序本身沒有關聯工作表對象,但在工作簿對象之內。

Set firstExcel = CreateObject("Excel.application") 
Set wkb = firstExcel.Workbooks.Open("C:\Myroute\excelName.xls") 
Set oSht = wkb.Worksheets("Input Data") 
str="hello" 
Set aCell = oSht.Range("A1:E15").Find(str,,-4163) 
If Not aCell is Nothing Then MsgBox aCell.row 'because if it does not find the string, it will not return a range object 

此外,你可以在你的代碼的頂部聲明常數和使用常數在.Find聲明。

const xlValues = -4163 
.Find(str,,xlValues) 
+0

當我我的代碼更改爲你我得到一個新的錯誤:語句預計年底,在行:Set WKB = firstExcel.Workbooks.Open「C:\ Myroute \ excelName.xls」 – laura

+0

對不起,忘了括號在聲明中。看到我的編輯,然後再試一次。 –

+0

對不起,我試過了,但我仍然有使用Find方法的奇怪錯誤。不管怎麼說,還是要謝謝你。 – laura