繁体   English   中英

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

[英]Excel VBA IE automation - paste link to spreadsheet

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

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

我要复制/粘贴的要素是“摘要短”。

我的代码在下面-一切都从一开始就分开了:

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您实际上想要哪个对象的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方法返回一个对象集合)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM