2016-02-11 78 views
0

我是一名高中生做科学研究项目。虽然我对通用编程和逻辑有很好的理解,但我并没有在Excel中编程的经验。这是我的第一篇文章。如何使用VBA将XML中的数据转换为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

非常感谢你提前为任何帮助!

回答

0

VBA项目引用添加到库中 “微软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