从结果中获取"subscript out of range"错误"Find"



我想在Excel工作表中找到一个字符串。Excel单元格值是使用公式计算的。当我运行这段代码时:

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

我有一个错误说:

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

你得到.Find行错误信息的原因是vbscript不识别excel常量,所以你需要用数字-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:MyrouteexcelName.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)

相关内容

最新更新