首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >VBA返回“运行时错误91:对象变量或未设置块变量”

VBA返回“运行时错误91:对象变量或未设置块变量”
EN

Stack Overflow用户
提问于 2012-11-08 23:42:32
回答 3查看 6.6K关注 0票数 0

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

代码语言:javascript
复制
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

有人能告诉我我哪里做错了吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-11-09 00:06:41

SelectSingleNode()可能返回Nothing

如果函数的结果可以为Nothing,则永远不要对该函数调用属性(如.Text)。

执行以下操作以避免此错误:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2012-11-08 23:47:28

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

票数 0
EN

Stack Overflow用户

发布于 2012-11-09 03:33:32

当我尝试在不使用set的情况下为对象赋值时,这种情况总是发生在我身上。试试这个:

代码语言:javascript
复制
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
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13292364

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档