Using Excel VBA to import website table created by

2019-09-07 22:39发布

问题:

I'm trying to extract a table from a website using Excel VBA, but the table is created using JavaScript, and I really don't know how to do it.

Generally, I extract a table something like this:

Dim Document As Object
Dim StatementTable As HTMLTable

Set Document = CreateObject("HTMLFile")

With CreateObject("msxml2.xmlhttp")
    .Open "GET", Url, False
    .send
    Do: DoEvents: Loop Until .readyState = 4
    Document.body.innerHTML = .responseText
    .abort
End With

Set StatementTable = Document.getElementById("TableID")

With StatementTable
    For r = 0 To .Rows.Length - 1
        For c = 0 To .Rows(r).Cells.Length - 1

            Sheets(Destination).Cells(r + 1, c + 1).Value = .Rows(r).Cells(c).innerText
        Next c
    Next r
End With

I tried doing something similar at this link:

http://financials.morningstar.com/income-statement/is.html?t=JPM&region=USA&culture=en-US

However, as I said, the table is created with JavaScript and is not natively in the HTML file.

I browsed the source code, and it appears that the JavaScript that creates the table is executed in lines 238-242 of the HTML file:

<script type="text/javascript">
    var print4com = false
    SRT_stocFund.LoadAComponent("sfcontent", "JPM", "is", "en-US","USA", "", "usa", null,{showSubTab: false}, {refresh:"", urlAppendix:"&t=XNYS:JPM&region=usa&culture=en-US&cur=USD"});
    var ops = "";
</script>

I just have no idea how to load this into VBA and import it into Excel, though.

Also, I'd like to avoid using Internet Explorer, if possible.

Thanks for any help you can provide.

-Ryan

回答1:

VBScript and JScript share the global namespace so something like this should work:

<script type="text/javascript">
    var print4com = false
    js_data = SRT_stocFund.LoadAComponent("sfcontent", "JPM", "is", "en-US","USA", "", "usa", null,{showSubTab: false}, {refresh:"", urlAppendix:"&t=XNYS:JPM&region=usa&culture=en-US&cur=USD"});
    var ops = "";
</script>

<script type="text/vbscript">
  Dim vb_data = js_data
</script>

Importing from VBScript into Excel is covered in detail elsewhere.