好的,我正在尝试在VBA中创建一个复杂的地理编码脚本。我编写了以下代码,但由于某种原因,它返回了一个错误(“运行时错误91:对象变量或未设置块变量”)。我使用的链接的一个例子可以是:"https://maps.googleapis.com/maps/api/geocode/xml?address=1+Infinite+Loop,+Cupertino,+Santa+Clara,+California+95014&sensor=false"。
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有人能告诉我我哪里做错了吗?
发布于 2012-11-09 00:06:41
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发布于 2012-11-08 23:47:28
为什么lng上的/location/lat和.Text之前有空格,而不是lat?
发布于 2012-11-09 03:33:32
当我尝试在不使用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").Texthttps://stackoverflow.com/questions/13292364
复制相似问题