VBA:尝试访问网站,但网站偶尔无法加载

时间:2013-08-16 00:38:35

标签: excel vba excel-vba navigateurl

目前的代码如下:

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

3 个答案:

答案 0 :(得分: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 :(得分:0)

好的,你似乎在问一个关于获取HTML元素集合的新问题,所以我将把它作为一个新答案发布。您收到对象错误的原因似乎是因为您没有将objCollection标注为正确的对象。我已经修改了原始答案中的代码来执行此操作并将集合设置为您的代码段。要使用此代码,我必须包含对Microsoft HTML Object Library的引用。

请注意,此代码会在退出子代码之前销毁元素集合,您可能希望使用它来执行某些操作。

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

答案 2 :(得分:0)

也许您可以添加代码来帮助您等待它加载,在X秒之后您可以决定是否等待,或者您可以优雅地退出/执行其他操作(发布消息等)

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

Do While ie.Busy
    DoEvents
Loop