Getting “subscript out of range” error from “Find” result

前端 未结 1 1065
梦谈多话
梦谈多话 2021-01-07 02:10

I would like to find a string in an Excel worksheet. The Excel cell values are calculated using formulas. When I run this code:

Set firstExcel = CreateObject         


        
1条回答
  •  别那么骄傲
    2021-01-07 02:48

    The reason you get the error message on the .Find line is that vbscript does not recognize Excels constants, so you need to replace xlValues with the number -4163. (All Excel constant values can be found in the VBA Object Browser).

    Also, the line you wrote Set oSht = firstExcel.Worksheets("Input Data") does not make sense to VB because firstExcel is the Excel Application itself and there is no Worksheet object associated with the Excel Application itself, but there is within the Workbook object.

    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
    

    Furthermore you could declare a constant at the top of your code and use that constant in the .Find statement.

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

    0 讨论(0)
提交回复
热议问题