2017-02-16 137 views
4

我有下面的行,当我运行它时失败,但是当我在此行之前中断应用程序时,它工作正常。excel VBA代码在加入时运行,但不在运行时运行

I = InStr(html_document.body.innerHTML, "EPG") 

我是一个很长的,已初始化,应该工作正常。 html_document是IE.document,通过

Set IE = New InternetExplorer 

把一个断点,这条线也可以正常工作之前进行初始化,我拿起正确的字符位置。

把一个断点,该行后,I仍然为0。

任何想法将非常感激。

+4

在获取html_document之前是否在等待页面加载?例如在使用'IE.Navigate'后,你需要做一些事情,比如'Do While IE.ReadyState <> 4:DoEvents:Loop' – Jordan

回答

0

嗯,有可能你的IE对象没有完全加载,这意味着你的“I”变量将无法获得一个值。 你可以尝试先添加一个验证:

Do While IE.busy 
    DoEvents 
Loop 

试图粘贴的东西,找出该应用程序还没有准备好这样做时,我也有过类似的问题与VBA。东西帮我正在创造一个函数来执行类似这样的任务:

在您的模块的开头声明一个常数milisseconds:

Const ms As Double = 0.000000011574 

然后尝试适应这为您的需求:

Function Try_Something() as Boolean 
    On Error GoTo errorHandler 
    Application.Wait Now + ms * 50 

     'Do something here, such as checking if the value is obtainable' 
     var = InStr(html_document.body.innerHTML, "EPG") 

    Try_Something = True 
    Exit Function 
errorHandler: 
    Try_Something = False 
End Function 

这个函数的作用是封装运行时错误,如果发生错误,并在连续尝试之间增加50 ms的延迟,通常足以使您的代码顺利运行。在此之后,你原来的代码看起来有点像:

Do until Try_Something = True 
    DoEvents 
Loop 
I = InStr(html_document.body.innerHTML, "EPG") 
2

你最好使用READYSTATE枚举检查该页面已实际加载。

'READYSTATE_UNINITIALIZED = 0 
'READYSTATE_LOADING = 1 
'READYSTATE_LOADED = 2 
'READYSTATE_INTERACTIVE = 3 
'READYSTATE_COMPLETE = 4 


Dim IE As New InternetExplorer 
'// your other code here 
IE.Navigate "http://www.google.co.uk" 

While IE.ReadyState <> READYSTATE_COMPLETE 
    DoEvents 
Wend 

'// Following code will only run once the document has completely loaded. 

Set html_document = IE.Document 
I = InStr(html_document.body.innerHTML, "EPG") 

'// rest of your code here....