excel - 如何使用 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
解决方案
通过测试是否创建了对象来检查页面上是否存在元素呢?
那么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
推荐阅读
- python - Data manipulation in Pandas Dataframe add row for each group
- twitter - 无法使用 Landoop/Fast-data-dev 创建 twitterSourceConnector。创建按钮被禁用
- python - 用于获取 JSON 请求的函数的 Python 装饰器
- java - 如何让这个 android 材质看起来不错?
- python-3.x - Python新手:使用字典中的值打印列表
- kubernetes - metrics-server 和 prometheus-adapter 等metrics provider如何将自己的api注册到kubernetes apiserver
- python - 如何根据数值列值将 Pandas 数据框中的一行转换为多行?
- windows - Why is the syntax of command FOR incorrect?
- c++ - how to reduce compile time: in case of including an untouched header file
- layout - 将按钮添加到布局,它不会显示