运行时错误462与Internet Explorer

时间:2017-02-05 02:40:04

标签: excel vba

我正在尝试使用VBA从excel访问网页。我可以启动Internet Explorer,我看到网页出现了,但是当我点击Do Until internet.ReadyState> = 4行代码时出现运行时错误462。有任何想法吗?最终我希望能够解析一个网站并获得该网站上的链接列表并选择一个,然后点击"在那个链接上。建议和帮助会很棒。这是我正在使用的功能(我在网上找到的):

Public Sub clicklick()

Dim internet As Object
Dim internetdata As Object
Dim div_result As Object
Dim header_links As Object
Dim link As Object
Dim URL As String

Set internet = CreateObject("InternetExplorer.Application")
internet.Visible = True

URL = "https://www.google.co.in/search?q=how+to+program+in+vba"
internet.Navigate URL


Do Until internet.ReadyState >= 4
    DoEvents
Loop

Application.Wait Now + TimeSerial(0, 0, 5)

Set internetdata = internet.Document
Set div_result = internetdata.getelementbyid("res")


Set header_links = div_result.getelementsbytagname("h3")

For Each h In header_links
    Set link = h.ChildNodes.Item(0)
    Cells(Range("A" & Rows.count).End(xlUp).row + 1, 1) = link.href
Next

MsgBox "done"

End Sub
谢谢你, 阿兰

2 个答案:

答案 0 :(得分:3)

我在VBA和 使用Set objIE = New InternetExplorerMedium代替Set objIE = CreateObject("InternetExplorer.Application")不能解决问题。我通过转到IE设置-> Internet选项->安全并取消选中“启用保护模式”选项Settings

解决了该问题

答案 1 :(得分:1)

尝试重新排列你的行:

Do Until internet.ReadyState >= 4
    DoEvents
Loop

Application.Wait Now + TimeSerial(0, 0, 5)

使用:

While internet.busy
    DoEvents
Wend

完整代码(已测试)

Option Explicit

Public Sub clicklick()

Dim internet As Object
Dim internetdata As Object
Dim div_result As Object
Dim header_links As Object
Dim link As Object
Dim h As Object
Dim URL As String

Set internet = CreateObject("InternetExplorer.Application")
internet.Visible = True

URL = "https://www.google.co.in/search?q=how+to+program+in+vba"
internet.Navigate URL

internet.Visible = True

While internet.busy
    DoEvents
Wend

Set internetdata = internet.Document
Set div_result = internetdata.getelementbyid("res")

Set header_links = div_result.getelementsbytagname("h3")

For Each h In header_links
    Set link = h.ChildNodes.Item(0)
    Cells(Range("A" & Rows.Count).End(xlUp).Row + 1, 1) = link.href
Next

MsgBox "done"

End Sub