Bring Internet Explorer Download Window to Focus - Foreground via VBA - vba

I've got a macro which currently works but I'm trying to automate the final "quirk" that I have had to live with up till now. Basically it opens IE to a URL which then closes the window and spits back a download window and I have excel use SENDKEYS to download file.
I'm struggling to bring the download window to focus, currently my end users click on the DL window for sendkeys to work as expected.
I have read through the following and tried utilizing the code to no avail:
vbscript - Bring Internet Explorer Application window to front
VBA to Activate Internet Explorer Window
Bringing Internet Explorer window to foreground
Set Focus to Internet Explorer Object in Visual Basic
There a few things to note:
I can't download the file via batch as I need IE to pass along the credentials.
The file is not static, the URL runs a script on the backend and then presents the file back to end terminal
I can't have any requirement to "Enable Reference Library" on end users computers
The macro is as follows:
Public Sub DLFILE()
'This will load a webpage in IE
Dim i As Long
Dim URL As String
Dim ie As Object
Dim objElement As Object
Dim objCollection As Object
'Create InternetExplorer Object
Set ie = CreateObject("InternetExplorer.Application")
'Define URL
URL = "http://example.com/"
'Navigate to URL
ie.navigate URL
' Statusbar let's user know website is loading
Application.StatusBar = URL & " is loading. Please wait..."
'IE ReadyState = 4 signifies the webpage has loaded (the first loop is set to avoid inadvertently skipping over the second loop)
Do While ie.ReadyState = 4: DoEvents: Loop 'Do While
Application.Wait (Now() + TimeValue("00:00:04"))
SendKeys "{RIGHT}{RIGHT}{ENTER}{TAB}{TAB}{TAB}{TAB}{ENTER}"
'Do Until IE.ReadyState = 4: DoEvents: Loop 'Do Until
'Unload IE
Set ie = Nothing
Set objElement = Nothing
Set objCollection = Nothing
End Sub
Also note, this doesn't bring up the prompt in the bottom of the IE window, but closes that window and brings up the "Full Downloads Window" like below.

As the shortcut for the "View Downloads" window is Ctrl+J in IE so I think we can use sendkeys to click Ctrl+J to bring the window to the front.
Sample code:
Sub LOADIE()
Set ieA = CreateObject("InternetExplorer.Application")
ieA.Visible = True
ieA.navigate "https://www.bing.com/"
Do Until ieA.readyState = 4
DoEvents
Loop
Application.Wait (Now + TimeValue("00:00:03"))
Application.SendKeys "^{j}"
End Sub
Result:

What I ended up doing was using an ObjURL to open the IE instance and then a DLUrl which I opened after. This made a few important adjustments, it's similar to opening a second tab in IE which would close, but instead of using the "Downloads Window" it would use the prompt at the bottom of the IE Window. This allowed me to continue to control the IEObj as the original ObjURL was still open. I couldn't get excel VBA to consistently control the "Downloads Window", but I was able to get consistent results using the following snippets. Between the two adjustments I now have consistent results.
Public Declare Function SetForegroundWindow Lib "user32" (ByVal HWND As Long) As Long
And
'Bring IEObj to Focus
HWNDSrc = IEObj.HWND
SetForegroundWindow HWNDSrc
Full Sub:
Public Declare Function SetForegroundWindow Lib "user32" (ByVal HWND As Long) As Long
Public Sub DL_File_IE()
Dim DLUrl As String, ObjURL As String
Dim IEObj As Object, objElement As Object, objCollection As Object
Set IEObj = CreateObject("InternetExplorer.Application")
IEObj.Visible = True
ObjURL = "http://google.com"
DLUrl = "http://example.com/file
IEObj.navigate ObjURL
Do Until IEObj.readyState = 4
DoEvents
Loop
IEObj.navigate DLUrl
'Bring IEObj to Focus
HWNDSrc = IEObj.HWND
SetForegroundWindow HWNDSrc
Application.Wait (Now() + TimeValue("00:00:02"))
SendKeys "{TAB}{TAB}{ENTER}", True ' Select "Save" in DL Window
Application.Wait (Now() + TimeValue("00:00:02"))
SendKeys "%{f4}", True ' Alt + F4 = Close IEObj
'Unload IE
Set IEObj = Nothing
Set objElement = Nothing
Set objCollection = Nothing
End Sub

Related

Web scraping debug print LocationURL returns unexpected value

This code is supposed to print webpage URL into the immediate window.
Sub BrowseToSite()
Dim IEObject As InternetExplorer
'Creating new instance of the internet explorer application
Set IEObject = New InternetExplorer
'make IE app visible
IEObject.Visible = True
'navigate to URL
IEObject.Navigate URL:="https://www.youtube.com"
Do While IEObject.Busy = True Or IEObject.ReadyState <> READYSTATE_COMPLETE
Application.Wait Now + TimeValue("00:00:01")
Loop
'Print the URL that we are currently at
Debug.Print IEObject.LocationURL
End Sub
I expect https://www.youtube.com but I get res://ieframe.dll/navcancl.htm.
I have references set to Microsoft HTML Object Library and Microsoft internet controls.

Run my VBA code from a existing (opened) internet explorer page

I would like to run my VBA macro on a specific internet explorer page that I have already opened and logged into .
This is because I have to login to my account and bypass the captcha code first.
I have to send this extremely repetitive message to over a couple hundred people over the course of the year.
Problem with the following is that I am opening up a brand new page and I wont be able to bypass the captcha.
Dim IE As InternetExplorer
Set IE = CreateObject("InternetExplorer.Application")
IE.navigate ("website")
IE.Visible = True
End Sub
Solution
Sub TestGetIE()
Dim IE As Object
'GetIE runs the Functoin we have created below
Set IE = GetIE("website opened in IE here ")
WaitFor IE
end sub
Function GetIE(sLocation As String) As Object
Dim objShell As Object, objShellWindows As Object, o As Object
Dim sURL As String
Dim retVal As Object
Set retVal = Nothing
Set objShell = CreateObject("Shell.Application")
Set objShellWindows = objShell.Windows
For Each o In objShellWindows
'Loop through all the opened internet explorer pages
sURL = ""
'Loops through all the pages opened on internet explorer
'Then we will tell our macro to work on that page
sURL = o.LocationURL
If sURL Like sLocation & "*" Then
Set retVal = o
Exit For
End If
Next o
Set GetIE = retVal
End Function
From your description, I understand that you want user interaction to fill the captcha and then want to continue to automate the same page.
I suggest you for both steps try to use 2 different modules and use the same IE object in both modules.
You can create a global IE object which you can use in both modules.
Then for the login part execute the first module.
After that user will fill the captcha manually.
Then execute the second module to automate the rest of the page.
Sample code:
Public ie As Object
Sub login()
Set ie = CreateObject("internetexplorer.application")
ie.Visible = True
ie.navigate "Your_web_site_URL_here..."
Do While ie.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
ie.document.getElementById("uname").Value = "user1"
ie.document.getElementById("pswd").Value = "12345"
End Sub
Sub second_part()
ie.document.getElementById("email").Value = "user1#abc.com"
ie.document.getElementById("age").Value = "30"
End Sub
UserForm1 code:
Private Sub CommandButton1_Click()
Call Module1.login
End Sub
Private Sub CommandButton2_Click()
Call Module1.second_part
End Sub
Output:
Calling upon this function helped me solve it.
Function GetIE(sLocation As String) As Object
Dim objShell As Object, objShellWindows As Object, o As Object
Dim sURL As String
Dim retVal As Object
Set retVal = Nothing
Set objShell = CreateObject("Shell.Application")
Set objShellWindows = objShell.Windows
For Each o In objShellWindows
'Loop through all the opened internet explorer pages
sURL = ""
'Loops through all the pages opened on internet explorer
'Then we will tell our macro to work on that page
sURL = o.LocationURL
If sURL Like sLocation & "*" Then
Set retVal = o
Exit For
End If
Next o
Set GetIE = retVal
End Function
One thing you could do is DoEvents until a certain Element is present on the page. Run your code to navigate to the website, then Do Until Element after captcha is present DoEvents. The code will loop until you are on logged into the website. I like using VBA SeleniumBasic ChromeDriver on GetHub. It makes web scraping way easier, and you do not need to use Internet Explorer.

Office 2016 VBA fails to open Internet Explorer shell window but works in Office 2013

I inherited this VBA script from my predecessor. It works fine for me in Excel 2013 up until recently when I was told I may need to work from home. Come to find out, the Office 2016 environment of my newly accessed VPN desktop does not like this script. I keep getting "The remote server machine is unknown or unavailable" when it reaches .ReadyState <> READYSTATE_COMPLETE.
The navigation did not fail as I can see the window where it successfully navigated to the URL and I can interact with it correctly. The strange thing is if I change the URL to "www.google.com" I get a valid ready state result.
I also need to figure out how to late bind the Shell Windows so it will work with both the v15 and v16 libraries simultaneously.
The intent of this script is to automate a process that
1. Opens an internal database at DBurl via web interface
2. Manipulates and runs a java script located on the web page
3. Close the browser window without closing any other browser windows
This could be modified for someone else's use by looking for a page element, such as a search box or specific button on a page, and interacting with it.
Edit:
Additional testing has revealed that a pause at and skipping the Do While loop and resuming at IETab1 = SWs.Count results in this script working in Office 2016. The only issue, then, is without the loop, the page isn't yet ready for the next step when the script tries to run the interaction. A wait for 5 seconds in place of the loop band-aid's this issue. Finding why the .ReadyState won't read will fix this issue.
Declare PtrSafe Function apiShowWindow Lib "user32" Alias "ShowWindow" _
(ByVal hwnd As Long, ByVal nCmdShow As Long) As Long
Sub OpenWebDB()
Dim ieApp As Object
Dim SWs As ShellWindows
Dim IETab1 As Integer
Dim JScript As String
Dim CurrentWindow As Object
Dim DBurl As String
Dim tNow As Date, tOut As Date
DBurl = "My.Database.url"
Set SWs = New ShellWindows
tNow = Now
tOut = tNow + TimeValue("00:00:15")
If ieApp Is Nothing Then
Set ieApp = CreateObject("InternetExplorer.Application")
With ieApp
.Navigate DBurl
Do While tNow < tOut And .ReadyState <> READYSTATE_COMPLETE
DoEvents
tNow = Now
Loop
IETab1 = SWs.Count
End With
End If
If Not tNow < tOut Then GoTo DBFail
On Error GoTo DBFail
Set CurrentWindow = SWs.Item(IETab1 - 1).Document.parentWindow
JScript = "javascript: DoSomething"
Call CurrentWindow.execScript(JScript)
On Error GoTo 0
SWs.Item(IETab1 - 1).Quit
Set ieApp = Nothing
Set SWs = Nothing
Exit Sub
DBFail:
MsgBox (DBurl & vbCrLf & "took too long to connect or failed to load correctly." & vbCrLf & _
"Please notify the Database manager if this issue continues."), vbCritical, "DB Error"
SWs.Item(IETab1 - 1).Quit
Set ieApp = Nothing
Set SWs = Nothing
End Sub
Try to remove the tNow < tOut from the Do While condition. Or, using the While statement to wait page complete:
While IE.ReadyState <> 4
DoEvents
Wend
The intent of this script is to automate a process that
1. Opens an internal database at DBurl via web interface
2. Manipulates and runs a java script located on the web page
3. Close the browser window without closing any other browser windows
Besides, according to the intent of the script, I suggest you could refer the following code (it could loop through the tabs, and close specific tab according the title):
Sub TestClose()
Dim IE As Object, Data As Object
Dim ticket As String
Dim my_url As String, my_title As String
Set IE = CreateObject("InternetExplorer.Application")
With IE
.Visible = True
.Navigate "https://www.microsoft.com/en-sg/" '1st tab
.Navigate "https://www.bing.com", CLng(2048) '2nd
.Navigate "https://www.google.com", CLng(2048) '3rd
While IE.ReadyState <> 4
DoEvents
Wend
'wait some time to let page load
Application.Wait (Now + TimeValue("0:00:05"))
'get the opened windows
Set objShell = CreateObject("Shell.Application")
IE_count = objShell.Windows.Count
'loop through the window and find the tab
For x = 0 To (IE_count - 1)
On Error Resume Next
'get the location and title
my_url = objShell.Windows(x).Document.Location
my_title = objShell.Windows(x).Document.Title
'debug to check the value
Debug.Print x
Debug.Print my_title
'find the special tab based on the title.
If my_title Like "Bing" & "*" Then
Set IE = objShell.Windows(x)
IE.Quit 'call the Quit method to close the tab.
Exit For 'exit the for loop
Else
End If
Next
End With
Set IE = Nothing
End Sub

Controlling IE11 “Do you want to Open/Save” VBA

I have issues with a code I am writing on VBA. I am basically using vba to open a website, input information and then click a download button, which downloads a csv that I can then copy and put onto my excel file. I do manage to get everything done up to the clicking download button. When I do that a Dialogue window shows up for IE11 asking me whether I want to save or open the file. I have no idea how solve this issue and how to click open or save. I have tryed everything mentioned in a solution for the same problem in Controlling IE11 "Do you want to Open/Save" dialogue window buttons in VBA , but even though I use this solution, the code runs but just does not do anything.
I have tried using the UIAutomation but I have been unsuccessful . I used the solution provided in Controlling IE11 "Do you want to Open/Save" dialogue window buttons in VBA. I have also tried using Sendkeys but I am not entirely sure how to set the focus on Internet explorer so that the sendkeys do what they are supposed to.
Code is actually very simple
Sub GetHTMLDocument()
Dim ie As New SHDocVw.InternetExplorer
Dim HTMLDoc As HTMLDocument
Dim HTMLInput As MSHTML.IHTMLElement
Dim HTMLButtons As MSHTML.IHTMLElementCollection
Dim HTMLButton As MSHTML.IHTMLElement
ie.Visible = True
ie.Navigate "this is where i put the website"
Do While ie.ReadyState <> READYSTATE_COMPLETE
Loop
Set HTMLDoc = ie.Document
Set HTMLInput = HTMLDoc.getElementById("Search")
HTMLInput.Value = "Hello"
Set HTMLInput = HTMLDoc.getElementById("downloadCSV")
HTMLInput.Click
End Sub
Unfortunately I cannot give the website and I cannot use a public one, after that I get the message whether to open or save it on internet explorer
Possible duplicate of VBA interaction with internet explorer
Though this answer may be more clear for this specific question.
1) add this to top of your module - It creates a function that will allow you to give any window focus. I have no idea on the details.
Public Declare Function SetForegroundWindow Lib "user32" (ByVal HWND As Long) As Long
2) Modify this code to taste in order to use SendKeys
'give IE focus to prepare for SendKeys
' IE.HWND = the handle of the Windows Internet Explorer main window.
Dim HWNDSrc As Long
HWNDSrc = IE.HWND
SetForegroundWindow HWNDSrc
'Make sure IE is not busy
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop
'send Alt-S to save
Application.SendKeys "%{S}"
'Make sure IE is not busy
Do While IE.Busy
Application.Wait DateAdd("s", 1, Now)
Loop

Get an active IE window by partial URL

I currently am running some VBA to navigate an intranet site, perform some actions, etc. I have completed the actions I need to take, and now I have 2 IE windows open. One window, my original, I want to remain open. The second window, I want to close.
I have been having issues closing the second window. Using simple SendKeys "%{F4}" doesn't close the window at all, although it would if I did the steps manually rather than through VBA. Also, ieApp.Quit keeps closing the first IE window, which I want to remain open to use again. Which is strange because it isn't the active window at the time.
My question is...is there a way to find/select an open IE window based on a partial URL? I know the URL will start with http://ctdayppv02/PVEShowDocPopup.aspx? but everything after that will change each time.
I've seen plenty online about launching IE with a URL, or returning the URL of an already open IE instance, but I'm not trying to do either of those at this point. I just want to activate a specific open IE window, so then I can close that one only.
Here is part of my code, which isn't closing anything as of now, but also doesn't result in any errors. It's the very last part that doesn't work, everything else is good.:
'***** Click the Search button *****
ieApp.Document.all.Item("btnSubmitProjectSearch").Click: DoEvents: Sleep 1000
'***** Click the Print button *****
ieApp.Document.all.Item("printLink").Click: DoEvents: Sleep 1000
'***** Setting variables for Windows API. Will be used to find the proper windows box by name *****
Dim windowHWND As LongPtr
Dim buttonHWND As LongPtr
Dim hwnd As String
Dim hwindow2 As String
''***** Will click the Print button. MUST HAVE MICROSOFT PDF AS DEFAULT PRINTER *****
windowHWND = getWindowPointer("Print", "#32770")
If windowHWND > 0 Then
'***** Add a small delay to allow the window to finish rendering if needed *****
Sleep 250
buttonHWND = FindWindowEx(windowHWND, 0, "Button", "&Print")
If buttonHWND > 0 Then
SendMessage buttonHWND, BM_CLICK, 0, 0
Else
Debug.Print "didn't find button!"
End If
End If
'***** Locate the "Save Print Output As" window, enter the filepath/filename and press ENTER *****
hwnd = FindWindow(vbNullString, "Save Print Output As")
Do
DoEvents
hwindow2 = FindWindow(vbNullString, "Save Print Output As")
Loop Until hwindow2 > 0
SendKeys "C:\Users\NAME\Documents\" & Range("G2").Value
SendKeys "{ENTER}"
'***** Locate the Viewer Control box that appears after saving and press ENTER to advance *****
hwnd = FindWindow(vbNullString, "PaperVision Document Viewer Control")
Do
DoEvents
hwindow2 = FindWindow(vbNullString, "PaperVision Document Viewer Control")
Loop Until hwindow2 > 0
SendKeys "{Enter}"
'***** Locate the "PaperVision - View Document" IE window and close it *****
hwnd = FindWindow(vbNullString, "PaperVision - View Document - Internet Explorer")
Do
DoEvents
hwindow2 = FindWindow(vbNullString, "PaperVision - View Document - Internet Explorer")
Loop Until hwindow2 > 0
'ieApp.Quit
SendKeys "%{F4}"
Any advice on how to close just that one page? Thanks in advance!
As per the first suggestion by QHarr, try...
Option Explicit
Sub test()
Dim oShell As Object
Dim oShellWindows As Object
Dim oShellWindow As Object
Dim sPartialURL As String
sPartialURL = "http://ctdayppv02/PVEShowDocPopup.aspx?"
Set oShell = CreateObject("Shell.Application")
Set oShellWindows = oShell.Windows
For Each oShellWindow In oShellWindows
If oShellWindow.Name = "Internet Explorer" Then
If InStr(oShellWindow.Document.URL, sPartialURL) > 0 Then
Exit For
End If
End If
Next oShellWindow
If Not oShellWindow Is Nothing Then
'Do stuff
'
'
oShellWindow.Quit
Else
MsgBox "The specified Internet Explorer window was not found!", vbExclamation
End If
Set oShell = Nothing
Set oShellWindows = Nothing
Set oShellWindow = Nothing
End Sub
I like Domenic's response more, but I wanted to post another way I came across online for anybody who may be looking at this down the road and wants another method.
This way uses a function that is called in the primary sub. The "View Document" is the wording that appears in the IE window caption, NOT in the URL. This will close any IE that contains that specific phrase somewhere in the window caption. I only tested this a few times but it seems to work.
Sub CloseWindow()
Do Until Not CloseIeIf("View Document"): Loop
End Sub
Function CloseIeIf(Str As String) As Boolean
Dim ie As Object
For Each ie In CreateObject("Shell.Application").Windows
If InStr(ie.LocationName, Str) <> 0 Then
ie.Quit
CloseIeIf = True
End If
Next
End Function