使用vba从网站表中获取数据

时间:2013-08-10 09:17:04

标签: vba fetch msxml

我需要不断更新excel文件的信息,从以下链接获得(警告,乌克兰语): link to the Ministry of Finance web-site of Ukraine

有用的数据由HTML标记<tbody></tbody>包装。

我需要类似的代码来检索表中的信息

Set htm = CreateObject("htmlFile")' #it doesn't work on mac os machine, but perfectly performs on windows
    With CreateObject("msxml2.xmlhttp")
        .Open "GET", <site_url_goes_here>, False
        .send
        htm.body.innerhtml = .responsetext
    End With

    With htm.getelementbyid("item")' <<<<<---what should I write here in order to parse data from the web-site table?
        Sheet2.Cells(Row, 4).Value = p
        For x = 1 To .Rows.Length - 1
            For y = 0 To .Rows(x).Cells.Length - 1
                Sheet2.Cells(Row, y + 1).Value = .Rows(x).Cells(y).innertext
            Next y
            Row = Row + 1
        Next x
    End With`

1 个答案:

答案 0 :(得分:0)

以下代码将每隔60秒从http://www.minfin.gov.ua获取更新数据。

Sub getData()

    Application.OnTime Now + TimeSerial(0, 0, 60), "finance_data"

End Sub

Private Sub finance_data()
    Dim url As String, lastRow As Long
    Dim XMLHTTP As Object, html As Object
    Dim tbl As Object, obj_tbl As Object
    Dim TR As Object, TD As Object
    Dim row As Long, col As Long

    lastRow = Range("A" & Rows.Count).End(xlUp).row

    url = "http://www.minfin.gov.ua/control/uk/publish/article?art_id=384069&cat_id=234036" & "&r=" & WorksheetFunction.RandBetween(1, 10000)

    Set XMLHTTP = CreateObject("MSXML2.XMLHTTP")
    XMLHTTP.Open "GET", url, False
    XMLHTTP.setRequestHeader "Content-Type", "text/xml"
    XMLHTTP.send

    Set html = CreateObject("htmlfile")
    html.body.innerHTML = XMLHTTP.ResponseText
    Set obj_tbl = html.getelementsbytagname("table")

    row = 1
    col = 1

    For Each tbl In obj_tbl
        If tbl.classname = "MsoNormalTable" Then
            Set TR = tbl.getelementsbytagname("TR")

            For Each obj_row In TR
                For Each TD In obj_row.getelementsbytagname("TD")
                    Cells(row, col) = TD.innerText
                    col = col + 1
                Next
                col = 1    ' reseting the value
                row = row + 1
            Next
        End If
    Next

    getData
End Sub