【问题标题】:Convert Html String into HTMLDocument VBA将 Html 字符串转换为 HTMLDocument VBA
【发布时间】:2013-09-02 06:58:50
【问题描述】:

我正在编写一个宏来从 yahoo 获取当前汇率,但我无法将 html 字符串转换为 HTMLDocument 以允许我通过 id 搜索所需的元素。到目前为止,这是我的代码,但在 debug.print 行上失败了。

Public Sub Forex(currency1 As String, currency2 As String)

Dim oXHTTP As Object
Dim doc As HTMLDocument
Dim url As String
Dim html As String
Dim id As String

Set oXHTTP = CreateObject("MSXML2.XMLHTTP")

url = "http://finance.yahoo.com/q?s=" & currency1 & currency2 & "=X"

oXHTTP.Open "GET", url, False
oXHTTP.send

html = oXHTTP.responseText
Set oXHTTP = Nothing

Set doc = New HTMLDocument
doc.body.innerHTML = html

id = "yfs_l10_" & currency1 & currency2

Debug.Print doc.getElementById("id").innerText

End Sub

我在这里错过了什么?

【问题讨论】:

    标签: vba dom excel html-parsing


    【解决方案1】:

    我正在使用excel-vba-http-request-download-data-from-yahoo-finance的方法:

    Sub Forex(currency1 As String, currency2 As String)
    
        Dim url As String, html As String, id As String
        Dim oResult As Variant, oLine As Variant, sRate As String
    
    
        url = "http://finance.yahoo.com/q?s=" & currency1 & currency2 & "=X"
        id = "<span id=""yfs_l10_" & currency1 & currency2 & "=x"">"
        html = GetHTTPResult(url)
    
        oResult = Split(html, vbLf)
        For Each oLine In oResult
            If InStr(1, oLine, id, vbTextCompare) Then
                sRate = Split(Split(oLine, "<span id=""yfs_l10_audusd=x"">")(1), "</span>")(0)
                Exit For
            End If
        Next
    End Sub
    
    Function GetHTTPResult(sURL As String) As String
        Dim XMLHTTP As Variant, sResult As String
    
        Set XMLHTTP = CreateObject("WinHttp.WinHttpRequest.5.1")
        XMLHTTP.Open "GET", sURL, False
        XMLHTTP.send
        sResult = XMLHTTP.responseText
        Set XMLHTTP = Nothing
        GetHTTPResult = sResult
    End Function
    

    【讨论】:

    • 我有点失望,无法将 html 字符串转换为 htmldocument,但您的解决方案可以完美运行。谢谢!
    • 原始问题在另一个线程中得到了回答。 stackoverflow.com/q/9995257/1337544
    【解决方案2】:

    你快到了,只是你的 id 错了:

    id = "yfs_l10_" & currency1 & currency2 & "=X"
    
    Debug.Print doc.getElementById(id).innerText
    

    【讨论】:

      猜你喜欢
      • 2014-07-11
      • 2014-08-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-28
      • 2021-12-27
      • 1970-01-01
      相关资源
      最近更新 更多