得到错误91“对象变量或未设置块变量”

时间:2018-09-11 17:37:26

标签: excel vba xpath

运行下面的代码将引发错误91。这有什么问题?

Sub abc()
    Dim objIE As InternetExplorer
    Set objIE = New InternetExplorer
    Dim elem As HTMLBaseElement
    objIE.Visible = True

    objIE.navigate "https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuote.jsp?symbol=COALINDIA"
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop

    Set elem = getXPathElement("/html[1]/body[1]/div[2]/div[4]/div[2]/div[1]/div[4]/ul[1]/li[1]/span[1]", objIE.document)
    Range("A5").Value = elem.innerText

End Sub

公共函数getXPathElement(sXPath作为字符串,objElement作为HTMLBaseElement)作为HTMLBaseElement     将sXPathArray()变暗为字符串

Dim sNodeName As String
Dim sNodeNameIndex As String
Dim sRestOfXPath As String
Dim lNodeIndex As Long
Dim lCount As Long

' Split the xpath statement
sXPathArray = Split(sXPath, "/")
sNodeNameIndex = sXPathArray(1)
If Not InStr(sNodeNameIndex, "[") > 0 Then
    sNodeName = sNodeNameIndex
    lNodeIndex = 1
Else
    sXPathArray = Split(sNodeNameIndex, "[")
    sNodeName = sXPathArray(0)
    lNodeIndex = CLng(Left(sXPathArray(1), Len(sXPathArray(1)) - 1))
End If
sRestOfXPath = Right(sXPath, Len(sXPath) - (Len(sNodeNameIndex) + 1))

Set getXPathElement = Nothing
For lCount = 0 To objElement.ChildNodes().Length - 1
    If UCase(objElement.ChildNodes().Item(lCount).nodeName) = UCase(sNodeName) Then
        If lNodeIndex = 1 Then
            If sRestOfXPath = "" Then
                Set getXPathElement = objElement.ChildNodes().Item(lCount)
            Else
                Set getXPathElement = getXPathElement(sRestOfXPath, objElement.ChildNodes().Item(lCount))
            End If
        End If
        lNodeIndex = lNodeIndex - 1
    End If
Next lCount

结束功能

1 个答案:

答案 0 :(得分:1)

该元素具有您可以代替使用的ID

Option Explicit
Public Sub abc()
    Dim objIE As InternetExplorer, elem As HTMLBaseElement
    Set objIE = New InternetExplorer
    objIE.Visible = True

    objIE.navigate "https://www.nseindia.com/live_market/dynaContent/live_watch/get_quote/GetQuote.jsp?symbol=COALINDIA"
    Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop

    Set elem = objIE.document.getElementById("lastPrice")
    Debug.Print elem.innerText
    ThisWorkbook.Worksheets("Sheet1").Range("A5").Value = elem.innerText
    objIE.Quit
End Sub

我猜测getXPathElement是自定义函数吗?没有本机的XPath选择器方法。如果是这样,请在您的问题中包括该函数,如果您必须使用该函数有一个解决方案。