VBA IE自动化,在我导航到网站中的其他页面之前触发VBA中的某些操作

VBA IE自动化,在我导航到网站中的其他页面之前触发VBA中的某些操作,vba,excel,webautomation,Vba,Excel,Webautomation,我需要一个VBA代码,当网页框架即将导航到其他页面时,该代码可以在VBA中执行某些操作。例如,当我单击某个链接时,按钮,它导航到其他页面,我想在页面导航到另一个页面之前进行屏幕截图。我已经做了类似的事情,但是它正在进行空白页面的屏幕截图,它只在页面导航和对象改变的时候工作一次。请帮我这个我已经搜索了两个星期了帮我 Sub pageLoad() Set ie2 = GetIE("https://xyz.com") Dim LinkFound As Boolean Dim linkCollectio

我需要一个VBA代码,当网页框架即将导航到其他页面时,该代码可以在VBA中执行某些操作。例如,当我单击某个链接时,按钮,它导航到其他页面,我想在页面导航到另一个页面之前进行屏幕截图。我已经做了类似的事情,但是它正在进行空白页面的屏幕截图,它只在页面导航和对象改变的时候工作一次。请帮我这个我已经搜索了两个星期了帮我

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

这里有一个可能的解决方案。仅显示如何创建对象和指定事件。这要求您引用Microsoft Internet控件并创建IE对象(这不适用于后期绑定)。此代码必须位于对象模块(工作表或工作簿)中,因为不能在标准模块中使用WithEvents

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 

您可能会看到这样一个问题:对于某些网站,BeforeNavigate2事件实际上会触发多次,因为加载时会额外调用资源。

这里有一个可能的解决方案。仅显示如何创建对象和指定事件。这要求您引用Microsoft Internet控件并创建IE对象(这不适用于后期绑定)。此代码必须位于对象模块(工作表或工作簿)中,因为不能在标准模块中使用WithEvents

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 

您可能会看到,对于某些网站,BeforeNavigate2事件实际上会多次触发,因为加载时会额外调用资源。

非常感谢您非常棒的解决方案,我使用了循环和状态,并使其变得复杂,谢谢,但是有没有像这样的函数不会为了额外的资源而多次启动..我怎么能做到呢?我得到一个错误声明,“对象已经从它的客户端断开了连接。”通过将
新InternetExplorer
切换到
新InternetExplorerMedium
解决了这个问题,如下所述:非常感谢非常棒的解决方案,我使用了循环和状态,并使其变得复杂,谢谢,但是有没有这样的函数不会多次触发以获取额外资源..我如何实现呢?我收到一个错误,指出“对象已断开与客户端的连接”。这是通过将
New InternetExplorer
切换到
New InternetExplorerMedium
来解决的,如下所述: