excel VBA代码在join时起作用,但在运行时不起作用

当我运行它时,我有下面的行失败,但是当我在这行之前中断应用程序,它工作正常。

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

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

 Set IE = New InternetExplorer 

在这行之前放置一个断点使其工作,我拿起正确的字符位置。

在这行之后放置一个断点, I保持为0。

任何想法将非常感激。

您最好使用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.... 

那么有可能你的IE对象没有被完全加载,这意味着你的“I”variables将无法获得一个值。 您可以尝试预先添加validation:

 Do While IE.busy DoEvents Loop 

当我尝试粘贴某些东西并发现应用程序还没有准备好的时候,我遇到了类似VBA的问题。 帮助我的东西是创build一个函数来执行类似这样的任务:

在模块的开头声明一个常量,以毫秒为单位:

 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 

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

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