Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
565 views
in Technique[技术] by (71.8m points)

javascript - Excel VBA: Get inner text of HTML table td

I'm using excel to get values from a webpage. Among other elements, the HTML contains the following table:

<div id="myDiv">    
<table class="myTable">
        
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You seem to have a typo in your variable name. Have you used Option Explicit?

Function myFunction(id)
    Call myConnection(id)    
    Set myDadta = oHtml.getElementById("myDiv").getElementsByClassName("myTable")(0).getElementsByClassName("data")(0)
    myFunction = myData.innerText   ' <-- This line
End Function

UPDATE

I put a Button on VBA form and the following corrected code that works:

Option Explicit

Dim oHtml, myData

Private Sub CommandButton1_Click()
    MsgBox myFunction(0)
End Sub

Function myFunction(id)
    Call myConnection(id)
    Set myData = oHtml.getElementById("myDiv").getElementsByTagName("Table")(0).getElementsByTagName("td")(1)
    myFunction = myData.innerText ' <-- will give 0.51
End Function

Public Sub myConnection(id)
    Set oHtml = New HTMLDocument
    With CreateObject("WINHTTP.WinHTTPRequest.5.1")
        '.Open "GET", "http://www.example.com" & id, False
        .Open "GET", "http://localhost/Test/Test.htm", False   '<-- this is my local machine; replace appropriately
        .send
        oHtml.body.innerHTML = .responseText
    End With
End Sub

UPDATED CODE TO DEMONSTRATE FUNCTION ON LIVE URL

Option Explicit

Dim oHtml, myData

Private Sub CommandButton1_Click()
    MsgBox myFunction(0)
End Sub

Function myFunction(id)
    Call myConnection(id)
    Set myData = oHtml.getElementById("overallRatios").getElementsByTagName("Table")(0).getElementsByTagName("td")(1)
    myFunction = myData.innerText  
End Function

Public Sub myConnection(id)
    Set oHtml = New HTMLDocument
    With CreateObject("WINHTTP.WinHTTPRequest.5.1")
        '.Open "GET", "http://www.example.com" & id, False
        .Open "GET", "http://www.reuters.com/finance/stocks/overview?symbol=PTI.LS", False
        .send
        oHtml.body.innerHTML = .responseText
    End With
End Sub

screenshot of working demo


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...