简体   繁体   中英

VBA Excel - Open IE window to URL, pause, then close

I am limited to using VBA to accomplish this. The goal is to programmatically Open a new IE window which is a duplicate of a window already open. I need to display this window for limited amount of time (in this example I am waiting 15 seconds), then I want to close one of the two IE windows I have open. I have cobbled together code fragments from a few examples I have found and this is partially working, but the results are not as I would expect.

  • First I am able to find the IE instances but even though I think I have coded an exit, both windows are closed.
  • The MsgBox I am using for debugging never appears.
  • With each run of the code the error message below appears

在此处输入图片说明

Below is the code I am trying to get to work, but failing with.

Private Sub OpenReport()
Dim IE
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate "http://~~~~~~~~~.net/reports/views/result/reportResult.faces"
' Wait for a period of time contained in TimeValue
Application.Wait (Now + TimeValue("00:00:15"))
' Now close ONE of the IE windows (Currently closing all of them)
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Process")
' Find IE Instances
For Each objItem In colItems
    If objItem.Name = "iexplore.exe" Then
        On Error Resume Next
        objItem.Terminate ' Terminates all instead of exiting after finding one IE window
        MsgBox objItem.Name & " " & objItem.ProcessID & " " & objItem.CommandLine 'Doesn't appear
        Exit For
    End If
Next
End Sub

I appreciate the input but had to go a slightly different route to get this working as it should...

The key to getting one instance of IE to close was solved by using TaskKill (commandline WScript).

Below is the full solution

Private Sub OpenReport()
Dim IE
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate "http://~~~~~~~~~~~net/reports/views/result/reportResult.faces"
' Wait for a period of time contained in TimeValue
Application.Wait (Now + TimeValue("00:00:15"))
' Now close ONE of the IE windows (Currently closing all of them)
Set objWMIService = GetObject("winmgmts:\\.\root\cimv2")
Set colItems = objWMIService.ExecQuery("Select * From Win32_Process")
' Find an IE instance
For Each objitem In colItems
    If objitem.Name = "iexplore.exe" Then
        On Error Resume Next

        Shell ("TaskKill /PID " & objitem.ProcessID)

    Exit For
    End If
Next
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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