我是Excel宏(VBA)的新手,并且正在寻找一种使IE自动登录到网站并进入特定页面的方法。网站网址:https : //www.mast-technicalservices.com/ecp/index2.jsp,需要填写登录详细信息,然后单击继续。
Sub WebsiteLogIn()
Dim nURL As String
Dim UNElementID As String
Dim UserName As String
Dim PWElementID As String
Dim Password As String
Dim SIElementID As String
Set LoginData = ThisWorkbook.Sheets("Sheet1")
Set nURL = "https://www.mast-technicalservices.com/ecp/index2.jsp"
Set UNElementID = "ecp_param_userId"
Set UserName = LoginData.Cells(1, "B").Value
Set PWElementID = "ecp_param_password"
Set Password = LoginData.Cells(2, "B").Value
Set SIElementID = "imageField2"
Dim IE As Object
Dim IEPage As Object
Dim IEPageElement As Object
'Create a new Internet Explorer instance, make it visible and maximize its window and navigate to url.
On Error Resume Next
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
ShowWindow IE.hwnd, SW_MAXIMIZE
IE.navigate URL
Set IEPage = IE.document
'setthe UserName text box using the element ID.
Set IEPageElement = IEPage.getElementById(UNElementID)
'set the Password text box using the element ID.
Set IEPageElement = IEPage.getElementById(PWElementID)
'set the Continue button using the element ID.
Set IEPageElement = IEPage.getElementById(SIElementID)
End Sub
这有效:
Sub login()
Const Url$ = "https://www.mast-technicalservices.com/ecp/index2.jsp"
Dim UserName As String, Password As String, LoginData As Worksheet
Set LoginData = ThisWorkbook.Worksheets("Sheet1")
UserName = LoginData.Cells(1, "B").Value
Password = LoginData.Cells(2, "B").Value
Dim ie As Object
Set ie = CreateObject("InternetExplorer.Application")
With ie
.navigate Url
ieBusy ie
.Visible = True
Dim oLogin As Object, oPassword As Object
Set oLogin = .document.getElementsByName("ecp_param_userId")(0)
Set oPassword = .document.getElementsByName("ecp_param_password")(0)
oLogin.Value = UserName
oPassword.Value = Password
.document.forms(0).submit
End With
End Sub
Sub ieBusy(ie As Object)
Do While ie.Busy Or ie.readyState < 4
DoEvents
Loop
End Sub
另一个sub:ieBusy
将确保你在尝试操作网页之前已完全加载该网页。
我尝试了代码,但遇到运行时错误“自动化错误和未指定的错误”,调试指向“ Do While”行,即ie.Busy或ie.readyState <READYSTATE_COMPLETE
还有更多错误详细信息吗?它指向特定的行了吗?我自己尝试了该代码,然后该代码起作用了(但是,我承认,这是我最新的更新之前的代码)。
我曾尝试过几次使用READYSTATE选项,但也失败了。我必须启用其他任何控件或引用才能使用此代码吗?
糟糕,这是因为您使用的是后期绑定。将READYSTATE_COMPLETE替换为数字
4
。还是一样。调试指向该行Do While ie.Busy或ie.readyState <4