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

StackOverflow https://stackoverflow.com/questions/13111253

  •  14-07-2021
  •  | 
  •  

Question

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
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top