使用Internet Explorer导航时出现VBA错误
我试图从全国下载一个自营投资/职位/定价表。 代码似乎做我想做的,除了当我尝试select一个特定的帐户(点击)产生“对象所需”的错误,
我以为我有正确的代码告诉我的macros,直到IE准备继续,但显然我失去了一些东西。
在代码中,相关行被突出显示。 如果我在错误行上面input一个STOP,我可以等到我“看到”链接出现,然后“继续”的代码,并按预期运行。
因为这到我的财务帐户,我不能提供用户名和密码,以允许某人复制确切的问题,但这里是代码,错误信息和突出显示。 build议感激。
Option Explicit 'set Reference to Microsoft Internet Controls Sub DownLoadFunds() Dim IE As InternetExplorer Dim sHTML Const sURL As String = "https://www.nationwide.com/access/web/login.htm" Const sURL2 As String = "https://isc.nwservicecenter.com/iApp/isc/app/ia/balanceDetail.do?basho.menuNodeId=12245" Dim wsTemp As Worksheet Set wsTemp = Worksheets("Scratch") Set IE = New InternetExplorer With IE .Navigate sURL .Visible = True 'for debugging Do While .ReadyState <> READYSTATE_COMPLETE DoEvents Loop Do While .Busy = True DoEvents Loop 'Login: User Name and Password "remembered" by IE .Document.all("submitButton").Click Do While .ReadyState <> READYSTATE_COMPLETE DoEvents Loop Do While .Busy = True DoEvents Loop 'Select this account to show .Document.all("RothIRA_#########").Click '<--Error at this line Do While .ReadyState <> READYSTATE_COMPLETE DoEvents Loop Do While .Busy = True DoEvents Loop .Navigate sURL2 Do While .ReadyState <> READYSTATE_COMPLETE DoEvents Loop Do While .Busy = True DoEvents Loop Set sHTML = .Document.GetElementByID("fundByFundOnly") With wsTemp .Cells.Clear .Range("a2") = sHTML.innertext End With .Quit End With Set IE = Nothing End Sub
这是错误信息:
这显示了突出显示的行:
编辑:
在Tim Williams的build议下,我添加了一个循环来testing所需元素的存在。 这似乎工作:
... On Error Resume Next Do Err.Clear DoEvents Application.Wait (Time + TimeSerial(0, 0, 1)) .Document.getelementbyid("RothIRA_#########").Click Loop Until Err.Number = 0 On Error GoTo 0
….
页面正在使用脚本来dynamic加载一些内容或在 “等待”循环结束后生成一些布局。 该循环只等到所有链接的内容/资源都被加载完毕,不会等待加载页面上的脚本完成。
一种方法是循环你的代码等待所需的元素被渲染:
Const MAX_WAIT_SEC as Long = 5 'limit on how long to wait... Dim t t = Timer Do While .Document.all("RothIRA_#########") Is Nothing DoEvents 'or you can Sleep here If Timer - t > MAX_WAIT_SEC Then Exit Do Loop 'carry on...
IE.Document.all("#RothIRA_....")
返回Nothing
(更精细的语言中为null
),因此调用Click
方法会导致错误。
你的代码和这样做是一样的:
Dim rothElement As Whatever rothElement = IE.Document.all("#RothIRA_....") rothElement.Click
…当你应该这样做:
Dim rothElement As Whatever rothElement = IE.Document.all("#RothIRA_....") If rothElement <> Nothing Then rothElement.Click End If
我build议使用现代的document.GetElementById
方法,而不是废弃的(如果不是过时的) document.All
API。