首页 > 解决方案 > VBA IE自动化-在网页上单击按钮时元素的变量丢失参考

问题描述

我使用 VBA 和 IE 自动化打开网页、登录、通过填写一些输入字段并单击网页的特定按钮进行导航,最后从中获取一些数据。

在导航时,我为网页中的元素设置了几个变量。接下来,我单击网页的按钮,然后单击一些变量(ele0eleeleCol0“失去参考”。我所说的“失去参考”是指它们既不指向元素也不等于什么。


这就是变量(ele0和)在局部变量窗口中的显示ele方式:eleCol0 在此处输入图像描述


这是一些代码:

Option Explicit


Public Sub Get_data()
Dim frmDocDap As HTMLDocument, frmDocPlir As HTMLDocument
Dim ele0 As HTMLHtmlElement, ele As HTMLHtmlElement, ele2 As HTMLHtmlElement, ele3 As HTMLHtmlElement
Dim frm As HTMLFrameElement
Dim eleCol As IHTMLElementCollection, eleCol2 As IHTMLElementCollection, eleCol0 As IHTMLElementCollection
Dim i As Integer, j As Integer
Dim sTemp As String
Dim sArr() As String
Dim bFlag As Boolean
Dim iRow As Long
Dim wsHid As Worksheet

'get doc from a frame:
    Set frm = html.getElementById("tabIframe2") 'html is a global variable of type HTMLDocument that holds the current IE document.
    Set frmDocDap = frm.contentWindow.Document
'udf that delays code by specific seconds:
    Delay_Code_By 1
'get table:
    Set ele0 = frmDocDap.getElementById("multi_record")
'no records check:
    If ele0 Is Nothing And frmDocDap.body.Children.Item(6).innerText = "No records." Then
        If MsgBox("Close Internet Explorer?", vbQuestion + vbYesNo, "No records!") = 6 Then _
            oIE.Quit
        GoTo END_HERE
    End If
    Set ele0 = ele0.FirstChild
'get first row:
    Set eleCol0 = ele0.getElementsByTagName("tr")
'get a specific link.
    Set ele2 = html.getElementById("describe")
    Set ele2 = ele2.getElementsByTagName("a")(5)

i = 2
NEXT_ITEM:
'click record to open details about it.
    Set ele = eleCol0(i)
    ele.Click
'at this point reference is lost for variables ele0, eleCol0, ele. All the others are OK.
    ele2.Click
    
    '...
    
END_HERE:
    Set ele0 = Nothing
    Set ele = Nothing
    Set ele2 = Nothing
    Set frm = Nothing
    Set eleCol0 = Nothing
    Set frmDocDap = Nothing
End Sub


Public Sub Delay_Code_By(seconds As Integer)
Dim endTime As Date
    endTime = DateAdd("s", seconds, Now)
    Do While Now < endTime
        DoEvents
    Loop
End Sub

有人可以解释一下吗:

我需要了解这一点才能避免它。

标签: vbaie-automation

解决方案


您经常会在刷新时获得陈旧的元素,例如某些点击事件。如果元素存在于新加载的内容中,那么通常可以简单地避免存储在变量中并始终使用 ie.document。我假设您正在使用一个可以更新您执行的操作的实时文档。然后,我将在本地传递 Internet Explorer 实例,而不是全局传递存储的 HTMLDocument 变量。


推荐阅读