得到"下标超出范围"错误来自"查找"结果

时间:2015-10-15 14:11:36

标签: excel vbscript

我想在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

我有一个错误说:

  

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

1 个答案:

答案 0 :(得分:2)

您在.Find行上收到错误消息的原因是vbscript无法识别Excels常量,因此您需要将xlValues替换为数字-4163。 (可以在VBA对象浏览器中找到所有Excel常量值。)

此外,您编写的Set oSht = firstExcel.Worksheets("Input Data")行对VB没有意义,因为firstExcel是Excel应用程序本身,并且没有与Excel应用程序本身关联的 Worksheet 对象,但是在工作簿对象中。

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)
相关问题