有没有一种方法可以在VBA中选择元素集合中的某些元素

时间:2020-05-19 11:18:25

标签: html vba loops if-statement screen-scraping

我还是VBA和数据抓取的新手。我想检查是否有一种方法可以选择元素集合中的某些元素。我的VBA代码如下:

Sub Refresh()
    Dim XMLPage As New MSXML2.XMLHTTP60
    Dim HTMLDoc As New MSHTML.HTMLDocument
    Dim HTMLTable As MSHTML.IHTMLElementCollection
    Dim Price As Variant, Change As Variant, Volume As Variant
    Dim HTMLTag As MSHTML.IHTMLElement

    XMLPage.Open "GET", Mapping.Range("B2"), False
    XMLPage.send
    HTMLDoc.body.innerHTML = XMLPage.responseText

    Set HTMLTable = HTMLDoc.getElementsByClassName("stockinfocol1")

    For Each HTMLTag In HTMLTable
    Debug.Print HTMLTag.innerText
    Next HTMLTag
End Sub

debug.print的结果如下:

最后交易价1.200

更改-0.030 / -2.44%

交易量为1,291,800

日范围1.190-1.250

最后交易日期2020-05-19

备注

但是,我只需要此集合中的某些元素(例如:最后交易的股价和交易量)。有没有一种方法可以执行For Each和IF语句来筛选我想要的元素?

HTML代码在这里供您参考:

<div class="stockinfocol1"><div title="AIMS APAC REIT Share Price" class="stockinfocol1row1"><span class="label">Last Traded Share Price </span><span class="value red">1.200</span></div><div class="stockinfocol1row"><span class="label">Change </span><span class="value red" label="change">-0.030 / -2.44%</span></div><div title="AIMS APAC REIT Volume Traded" class="stockinfocol1row"><span class="label">Volume Traded </span><span class="value" label="volume">1,218,700</span></div><div title="AIMS APAC REIT Day Price Range" class="stockinfocol1row"><span class="label">Day Range </span><span class="value" label="Day Range">1.190 - 1.250</span></div><div title="AIMS APAC REIT Last Traded Date" class="stockinfocol1row"><span class="label">Last Traded Date </span><span class="value" label="Last Traded Date">2020-05-19</span></div><div title="AIMS APAC REIT Remarks" class="stockinfocol1row"><span class="label">Remarks </span><span class="value" label="Remarks"> </span></div></div>

1 个答案:

答案 0 :(得分:0)

尝试这种方法

Sub Test()
    Dim html As New HTMLDocument, post As Object, sPriceTraded As String, sVolumeTraded As String, i As Long
    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "C:\Sample.html", False
        .send
        html.body.innerHTML = .responseText
    End With
    sPriceTraded = "Last Traded Share Price"
    sVolumeTraded = "Volume Traded"
    Set post = html.querySelectorAll(".stockinfocol1 div")
    With post
        For i = 0 To .Length - 1
            With .Item(i)
                If InStr(.innerText, sPriceTraded) Then
                    Debug.Print Trim(Replace(.innerText, sPriceTraded, vbNullString))
                End If
                If InStr(.innerText, sVolumeTraded) Then
                    Debug.Print Trim(Replace(.innerText, sVolumeTraded, vbNullString))
                End If
            End With
        Next i
    End With
End Sub