2015-10-15 87 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