Excel 2010 VBA - 从网站上拉表

时间:2014-02-07 20:50:59

标签: excel vba excel-vba

我是Excel VBA的新手,我获得了一些代码。我成功修改了一次,但之后我又尝试修改它,它不会提取正确的信息。可能是因为我不知道表格ID是肯定的吗?我不明白这个例子中的所有代码......这可能是另一个问题。无论如何我试图从this page拉出历史价格表。它会提取一些数据,但不会提供正确的数据。任何帮助,将不胜感激。谢谢!

这是我目前的代码:

Sub GrabHistData()

    Dim Ptrtbl As Long, r As Long, c As Long
    Dim htm As Object
    Dim elemCollection As Object

    Set htm = CreateObject("htmlFile")

    With CreateObject("msxml2.xmlhttp")
        .Open "GET", "http://finance.yahoo.com/q/hp?s=TWTR&a=04&b=30&c=2012&d=01&e=7&f=2014&g=d", False
        .send
        htm.body.innerhtml = .responsetext
    End With

    Set elemCollection = htm.getElementsByTagName("TABLE")

    Ptrtbl = 1
    For Each elem In elemCollection
        Ptrtbl = Ptrtbl + 1
        If elem.ID <> "yfncsumtab" Then GoTo Nxtelem
        With elemCollection(Ptrtbl)

                For c = 0 To (.Rows(r).Cells.Length - 1)
                    Cells(r + 1, c + 1) = .Rows(r).Cells(c).innertext
                Next c

        End With
        Exit For
Nxtelem:
    Next elem

End Sub

1 个答案:

答案 0 :(得分:0)

如果你想坚持现有的做法,这对我有用......

Sub GrabHistData()
    Dim Ptrtbl As Long, r As Long, c As Long
    Dim htm As Object
    Dim elemCollection As Object

    Set htm = CreateObject("htmlFile")

    With CreateObject("msxml2.xmlhttp")
        .Open "GET", "http://finance.yahoo.com/q/hp?s=TWTR&a=04&b=30&c=2012&d=01&e=7&f=2014&g=d", False
        .send
        htm.body.innerhtml = .responseText
    End With

    Set elemCollection = htm.getElementsByTagName("td")
    For Each itm In elemCollection
        If itm.classname = "yfnc_tabledata1" Then
            ActiveCell = itm.innertext

            If ActiveCell.Column = 7 Then
                ActiveCell.Offset(1, -6).Select
            Else
                ActiveCell.Offset(0, 1).Select
            End If
        End If
    Next
End Sub