【问题标题】:Runtime error 91 “Object variable or with block variable not set”运行时错误 91 “对象变量或未设置块变量”
【发布时间】:2020-03-11 10:49:41
【问题描述】:
Sub FindUser()

Dim ie as shdocvw.internetexplorer
Dim ht as htmldocument

Set ie = new internetexplorermedium
Ie.visible = True
Ie.navigate ("url")

Do while ie.busy or ie.readystate <> 4
Doevents
Loop

Set ht = ie.document

Activesheet.range("b30").value = ht.getelementbyid("infobasic").getelementsbytagname("span") (0).innertext

End sub

粗体文本(活动表...行)出现错误。但是,如果我继续手动运行代码,我会在单元格中获得所需的值。这只是中间的错误。请帮忙。我想将网络数据放入 Excel 单元格。在代码中我只提到了一个标签,但是我将使用更多标签来从网络中获取更多结果。

【问题讨论】:

  • 我会首先检查您尝试放入单元格中的内容是否做得很好。请尝试在有问题的行上方插入下一行:Debug.Print ht.getelementbyid("infobasic").getelementsbytagname("span") (0).innertext。然后,按 Ctrl + G 并查看 innertext 的第一个元素是否已返回。也许你拼错了一个标签名...在这种情况下,错误将移动到新插入的行。
  • 我尝试添加 Debug.Print ht.getelementbyid("infobasic").getelementsbytagname("span") (0).innertext 它没有给出任何内容并在调试代码上收到错误 91 但如果我继续运行它给了我结果值的代码。

标签: excel vba web-scraping


【解决方案1】:

该错误表示您正在尝试访问为空的对象的属性。

您需要稍微扩展您的方法,并在尝试访问其属性之前检查每个对象以避免此类错误。

例如:

Dim objInfo as Object
Set objInfo = ht.getelementbyid("infobasic")

If objInfo Is Nothing then
    'no need to go any further here as the object is null and 
    'will throw an error if you try to access its properties.
End if

Dim elements as Object
Set elements = objInfo.getelementsbytagname("span")

If elements Is Nothing then
    'same as above
End if

Dim element as Object
Set element = elements(0)

If Not element Is Nothing then
    'here you can safely access the .innerText property
End if


通过上面的调试,可以看到哪个对象没有被设置。

希望这会有所帮助。

【讨论】:

    猜你喜欢
    • 2016-10-07
    • 2017-05-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多