【发布时间】:2021-10-27 13:37:34
【问题描述】:
我创建了以下代码,该代码适用于 Excel 2016,但不适用于 Excel 2010,在 Set doc = ie.document 上出现 run time error 13 type mismatch vba 错误。
但我无法弄清楚 Excel 2010 将如何解决。
还有一件事我想让它比现在更快地工作。我将不胜感激。
Sub Link()
Dim ie As New InternetExplorer
Dim doc As New HTMLDocument
Dim lastrow As Long
Dim ecoll As Object
Dim ecolla As Object
Dim link As Object
Dim t As Date
lastrow = Range("A" & Rows.Count).End(xlUp).Row
t = Now()
'MsgBox "Do you want to initialize this COOL Scraper?"
For i = 2 To lastrow
ie.Visible = True
ie.navigate "https://www.google.co.in/search?q=" & Cells(i, 1) & "&rnd=" & WorksheetFunction.RandBetween(1, 10000)
Do
DoEvents
Loop Until ie.readyState = READYSTATE_COMPLETE
Set doc = ie.document
Set ecoll = doc.getElementById("rso")
Set ecolla = ecoll.getElementsByTagName("H3")(0)
Set link = ecolla.parentNode
On Error Resume Next
str_text = Replace(link.innerText, link.href, "")
On Error Resume Next
str_text = Replace(str_text, " ", "")
Cells(i, 2) = link.href
DoEvents
Next
ie.Quit
Set ie = Nothing
Debug.Print "done" & "Time taken : " & Format(Now() - t, "hh:mm:ss")
MsgBox "Ellapsed Time - " & Format(Now() - t, "hh:mm:ss")
End Sub
【问题讨论】:
-
您是否在打开的 Internet Explorer 窗口中看到您尝试访问的 google 页面?而且,为了让代码更快,不要再用IE了……
-
是的,当谷歌页面打开时会弹出错误。好吧会尝试知道如何去其他浏览器。
-
请尝试将其声明为
Dim doc As Object。 -
我在 Excel 2010 上,无法重现您的问题。 Excel 2016 和 Excel 2010 是否在同一台机器上?如果不是,那么我怀疑您的 mshtml.dll 可能是 Excel 2010 机器中的问题。
-
@HafizSh 说实话 - 我不知道(这也可能是您的 IE 上的问题?)所以我发布了另一种方法,希望它适用于您的机器!
标签: excel vba web-scraping