1

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
Community
  • 1
  • 1

1 Answers1

1

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.

Daniel
  • 12,982
  • 3
  • 36
  • 60
  • thank you very much awesome solution, i used loops and states and made it complex thanks, but is there any function like this which do not fire multiple times for additional resources..how can i achieve that? – nothingisimpossible Oct 29 '12 at 10:16
  • I got an error stating, "The object has disconnected from its clients." This was resolved by switching `New InternetExplorer` to `New InternetExplorerMedium` as described here: https://stackoverflow.com/questions/42403210 – lehiester Feb 21 '18 at 14:41