好的,我正在尝试在VBA中制作复杂的地理编码脚本。我编写了以下代码,由于某种原因它返回错误(“运行时错误91:对象变量或未设置块变量”)。我使用的链接示例可以是:“https://maps.googleapis.com/maps/api/geocode/xml?address=1+Infinite+Loop,+Cupertino,+Santa+Clara,+California+95014& ;传感器=假”
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
谁能告诉我我做错了什么?
答案 0 :(得分:1)
SelectSingleNode()
可能会返回Nothing
。
如果该函数的结果可以是.Text
,则永远不要在函数上调用属性(如Nothing
)。
执行以下操作以避免此错误:
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
答案 1 :(得分:0)
为什么/ position / lat之前的空格和lng上的.Text而不是lat?
答案 2 :(得分: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