2016-02-11 117 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