Excel VBA IE自动化-粘贴链接到电子表格



我有VBA代码连接到IE, bbc.co.uk和搜索任何文本是在单元格A1。

我希望将搜索的第一个结果粘贴到电子表格的单元格A2中。

我要复制/粘贴的元素是'summary short'。

我的代码如下-它都工作,除了最后:

Sub FillInBBCSearchForm()
Dim ieApp As New SHDocVw.InternetExplorer
Dim words As Range
Set words = Range("A1")
ieApp.Visible = True
'go to the website of interest
ieApp.Navigate "http://www.bbc.co.uk/"
Do While ieApp.Busy
DoEvents
Loop
'wait for page to finish loading
Do While ieApp.Busy And Not ieApp.ReadyState = READYSTATE_COMPLETE
DoEvents
Loop
'****fill in the search form
ieApp.Document.getElementById("orb-search-q").Value = words
Application.ScreenUpdating = True
'wait for page to finish loading
Do While ieApp.Busy And Not ieApp.ReadyState = READYSTATE_COMPLETE
DoEvents
Loop
'****click the search button
ieApp.Document.all("orb-search-button").Click
'wait for page to finish loading
Do While ieApp.Busy And Not ieApp.ReadyState = READYSTATE_COMPLETE
DoEvents
Loop

'Select the first article heading and paste it to cell A2
For Each elm In ie.Document.getElementsByClassName("summary short")
If InStr(elm.innerText, "@") Then
    Range("A2").Value = innerText
End If
Next elm
'Set out1 = ieApp.Document.getElementsByClassName("summary short")(0).innertext
End Sub

我注意到了一些事情。

首先,您已经将ieApp声明为InternetExplorer对象,但您试图使用ie代替。此外,在Range("A2").Value = innerText行中,您没有说明实际需要哪个对象的innetText。这一行应该改为Range("A2").Value = elm.innerText

:

For Each elm In ie.Document.getElementsByClassName("summary short")
If InStr(elm.innerText, "@") Then
    Range("A2").Value = innerText
End If
Next elm

应该是这样的:

For Each elm In ieApp.Document.getElementsByClassName("summary short")
If InStr(elm.innerText, "@") Then
    Range("A2").Value = elm.innerText
End If
Next elm

为了避免这样的错误,我将Option Explicit添加到任何子程序之外的模块中。这将强制显式地声明变量,并且除了是良好的实践之外,还将在代码执行之前捕获这些错误,并且可以节省几个小时的调试时间,从而发现您输入了错误的变量名称。这也可以帮助你弄清楚,当你回到一段时间没有访问过的旧代码时,你想要做什么。

如果你添加了Option Explicit,它将强制你声明elm。您可以在代码开头添加Dim elm As Object来解决这个问题(因为getElementsByClassName方法返回一个对象集合)。

最新更新