且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

VBA Internet Explorer 自动化“权限被拒绝"

更新时间:2021-07-04 10:26:07

在测试了以上所有建议的修复甚至更多之后,我确信这是一个奇怪的错误,当有不同的安全区域时,IE 会调用子进程的事件处理一个网站.

After testing all above suggested fixes and even more, I am positive this is a weird bug with Eventhandling of child Processes invoked by IE whenever there are different security zones on one website.

切入正题,这是解决方案:

Cut to the chase, here is the solution:

'Craziest workaround ever due to bugged IE Eventhandling
Do While IE.ReadyState = 4: DoEvents: Loop 
Do Until IE.ReadyState = 4: DoEvents: Loop

每次导航到新页面或其他可能导致网站重新加载的事件(例如点击提交按钮或类似按钮)后,添加此代码段.

上面的 Dan 建议在你的代码中随意添加 DoEvents 语句,这对我来说并没有 100% 成功.相反,我建议在适用的地方添加上述代码.

Dan above suggested to add DoEvents statements liberally in your code, which did not 100% do the trick for me. Instead, I suggest to add above code whereever applicable.

感谢 Dan,如果没有您的评论,我永远不会知道!

Kudos to Dan, without your comment I would've never figured it out!

此方法相对于其他建议修复的优点的简短摘要:

  • 如果你愿意,你可以坚持后期绑定(将 IE 作为对象)
  • 您可以坚持创建 InternetExplorer 对象(而不是 InternetExplorerMedium)
  • 您无需更改 IE 中的安全区域设置
  • 在您的应用程序中没有不必要的等待时间
  • 您摆脱了错误 70 - 权限被拒绝
  • 您摆脱了丢失的会话,即运行时错误‘-2147417848 (80010108)’:自动化错误调用的对象已与其客户端断开连接."
  • 您摆脱了接口问题,即运行时错误‘-2147023179 (800706b5)’:自动化错误接口未知"

使用此方法您不需要的所有内容的摘要:

Summary of all the things YOU DO NOT NEED with this approach:

  • InternetExplorerMedium 对象
  • 一般早期绑定
  • 参考 Microsoft Internet Controls
  • 参考 Microsoft Shell 控件和自动化
  • 奇怪的错误处理
  • 无需检查代码中的 IE.Busy
  • Application.wait 或 sleep 导致不必要的猜测延迟

我只包含上面的总结,因为我已经看到了所有建议的解决方法,并且到目前为止我已经亲自尝试过但没有运气.

基于 OP 问题的示例代码:

Dim IE as Object    
Set IE = CreateObject("InternetExplorer.Application")

IE.Visible = True
IE.Navigate("http://www.google.com")

'Craziest workaround ever due to bugged IE Eventhandling
Do While IE.ReadyState = 4: DoEvents: Loop
Do Until IE.ReadyState = 4: DoEvents: Loop

IE.document.getElementsByTagName("Input")(3).Value = "Search Term"
IE.document.Forms(0).Submit     ' this previously crashed

我真的希望这会在未来对其他人有所帮助.向所有帮助拼凑解决方案的人致敬.

I really hope this will help others in the future. Godspeed to everyone who helped with piecing the solution together.

***的问候帕特里克