2013-08-16 58 views
1

当前的代码如下:VBA:试图访问的网站,但网站偶尔会无法加载

Set IE = CreateObject("InternetExplorer.Application") 
IE.Navigate "https://www.website.com/" 
Application.StatusBar = "https://www.website.com/ is loading. Please wait..." 
Do While IE.Busy 
    Application.Wait DateAdd("s", 1, Now) 
    Loop 
Application.StatusBar = "Search form submission. Please wait..." 

我遇到的问题是,“https://www.website.com/”无法从时间加载时间(我相信这是由于我反复访问它)。其结果是,该代码永远不会超越了这个循环:

Do While IE.Busy 
    Application.Wait DateAdd("s", 1, Now) 
    Loop 

一个合乎逻辑的解决方案,在我看来,是杀IE和一定的时间限制后重新启动整个过程(30秒?)已经达到。请告知如何编码此解决方案,和/或如何编写更有效的解决方案。非常感谢你!而且我使用IE10,如果这很重要的话。

而且,这里是一个链接,我发现了有些相关的相关信息: http://www.ozgrid.com/forum/showthread.php?t=161094

+0

您在宏完成执行代码后是否将'IE'设置为空? – Jaycal

+0

是的,先生!代码最后清理很多。 – autzen7

回答

5

你可以尝试修改代码来读取

Sub LoadWebsite() 
Dim iSecondCounter As Integer 
Static iAttempts As Integer 

iAttempts = iAttempts + 1 

Set ie = CreateObject("InternetExplorer.Application") 
ie.Navigate "https://www.website.com/" 
Application.StatusBar = "https://www.website.com/ is loading. Please wait..." 

iSecondCounter = 0 
Do While ie.Busy And iSecondCounter < 30 
    Application.Wait DateAdd("s", 1, Now) 
    iSecondCounter = iSecondCounter + 1 
Loop 
If iSecondCounter = 30 Then 
    ie.Quit 
    If iAttempts <= 3 Then Call LoadWebsite 
End If 

Set ie = Nothing 
End Sub 
+1

谢谢你。然后,如果IE被杀死了,我怎么会有条件地循环回去呢? – autzen7

+0

嗨我已编辑的代码,使其成为一个递归子程序,如果IE失败并被杀死,然后subriutine将再次运行,但如果3次后,它仍然没有加载它会放弃(保存你从一个无限循环) 。 –

+0

因此,代码现在代表: '调用LoadWebsite Set objCollection = IE.document.getElementsByTagName(“input”)' 并导致此错误:Object variable或With block variable not set。 – autzen7

0

OK,你似乎可以提出一个新的有关获取HTML元素集合的问题,所以我会将其作为新答案发布。您收到对象错误的原因似乎是因为您没有将objCollection标注为正确的对象。我已经修改了原始答案中的代码,并将其设置为您的代码片段。要使用此代码,我必须包含对Microsoft HTML对象库的引用。

请注意,这段代码在退出子文件之前破坏了元素集合,你可能想要对它做些什么。

Sub LoadWebsite() 
Dim iSecondCounter As Integer 
Static iAttempts As Integer 
Dim objCollection As IHTMLElementCollection 
iAttempts = iAttempts + 1 

Set ie = CreateObject("InternetExplorer.Application") 
ie.Navigate "https://www.website.com/" 
Application.StatusBar = "https://www.website.com/ is loading. Please wait..." 

iSecondCounter = 0 
Do While ie.Busy And iSecondCounter < 30 
    Application.Wait DateAdd("s", 1, Now) 
    iSecondCounter = iSecondCounter + 1 
Loop 
If iSecondCounter = 30 Then 
    ie.Quit 
    If iAttempts <= 3 Then Call LoadWebsite 
End If 


Set objCollection = (ie.Document.getElementsByTagName("INPUT")) 

Cleanup: 

Set ie = Nothing 
Set objCollection = Nothing 

End Sub 
0

也许你可以添加代码,以帮助你等待它加载和X秒后,你可以决定是否要等待,或者你可以优雅地退出/做别的事情(发布消息等)

ie.Navigate "http://www.website.com" 
Application.Wait Now + TimeSerial(0, 0, 3) 

Do While ie.Busy 
    DoEvents 
Loop