首页 > 解决方案 > 如何使用 vba Excel 修复“运行时错误 91:“对象变量或未设置块变量”?

问题描述

我有一小段代码可以自动登录到特定网站,该网站有时有效,有时会出现运行时错误 91,表示对象变量或未设置块变量。我该如何解决这个问题?

Sub AutoLogin()
    Const Url = "https://www.tymetrix360.com/Common/Pages/LoginPage.aspx? 
ReturnUrl=%2f"

    Dim userName As String, password As String, LoginData As Worksheet
    Set LoginData = ThisWorkbook.Worksheets("Sheet1")
    userName = LoginData.Cells(1, "A").Value
    password = LoginData.Cells(2, "A").Value

    Dim ie As Object

    Set ie = CreateObject("InternetExplorer.Application")


        ie.navigate Url
        ie.Visible = True

        ieBusy ie

        ie.Document.all.Item("LoginTextBox").Value = userName
        ie.Document.all.Item("PasswordTextBox").Value = password

        ie.Document.all.Item("LoginButton").Click

End Sub

Sub ieBusy(ie As Object)
    Do While ie.Busy
        DoEvents
    Loop
End Sub

标签: excelvba

解决方案


通过测试是否创建了对象来检查页面上是否存在元素呢?

那么Set user_id_element = ie.document.getElementById("user_id")然后检查IsObject(user_id_element)它是否继续,如果不是那么循环直到出现?最好有某种退出条件,以防它永远不存在。

像这样的东西:

Sub AutoLogin()
    Const Url = "https://www.campus.ie.edu"

    Dim userName As String, password As String, LoginData As Worksheet
    Set LoginData = ThisWorkbook.Worksheets("Sheet1")
    userName = LoginData.Cells(1, "A").Value
    password = LoginData.Cells(2, "A").Value

    Dim ie As Object

    Set ie = CreateObject("InternetExplorer.Application")


        ie.navigate Url
        ie.Visible = True

        ieBusy ie

        Debug.Print ie.locationurl
        If InStr(1, ie.locationurl, "portal") > 0 Then
            'Already logged in
        Else
            'Need to log in
            Do While Not IsObject(ie.document.getElementById("user_id"))
                'Check if the element is present, otherwise loop and wait
                ieBusy ie
            Loop

            ie.document.getElementById("user_id").Value = userName
            ie.document.all.Item("password").Value = password

            'One way or another submit the form
            'ie.document.getElementById("password").Focus
            'Application.SendKeys "{ENTER}" 'Submit form

            ie.document.forms("login").submit
            'ie.Document.getelementbyid("login").Click
        End If

End Sub

Sub ieBusy(ie As Object)
    Do While ie.Busy
        DoEvents
    Loop
End Sub

推荐阅读