taking control of an open browser instance - vba

Set Browser = New SHDocVw.InternetExplorer
Once you create a new browser instance, how do you refer to that instance, instead of closing and reopening, say If I activate Excel window, then I want to activate back to the browser, how is this done?
I looked into
AppActivate "Windows Internet Explorer"
But If I have more than one window open, that wont work right, I dont think

I think you mean:
Option Explicit
Public browser As SHDocVw.InternetExplorer
Sub NavigateTo()
Set browser = New SHDocVw.InternetExplorer
browser.Visible = True
browser.Navigate "http://stackoverflow.com"
End Sub
In other words, declare the browser variable at module level so it remains available.
You can also capture an instance like so:
Sub getIE()
Dim sh As Object, oWin As Object, IE As Object
Set sh = CreateObject("Shell.Application")
For Each oWin In sh.Windows
If TypeName(oWin.Document) = "HTMLDocument" Then
Set IE = oWin
Exit For
End If
Next
Debug.Print IE.Document.url
End Sub

Related

VBA to Activate Internet Explorer Window

I'm making a macro that opens Internet Explorer, navigates and logs into a website. Everything works fine, but I need to bring the IE Window up front, and activate it, so I can use SendKeyson it.
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
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.
I always just make IE an untyped object, like so
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.
Someone write similar things here:
Get existing IE via VBA
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
*PtrSafe / LongPtr is to be used in 64-bit system
*You may delete it if you are using 32-bit
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 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

Handle HTMLElement events in VBA

I use SHDocVw.InternetExplorer to show in powerpoint a local html file to the user. The file contains a form with a submit button and I would like to run my vba function when the button is clicked. I did the following to handle the onQuit-event of the InternetExplorer.
Class module "CIE"
Public WithEvents ie As SHDocVw.InternetExplorer
Private Sub ie_onQuit()
Debug.Print "onQuit was fired"
End Sub
Module code
Option Explicit
Public curCIE As CIE
Sub open_ie()
Dim CIEobj As CIE
Set CIEobj = New CIE
Dim ie As SHDocVw.InternetExplorer
Set ie = New SHDocVw.InternetExplorer
ie.Visible = True
ie.Navigate "C:\search.html"
Do While ie.Busy Or ie.readyState <> 4
DoEvents
Loop
Set CIEobj.ie = ie
Set curCIE = CIEobj
End Sub
I actually want to handle the onclick event of
curCIE.ie.Document.getElementsByTagName("button").Item(0)
but I do not know how to proceed.
You could add reference to MSHTML, then make your class module this way:
Public WithEvents ie As SHDocVw.InternetExplorer
Private WithEvents button As MSHTML.HTMLButtonElement
Public Sub LoadButton()
Set button = ie.document.getElementsByTagName("button").Item(0)
End Sub
Private Function button_onclick() As Boolean
'do what you want here
End Function
Private Sub ie_onQuit()
Debug.Print "onQuit was fired"
End Sub
And then, in the other module, add this statement after setting CIEobj.ie property:
CIEobj.LoadButton

Find value stored in IE object in VBA

I have declared an object named IE in my VBA code.
Set IE = CreateObject("InternetExplorer.Application")
Sometimes user may close the browser linked to IE object. How can i write code to find if the browser is closed or open?
As shown in below image, software shows Internet Explorer when i place cursor on IE object during run time. Can this value be used to determine if browser is closed or open? If not, any other way?
Create a custom class to capture the Internet Explorer events using WithEvents. You'll need to set a reference to Microsoft Internet Controls.
Option Explicit
Private WithEvents IE As InternetExplorer
Private Sub IE_OnQuit()
End Sub
Private Sub IE_OnVisible(ByVal Visible As Boolean)
End Sub
Private Sub Class_Initialize()
Set IE = New InternetExplorer
End Sub
If the object is closed, then accessing some of it's members should give you an error.
Dim isOpen As Boolean ' False by default
On Error Resume Next
If IE.HWND > 0 Then isOpen = True
On Error Goto 0

Do Action if user returns to Excel from another Application

I have an Excel workbook that has links to a webpage. The user can click on the links, which minimize the Excel window and open their browser. When they are done with the site, they minimize or close their browser, which returns them to Excel (as it was their previous active window).
I would like VBA to take an action (update a table) when the user is returned to Excel.
I've looked at the Workbook_WindowActivate event, but this only works if you are moving from one Excel Workbook to another within the Excel Application.
Maybe I could use Application.name or the Windows function GetActiveWindow somehow but I am not sure how best to do this.
Any ideas? Thanks!
You want to add an event handler for Workbook_SheetFollowHyperlink. You can then use the code below. This just checks to see if the webpage has focus. the ' DO EVENTS ' is where you would add your code and then exit the sub
'********************* References used
'* Microsoft Shell Controls An Automation : shell32.dll*
'* Microsoft HTML Objects Library: MSHTML.dll expand ยป *
'* Microsoft Internet Controls: IEFRAME.dll *
Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
Dim ie As InternetExplorer 'IE window variable
Dim sUrl 'url of the webpage
Dim dt As Date 'timer
'set the url to look for
sUrl = Target.Address
'set initial timeout period *used instead of browser ready due to page redirection.
'you should also check the browser ready status
dt = DateAdd("s", 5, DateTime.Now)
Do While dt > DateTime.Now
DoEvents
Loop
'reset the timeout period to allow time to view and select
dt = DateAdd("s", 30, DateTime.Now)
Dim shShell As New Shell ' windows shell variable
'continue loop until we hit the timeout or the webpage no longer has focus
Do While dt > DateTime.Now
'Loop through all the IE windows
For Each ie In shShell.Windows
'check to see if the URL's match
If InStr(ie.LocationURL, sUrl) Then
Dim hDoc As HTMLDocument
'get the webpage document
Set hDoc = ie.document
'check to see if it has focus
If Not hDoc.hasFocus Then
ThisWorkbook.Activate
'''''''''''''
' DO EVENTS '
'''''''''''''
Exit Sub
End If
Set hDoc = Nothing
End If
Next ie
Loop
End Sub
Here's what I've ended up doing. I borrowed quite a bit from this post: How to make a macro which executes periodically in Excel?
When the user clicks on a hyperlink, the code starts periodically checking whether Excel is their active window. I've found that the GetActiveWindow function returns zero if the user is not in the Excel application and some positive number if they are. If the code finds that the user returned to Excel from a different window (the previous check found that they were in a different window and the current one finds they are in Excel) then my table gets updated and the timer stops checking for the active window.
Doing it this way has the advantage of working for any web browser.
Option Explicit
Dim ExcelIsActive As Boolean
Private Declare Function GetActiveWindow Lib "user32" () As Long
Dim m_dtNextTime As Date
Dim m_dtInterval As Date
Dim DisableFlag As Boolean
Private Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
Call start
End Sub
Public Sub Enable(Interval As Date)
Call Disable
m_dtInterval = Interval
Call starttimer
End Sub
Private Sub starttimer()
m_dtNextTime = Now + m_dtInterval
Application.OnTime m_dtNextTime, "TestActive"
End Sub
Public Sub TestActive()
If GetActiveWindow > 0 Then
If ExcelIsActive = False Then
ExcelIsActive = True
Call RefreshQuery
End If
Else
ExcelIsActive = False
End If
If Not DisableFlag Then
Call starttimer
Else
Call Disable
End If
End Sub
Public Sub Disable()
Dim dtZero As Date
If m_dtNextTime <> dtZero Then
' Stop timer if it is running
On Error Resume Next
Application.OnTime m_dtNextTime, "TestActive", , False
On Error GoTo 0
m_dtNextTime = dtZero
End If
m_dtInterval = dtZero
End Sub
Sub start()
'Start the timer
DisableFlag = False
ExcelIsActive = True
'Sets the interval to be three seconds
Call Enable(#12:00:03 AM#)
End Sub
Public Sub RefreshQuery()
'I do my stuff here
'Stop the timer until the next time the user launches the browser
DisableFlag = True
End Sub

VBA IE automation, To trigger some action in VBA before whenever i navigate to other page in website

I need a VBA code which can do some action in VBA when the webpage frame is just about to navigate to other page.for example when i click on some link,button it navigates to other page i want to take screen shot of the page before frame navigates to other.i have done something like this but it is taking screen shot of the blank page and its only working for onetime as the page is navigated and object gets changed. please help me with this i have been searching for this since 2 weeks help me.
Sub pageLoad()
Set ie2 = GetIE("https://xyz.com")
Dim LinkFound As Boolean
Dim linkCollection
Dim IEfr0 As Object
i = 0
Dim Link As MSHTML.HTMLAnchorElement
'HTMLInputElement
Set wordapp = CreateObject("word.Application")
wordapp.Visible = True
Set wrdDoc = wordapp.Documents.Add
Set IEfr0 = ie2.document.frames(0).document
Set linkCollection = IEfr0.getElementsByTagName("a")
Do While ie2.Visible = True
For Each Link In linkCollection
If ie2.document.frames(2).document.readyState = "interactive" Then
sai1
End If
If IEfr0.readyState = 1 Then
sai1
End If
Next
Loop
End Sub
Sub sai1()
Application.SendKeys "{PRTSC}"
wordapp.Selection.Paste
Do While ie2.Busy
Loop
End Sub
Here's a possible solution. Only showing you how to create the object and specify the BeforeNavigate2 event. This requires you to reference Microsoft Internet Controls and create the IE object (this will not work with late binding). This code must be in an object module (worksheet or workbook) because you cannot use WithEvents in a standard module.
Option Explicit
Dim WithEvents ie As InternetExplorer
Sub Example()
Set ie = New InternetExplorer
ie.Visible = True
ie.Navigate "Your URL Here..."
Do Until ie.ReadyState = READYSTATE_COMPLETE: DoEvents: Loop
End Sub
Private Sub ie_BeforeNavigate2(ByVal pDisp As Object, URL As Variant, Flags As Variant, TargetFrameName As Variant, PostData As Variant, Headers As Variant, Cancel As Boolean)
'Place code to run before navigating here.
End Sub
An issue you may see with this is that for some websites, the BeforeNavigate2 event will actually fire multiple times due to additional calls for resources when loading.