2012-11-05 70 views
3

我想創建一個VBA腳本,讓我地理編碼我的地址數據庫。我一直在研究這個腳本幾天,我認爲有一段時間我不得不請專家提供一些建議。 因此,我想讓腳本訪問谷歌地圖網址並查找經度和緯度值。我設法從本地XML文檔中提取該信息,但我無法使用從Google地圖服務器讀取的XML。爲我工作的代碼如下:使用VBA自動地理編碼

Sub XMLread() 
Dim odc As DOMDocument 
Dim nde As IXMLDOMNode 
Dim lat As IXMLDOMElement 
Dim url As String 

Set odc = New MSXML2.DOMDocument 
url = "C:\~path~\address.xml" 
odc.Load (url) 

For Each nde In odc.SelectNodes("GeocodeResponse/result/geometry/location") 
    Set lat = nde.SelectSingleNode("lat") 
    Debug.Print lat.Text 
Next 
End Sub 

這段代碼所做的就是打開一個XML文件,發現在調試窗口中的「緯度」,並打印出來的價值。我打算將結果放在電子表格中,但這不是問題。問題是直接從服務器提取數據。我使用下面的代碼:

Sub XMLerverRead() 
Dim odc As DOMDocument 
Dim nde As IXMLDOMNode 
Dim lat As IXMLDOMElement 
Dim url As String 
url="https://maps.googleapis.com/maps/api/geocode/xml?address=1+Infinite+Loop,+Cupertino,+Santa+Clara,+California+95014&sensor=false" 

Set odc = New MSXML2.DOMDocument 
odc.async = False 
odc.Load (url) 

For Each nde In odc.SelectNodes("GeocodeResponse/result/geometry/location") 
    Set lat = nde.SelectSingleNode("lat") 
    Debug.Print lat.Text 
Next 
End Sub 

而上述代碼不會返回任何內容,甚至不會發生錯誤。您能否幫我解決問題並告訴我如何解決這個問題?先謝謝你。

P.S.我是VBA新手,但我在這個問題上做了很好的研究。

+0

我測試了你的代碼,它工作正常。 – CaBieberach

+0

什麼......實際上,我將它複製到一個新的工作表中並且它工作正常。但它返回兩個值 - 37.3317055和37.3318200。這可能是因爲執行兩次的For循環。我能以某種方式擺脫那個循環嗎? – MartinUKPL

+0

當然可以。使用Xpath來定義你想要的哪一個。 – CaBieberach

回答

4

試試這個:

Sub XMLerverRead() 
    Dim odc As DOMDocument 
    Dim url As String 
    Dim lat As String 

    url="https://maps.googleapis.com/maps/api/geocode/xml?address=1+Infinite+Loop,+Cupertino,+Santa+Clara,+California+95014&sensor=false" 

    Set odc = New MSXML2.DOMDocument 
    odc.async = False 
    odc.Load (url) 

    If odc Is Nothing Then 
     MsgBox "Odc is not loaded with the Xml." 

    Else 
     lat= vbNullString  'This is to assure that the variable lat has no value.'  
     On Error Resume Next 'We dont want to show the user a system msgbox if the node does not exist' 
     lat = odc.SelectSingleNode("GeocodeResponse/result/geometry[location_type='ROOFTOP']/location/lat").Text 
     On Error Goto 0 

     If lat=vbNullString Then 'Here you can show the user some useful info or do something with your code instead' 
     MsgBox "There is no Latitude value for a 'ROOFTOP' node in the given XML" 
     End If 
    End If   

End Sub 

編輯:

我做的代碼做一些修改,以幫助您解答。

說明: 爲了舉例,我使用了節點'ROOFTOP'。如果您在找到第一個緯度值時沒問題,則可以使用以下任一選項。

odc.SelectSingleNode("GeocodeResponse/result/geometry/location/lat") 
odc.SelectSingleNode("//lat") 

你讀到的Xpath越多,你的任務就越容易。重要的是要注意,VBA僅適用於Xpath 1.0(不支持Xpath 2)。

+0

完美!非常感謝你。 – MartinUKPL

+0

其實,我剛開始出現一個錯誤 - 「對象變量或塊變量未設置」。調試器突出顯示了我將值賦給lat的行:lat = odc.SelectSingleNode(「GeocodeResponse/result/geometry [location_type ='ROOFTOP']/location/lat」)文本 – MartinUKPL

+0

如果我想分配最後一行你的代碼到「lat」變量是否必須以某種特殊的方式聲明該變量?或者我必須使用「設置」? – MartinUKPL