用于将数字提取到多个单元格的VBA代码

问题描述 投票:0回答:1

嗨,我很难将数字放到多个单元格中。我只是想将财务数据按顺序放入单元格中,但我不知道为什么它不起作用。 (代码由另一个问题帖子给出,我无法完全理解节点层次结构和语句如何结合for-loop一起工作)

我认为我的问题是在Range()方面申请循环。

我想指定停止(对于~~ [此停止条件],

以及接收数字但是范围(“D”和i)= ~~ innerText的单元格范围不起作用

Sub FetchFinanceInfo()
    Dim XMLReq As New XMLHTTP60, HTMLDoc As New HTMLDocument
    Dim post As Object, i&

    XMLReq.Open "GET", "https://finance.yahoo.com/quote/BABA/cash-flow?p=BABA", False
    XMLReq.send
    HTMLDoc.body.innerHTML = XMLReq.responseText

    For Each post In HTMLDoc.getElementsByTagName("span")
        If InStr(post.innerText, "From Operating Activities") > 0 Then
            With post.ParentNode.ParentNode.getElementsByTagName("td")
                For i = 1 To .Length - 1
                    Range("D4:D20") = post.ParentNode.ParentNode.getElementsByTagName("td")(1).innerText
                Next i
            End With
            Exit For
        End If
    Next post
End Sub
html vba web-scraping
1个回答
0
投票

您可以使用以下内容:

Option Explicit
Sub FetchFinanceInfo()
    Dim XMLReq As New XMLHTTP60, HTMLDoc As New HTMLDocument
    Dim post As Object, i&

    XMLReq.Open "GET", "https://finance.yahoo.com/quote/BABA/cash-flow?p=BABA", False
    XMLReq.send
    HTMLDoc.body.innerHTML = XMLReq.responseText
    Dim td As Object, tds As Object
    Set tds = HTMLDoc.getElementsByClassName("Bdbw(0px)! H(36px)")(1).getElementsByTagName("td")
    For Each td In tds
        ActiveSheet.Cells(4 + i, 4) = td.innerText
        i = i + 1
    Next
End Sub

或者调整你的例子,忽略行的标题单元格

Sub FetchFinanceInfo()
    Dim XMLReq As New XMLHTTP60, HTMLDoc As New HTMLDocument
    Dim post As Object, i&

    XMLReq.Open "GET", "https://finance.yahoo.com/quote/BABA/cash-flow?p=BABA", False
    XMLReq.send
    HTMLDoc.body.innerHTML = XMLReq.responseText

    For Each post In HTMLDoc.getElementsByTagName("span")
        If InStr(post.innerText, "From Operating Activities") > 0 Then
            With post.ParentNode.ParentNode.getElementsByTagName("td")
                For i = 1 To .Length - 1
                     ActiveSheet.Cells(3 + i, 4) = .item(i).innerText
                Next i
            End With
            Exit For
        End If
    Next post
End Sub
© www.soinside.com 2019 - 2024. All rights reserved.