简体   繁体   English

VBA 激活 Internet Explorer Window

[英]VBA to Activate Internet Explorer Window

I'm making a macro that opens Internet Explorer, navigates and logs into a website.我正在制作一个可以打开 Internet Explorer、导航和登录网站的宏。 Everything works fine, but I need to bring the IE Window up front, and activate it, so I can use SendKeys on it.一切正常,但我需要把 IE Window 放在前面,然后激活它,这样我就可以使用SendKeys了。 I've found websites and videos with different approaches on a command called AppActivate and i've tried many of them, but even if I copy the entire code (which works for the author) it won't work for me, I always get an error: Invalid Procedure Call or Argument - Error 5我在一个名为AppActivate的命令上找到了具有不同方法的网站和视频,我已经尝试了很多,但即使我复制了整个代码(对作者有用),它对我也不起作用,我总是得到错误:无效的过程调用或参数 - 错误 5

A list of everything I've found and tried:我找到并尝试过的所有内容的列表:

Dim objIE As InternetExplorerMedium
Set objIE = New InternetExplorerMedium
objIE.navigate "http://google.com"
'makes it visible, but not active
objIE.Visible = True

'A list of ways I've tried:
objIE.AppActivate "Google - Internet Explorer"
AppActivate "Google - internet Explorer"
'the above supposedly looks for the title of the page
AppActivate objIE
AppActivate (objIE)
AppActivate "objIE"

observations: I'm running this inside Excel 2013 and I'm using Windows 7 with IE 11.观察:我在 Excel 2013 中运行它,我正在使用 Windows 7 和 IE 11。

I always just make IE an untyped object, like so 我总是像这样将IE设为无类型对象

Sub test()
Dim IE As Object

Set IE = Nothing
Set IE = CreateObject("InternetExplorer.Application")
IE.Navigate "www.google.com"
IE.Visible = True

End Sub

The IE window has focus when this finishes running on my end. 完成此操作后,IE窗口将具有焦点。

Someone write similar things here:有人在这里写类似的东西:

Get existing IE via VBA 通过 VBA 获取现有 IE

With a little modification: (SetForegroundWindow Lib "user32" ) So that after it search for the Existing IE, it will appear on the top of our screen稍加修改: (SetForegroundWindow Lib "user32" ) 这样搜索Existing IE后,它就会出现在我们的屏幕顶部

*PtrSafe / LongPtr is to be used in 64-bit system *You may delete it if you are using 32-bit *PtrSafe / LongPtr 用于 64 位系统 *如果您使用 32 位系统,您可以删除它


Call Library调用库

Public Declare PtrSafe Function SetForegroundWindow Lib "user32" (ByVal HWND As LongPtr) As LongPtr

Main Sub主副

Sub Test1()

    Dim IE1 As Object
    Set IE1 = ThisIE
    
    IE1.navigate "http://stackoverflow.com"
    
    Do While IE1.readyState <> READYSTATE_COMPLETE
    Loop
    
    SetForegroundWindow (IE1.HWND)
End Sub

Function to be called Function 被调用

Function ThisIE() As Object

    For Each ThisIE In CreateObject("Shell.Application").Windows()
        If (Not ThisIE Is Nothing) And ThisIE.Name = "Internet Explorer" Then Exit For
    Next ThisIE
    
    If ThisIE Is Nothing Then Set ThisIE = CreateObject("InternetExplorer.Application")
        ThisIE.Visible = True
        
End Function

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM