2012-11-08 119 views
0

好吧,所以我試圖在VBA中創建一個複雜的地理編碼腳本。我寫了下面的代碼,由於某種原因,它返回一個錯誤(「運行時錯誤91:對象變量或With塊變量未設置」)。我使用的鏈接示例可以是:「https://maps.googleapis.com/maps/api/geocode/xml?address=1+Infinite+Loop,+Cupertino,+Santa+Clara,+California+95014 & sensor = false「。VBA返回「運行時錯誤91:對象變量或未設置塊變量」

Sub readXML(link As String) 
Dim odc As DOMDocument 
Dim lat As IXMLDOMElement 
Dim lng As IXMLDOMElement 

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

lat = odc.SelectSingleNode("GeocodeResponse/result/geometry[location_type='ROOFTOP']/location/lat").Text 
lng = odc.SelectSingleNode("GeocodeResponse/result/geometry[location_type='ROOFTOP']/location/lng").Text 

Debug.Print lat & "; " & lng 
End Sub 

有誰能告訴我我做錯了什麼嗎?

+1

如果你確切地指出你的錯誤在哪裏,總是有幫助的。很可能你的一個xpaths不會導致任何選定的節點。 –

回答

1

SelectSingleNode()可能會返回Nothing

如果該函數的結果可能是Nothing,則不要調用某個函數的屬性(如.Text)。

做這樣的事情,以避免這個錯誤:

Dim location As IXMLDOMElement 
Dim locationPath As String 

locationPath = "GeocodeResponse/result/geometry[location_type='ROOFTOP']/location" 
Set location = odc.SelectSingleNode(locationPath) 

lat = GetTextValue(location, "./lat") 
lng = GetTextValue(location, "./lng") 


' ------------------------------------------------------------------------ 

Function GetTextValue(node As IXMLDOMElement, Optional xpath As String = "") As String 
    Dim selectedNode As IXMLDOMElement 

    If xpath <> "" And Not node Is Nothing Then 
    Set selectedNode = node.SelectSingleNode(xpath) 
    Else 
    Set selectedNode = node 
    End If 

    If selectedNode Is Nothing Then 
    GetTextValue = "" 
    Else 
    GetTextValue = Trim(selectedNode.Text) 
    End If 
End Function 
+0

相同的錯誤,但在行「Set selectedNode = node.SelectSingleNode(」./「&xpath)」「。 另外,我在「如果selectedNode是Nothing」行中出現了一個語法錯誤,但我添加了「Then」,並且我沒有再收到該語法錯誤。 – MartinUKPL

+0

@MartinUKPL哎呀,有'那麼'失蹤。我也移動了'。/'。再試一次。 – Tomalak

+0

同樣的錯誤,但現在在'lat = GetTextValue(location,「./lat」)' – MartinUKPL

0

爲什麼在lng之前的空格/位置/ lat和.Text不是lat?

+0

對不起,我在將代碼複製到Firefox時犯了這些錯誤。 – MartinUKPL

+0

好吧我會建議找到引發此錯誤的行以進一步探究哪些以及爲什麼未設置對象。我注意到你沒有在Dim和Set上指定MSXML2。 –

0

這總是發生在我身上時,我嘗試將值分配給一個對象,而無需使用set。試試這個:

Set lat = odc.SelectSingleNode("GeocodeResponse/result/geometry[location_type='ROOFTOP']/location/lat").Text 
Set lng = odc.SelectSingleNode("GeocodeResponse/result/geometry[location_type='ROOFTOP']/location/lng").Text 
+0

節點的'.text'屬性返回一個字符串,而不是一個對象。 –

+0

啊,錯過了舊的「需要讀到底」的板栗。哎呦!謝謝你的提示。 –

相關問題