如何使用VBA将数据从XML获取到Excel?

时间:2016-02-11 05:27:12

标签: xml excel vba excel-vba

我是一名从事科学研究项目的高中生。虽然我对通用编程和逻辑有很好的理解,但我对excel编程没有经验。这是我的第一篇文章。

我做了彻底的谷歌搜索,但我似乎无法找到我正在寻找的东西。 在这里,我只需要从这个Web服务中获取高程数据:hhttp://ned.usgs.gov/epqs/ 我需要知道的是如何让excel从xml中获取内部文本,例如:http://ned.usgs.gov/epqs/pqs.php?x=-73.06&y=40.8725&units=Feet&output=xml

到目前为止,这是我的代码:

    Sub elevgrabwebserv()

Dim Doc As HTMLDocument
Dim elev As String
Dim lat As String
Dim longt As String
Dim sht As Worksheet
Dim IE As New InternetExplorer
Set sht = ThisWorkbook.Worksheets("Both")

IE.Visible = False

lr = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row

For i = 3 To lr
If sht.Cells(i, 7) > 0 And IsEmpty(sht.Cells(i, 14)) Then

lat = sht.Cells(i, 7)
longt = sht.Cells(i, 8)

IE.navigate "http://ned.usgs.gov/epqs/pqs.php?x=" & longt & "&y=" & lat & "&units=Feet&output=xml"

Do
DoEvents
Loop Until IE.readyState = READYSTATE_COMPLETE
Set Doc = IE.document

'here below is the problem
elev = Doc.getElementsByName("elevation").innerText

'from here parse the inner text to fit my needs



End If
Next i

End Sub

Here is the sample data that I need to get. As you can see, I need to run this web service many times, hence my for loop

非常感谢你提前帮忙!

1 个答案:

答案 0 :(得分:0)

向库中添加VBA项目引用" Microsoft VML v6.0":

Sub Tester()
    Debug.Print Elevation(-73.06, 40.8725)
End Sub


Function Elevation(x, y)
    Dim http As New XMLHTTP60
    Dim doc As New MSXML2.DOMDocument60
    http.Open "GET", "http://ned.usgs.gov/epqs/pqs.php?x=" & x & _
                     "&y=" & y & "&units=Feet&output=xml"
    http.send
    doc.LoadXML http.responseText
    Elevation = doc.getElementsByTagName("Elevation")(0).nodeTypedValue
End Function