我希望使用VBA每周从本网站下载汇率 我是XML新手,一直在寻找堆栈交换,并看到一些使用表单的实现(我想避免这种方法)
我尝试使用MS Access Wizard导入它,但表中的所有字段都是空白
我想尽可能实施这些步骤
目前我有以下代码。但它显然是基于其他人的工作而组合在一起的,并且更像是一个可以解决的模板 任何人都可以指出我正确的方向
Sub Test()
'**********************************************************
' DOWNLOAD XML DATA
' ref: http://stackoverflow.com/questions/7091162/access-vba-how-to-download-xml-file- and-enter-its-data-into-a-recordset
'**********************************************************
Dim obj As MSXML2.ServerXMLHTTP
Set obj = New MSXML2.ServerXMLHTTP
obj.Open "GET", "http://www.ecb.europa.eu/stats/eurofxref/eurofxref-daily.xml", False
'in case you are sending a form *POST* or XML data to a SOAP server set content type
obj.setRequestHeader "Content-Type", "text/xml"
obj.send
Dim status As Integer
status = obj.status
If status >= 400 And status <= 599 Then
Debug.Print "Error Occurred : " & obj.status & " - " & obj.statusText
End If
'**********************************************************
'CREATE XML DOM DOCUMENT
'**********************************************************
Dim xmlDoc As MSXML2.DOMDocument
Dim xmlElement As MSXML2.IXMLDOMElement
Dim xmlNode As MSXML2.IXMLDOMElement
Set xmlDoc = New MSXML2.DOMDocument
xmlDoc.loadXML (obj.responseText)
'**********************************************************
'ACCESS ROWS
'http://stackoverflow.com/questions/11305/how-to-parse-xml-in-vba
'**********************************************************
Dim point As IXMLDOMNode
Set point = xmlDoc.firstChild
Debug.Print point.selectSingleNode("subject").Text
End Sub
答案 0 :(得分:3)
使用XPath选择所需的元素,然后getAttribute
从每个选定的元素中提取currency
和rate
属性的值。
Const cstrXPath As String = "/gesmes:Envelope/Cube/Cube/Cube"
Dim xmlDoc As MSXML2.DOMDocument
Dim xmlElement As MSXML2.IXMLDOMElement
Dim xmlSelection As MSXML2.IXMLDOMSelection
Dim i As Long
Dim strUrl As String
strUrl = "http://www.ecb.europa.eu/stats/" & _
"eurofxref/eurofxref-daily.xml"
Set xmlDoc = New MSXML2.DOMDocument
xmlDoc.async = False
xmlDoc.Load strUrl
Set xmlSelection = xmlDoc.SelectNodes(cstrXPath)
Debug.Print "xmlSelection.Length: " & xmlSelection.Length
i = 1
For Each xmlElement In xmlSelection
Debug.Print i, xmlElement.getAttribute("currency"), _
xmlElement.getAttribute("rate")
i = i + 1
Next xmlElement
您可以在立即窗口中查看输出;你可以用 Ctrl + g 去那里。这是一个缩写输出样本......
xmlSelection.Length: 32
1 USD 1.3495
2 JPY 136.93
3 BGN 1.9558
最终,您希望存储这些值,而不仅仅是Debug.Print
。当你到达那一点时,请注意getAttribute
返回文本值。如果您要将rate
存储在数字字段中,例如。单,您可以在存储时将文本值转换为数字。
CSng(xmlElement.getAttribute("rate"))