0

好的,所以我正在尝试在 VBA 中制作一个复杂的地理编码脚本。我编写了以下代码,由于某种原因它返回错误(“运行时错误 91:对象变量或未设置块变量”)。我使用的链接示例可以是:“https://maps.googleapis.com/maps/api/geocode/xml?address=1+Infinite+Loop,+Cupertino,+Santa+Clara,+California+95014&sensor =假”。

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

谁能告诉我我做错了什么?

4

3 回答 3

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
于 2012-11-08T16:06:40.687 回答
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
于 2012-11-08T19:33:31.840 回答
0

为什么 /location/lat 之前的空格和 lng 上的 .Text 而不是 lat?

于 2012-11-08T15:47:27.607 回答