我正在尝试在网页上使用VBA。我已经弄清楚了如何登录并提交我的用户名和密码。接下来,我需要单击3个按钮。它们仅在单击上一个按钮后出现。我有if语句,如果我逐段检查代码,这些语句就可以工作。看起来它遍历每个语句多次-经历了if then部分,然后退出for,end if,next,然后再次返回if语句,而没有完成任务。它会执行几次,直到我猜最终它会起作用。
我基本上已经尝试了一切。 .document.getElementsbyId和与之相关的所有文件均无效。也许是否有一种方法可以搜索文档并单击它?似乎它不起作用,因为直到最后它才是不正确的?我真的不确定(我是新来的)
'Enters username and password & submits
With .document.forms("signinginn")
.User.Value = "username"
.Password.Value = "password"
.document.forms(0).submit
End With
Application.Wait DateAdd("s", 2, Now)
With IE.document
Set a = .getElementsbyTagName("input")
For Each a In .getElementsbyTagName("input")
If a.getAttribute("value") = "Start" Then
a.Click
Exit For
End If
Next a
如果我部分地执行此代码,则此代码有效,但它只经历了几次。我能否在第一时间得到正确的显示?该代码的预期输出将通过并立即单击按钮。
答案 0 :(得分:0)
尝试为要显示的元素添加定时循环,等待适当的页面加载,并使用querySelector删除当前循环并仅将输入元素的属性值作为目标
Option Explicit
'VBE > Tools > References: Microsoft Internet Controls
Public Sub ClickElement()
Dim ie As Object, elems As Object, t As Date
Const MAX_WAIT_SEC As Long = 10
Set ie = CreateObject("InternetExplorer.Application")
With ie
.Visible = True
.Navigate2 "url"
While .Busy Or .readyState < 4: DoEvents: Wend
With .document.forms("signinginn")
.User.Value = "username"
.Password.Value = "password"
.document.forms(0).submit
End With
While .Busy Or .readyState < 4: DoEvents: Wend
t = Timer
Do
On Error Resume Next
Set elems = .document.querySelectorAll("input[value=Start]")
On Error GoTo 0
If Timer - t > MAX_WAIT_SEC Then Exit Do
Loop While elems Is Nothing
If Not elems Is Nothing Then
elems.item(0).Click
Else
Exit Sub
End If
'Other code
Stop '<=Delete me later
.Quit
End With
End Sub