【问题标题】:VBA IE automation, To trigger some action in VBA before whenever i navigate to other page in websiteVBA IE 自动化,在我导航到网站中的其他页面之前触发 VBA 中的某些操作
【发布时间】:2012-10-18 03:43:18
【问题描述】:

我需要一个 VBA 代码,当网页框架即将导航到其他页面时,它可以在 VBA 中执行一些操作。例如,当我单击某个链接时,按钮导航到我想要截屏的其他页面框架导航到其他页面之前的页面。我做了类似的事情,但它正在拍摄空白页面的屏幕截图,并且它仅在页面导航和对象更改时工作一次。请帮我解决这个问题,自从 2 周以来我一直在寻找这个,帮帮我。

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

【问题讨论】:

    标签: vba excel webautomation


    【解决方案1】:

    这是一个可能的解决方案。仅向您展示如何创建对象并指定BeforeNavigate2 事件。这需要您引用 Microsoft Internet Controls 并创建 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 事件实际上会触发多次,因为加载时会额外调用资源。

    【讨论】:

    • 非常感谢您非常棒的解决方案,我使用了循环和状态并使它变得复杂,谢谢,但是有没有像这样的函数不会多次触发以获得额外的资源..我怎样才能实现呢?
    • 我收到一条错误消息,指出“对象已与其客户端断开连接。”这已通过将New InternetExplorer 切换为New InternetExplorerMedium 来解决,如下所述:stackoverflow.com/questions/42403210
    猜你喜欢
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-12
    相关资源
    最近更新 更多