从“查找”结果中获取“下标超出范围”错误

我想在Excel工作表中find一个string。 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 

我有一个错误,说:

错误:下标超出范围
代码:800A0009

您在.Find行上得到错误消息的原因是vbscript不能识别Excels常量,因此您需要用数字-4163replace-4163 。 (所有的Excel常量值都可以在VBA对象浏览器中find)。

此外,您写的Set oSht = firstExcel.Worksheets("Input Data")对VB没有意义,因为firstExcel是Excel应用程序本身,没有与Excel应用程序本身相关联的Worksheet对象,但是在Workbook目的。

 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)