Search code examples
excelvbagetelementbyidgetelementsbyclassnamemshtml

Unable to retrieve contents of element id


Unable to retrieve elements contents using excel vba

Option Explicit
Dim XMLPage As New MSXML2.XMLHTTP60
Dim HTMLDoc As New MSHTML.HTMLDocument
Dim HTMLInput As MSHTML.IHTMLElement
Dim HTMLButtons As MSHTML.IHTMLElementCollection
Dim HTMLbutton As MSHTML.IHTMLElement
Dim HTMLTables As MSHTML.IHTMLElementCollection

Sub Test1()

Dim URL As String, PriceNSE As Object
URL = "https://www.google.com/finance/quote/TATAMOTORS:NSE"

With XMLPage
    .Open "GET", URL, False
    .send
End With

Set PriceNSE = HTMLDoc.getElementsByClassName("YMlKec fxKbKc")(0)
Debug.Print PriceNSE.innerText

End Sub

I have tried to getelemenybyid, but no yielded no result.


Solution

  • You need to assign the HTTP response text to your HTML document as follows...

    With XMLPage
        .Open "GET", URL, False
        .send
        HTMLDoc.body.innerHTML = .responseText
    End With
    

    EDIT

    For your follow-up question, try...

    Dim txt As String
    Dim pos As Long
    txt = SymbolNSE.innerText
    txt = Mid$(txt, 1 + IIf(Left$(txt, 4) = "Home", 4, 0))
    pos = InStr(1, txt, " ")
    If pos > 0 Then
        txt = Left$(txt, pos - 1)
    End If
    
    Debug.Print txt