我尝试使用VBA代码将HTML元素中的数据提取或提取到Excel中:https://drive.google.com/file/d/1_fGBlOLzMxmV3r-WwC8klcBNB7wUuJN2/view?usp=sharing
我的想法是从HTML网站中提取并提取黄色突出显示的汇率数据:https://drive.google.com/file/d/1LACA6quFz_Am6mGVjGQ39xvehtX1sybB/view?usp=sharing
[不幸的是,当我尝试运行代码时,它将错误编译为“运行时错误445”,并且“对象不支持此操作”]
感谢某人可以指导我找出错误所在。以下是我完整的VBA代码:
Sub ExchangeRate()
Dim ieObj As InternetExplorer
Dim htmlEle As IHTMLElement
Dim htmlEleCollection As IHTMLElementCollection
Dim i As Integer
i = 1
Set ieObj = New InternetExplorer
ieObj.Visible = True
ieObj.navigate "https://secure.mas.gov.sg/msb/ExchangeRatesFeed.aspx?currency=jpy"
While ieObj.readyState <> 4 Or ieObj.Busy: DoEvents: Wend
Set htmlEleCollection = ieObj.document.getElementsByClassName("paditembox").Item(0).getElementsById("item").Value
For Each htmlEle In htmlEleCollection
If htmlEle.Children.Length > 1 Then
With ActiveSheet
.Range("A" & i).Value = htmlEle.Children(0).textContent
.Range("B" & i).Value = htmlEle.Children(1).textContent
.Range("C" & i).Value = htmlEle.Children(2).textContent
.Range("D" & i).Value = htmlEle.Children(3).textContent
.Range("E" & i).Value = htmlEle.Children(4).textContent
.Range("F" & i).Value = htmlEle.Children(5).textContent
.Range("G" & i).Value = htmlEle.Children(6).textContent
End With
End If
i = i + 1
Next htmlEle
End Sub
如果我说对了,那么下面的内容应该会带给您您想从那里获取的内容。
Sub fetchData()
Const Url = "https://secure.mas.gov.sg/msb/ExchangeRatesFeed.aspx?currency=jpy"
Dim oItem As Object, Xdoc As New DOMDocument, R&
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", Url, False
.send
Xdoc.LoadXML .responseText
End With
For Each oItem In Xdoc.getElementsByTagName("item")
R = R + 1: Cells(R, 1) = oItem.getElementsByTagName("description")(0).Text
Next oItem
End Sub
添加到库中的参考:
Microsoft HTML Object Library
这是上面脚本产生的输出类型:
100 Japanese Yen buys 1.3006 Singapore Dollars
100 Japanese Yen buys 1.3001 Singapore Dollars
100 Japanese Yen buys 1.2986 Singapore Dollars
100 Japanese Yen buys 1.2887 Singapore Dollars
100 Japanese Yen buys 1.2857 Singapore Dollars
100 Japanese Yen buys 1.2726 Singapore Dollars
100 Japanese Yen buys 1.2773 Singapore Dollars
您可以进行字符串操作或应用正则表达式以从上述结果中找出想要的部分。