如何修复';运行时错误91:“;对象变量或未设置块变量";使用vba Excel?
我有一小部分代码可以自动登录到特定网站,有时可以正常工作,有时会出现运行时错误91,表示未设置object variable或with block variable。如何解决此问题如何修复';运行时错误91:“;对象变量或未设置块变量";使用vba Excel?,excel,vba,Excel,Vba,我有一小部分代码可以自动登录到特定网站,有时可以正常工作,有时会出现运行时错误91,表示未设置object variable或with block variable。如何解决此问题 Sub AutoLogin() Const Url = "https://www.tymetrix360.com/Common/Pages/LoginPage.aspx? ReturnUrl=%2f" Dim userName As String, password As String, Logi
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
通过测试是否创建了对象来检查页面上是否存在该元素,怎么样 所以
设置user\u id\u element=ie.document.getElementById(“user\u id”)
然后检查IsObject(user\u id\u 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
哪一行抛出错误?我猜这是您设置用户名的那一行?这两行:@Zac ie.Document.all.Item(“LoginTextBox”).Value=username ie.Document.all.Item(“PasswordTextBox”).Value=passwordGreat听到@DidaW,谢谢您将其标记为正确的解决方案:)