首页 > 解决方案 > Excel VBA Sendkeys 在第二个循环中停止/暂停

问题描述

截屏

我正在填写网络表单。它需要按键盘。所以我使用 sendkeys 来点击标签。它第一次工作得很好,但是当它第二次循环时,它会在Application.SendKeys "{TAB}", True. 我必须在 VBA 内单击,然后它会再次恢复。

谢谢你。

对于 i = 2 到 3

IE.getElementsByName("recipientName")(0).Value = ActiveSheet.Range("A" & i)

   AppActivate ("Internet Explorer"), True
        Application.Wait (Now + TimeValue("00:00:03"))
    For tabbtn = 1 To 20
        Application.SendKeys "{TAB}", True
        Application.Wait (Now + TimeValue("00:00:01"))
     Next Tabbtb

Next i
End Sub

标签: excelvbaloopsinternet-explorersendkeys

解决方案


我尝试检查该站点,并且我了解您正在尝试将值添加到文本框中,但是当您提交数据时,它显示字段是必需的。

传递 TAB 键 20 次不是此问题的正确解决方案。

您需要在字段中设置值后调度事件。

注意:您需要为添加值的每个字段分派事件。

我无权访问该特定页面,因此我使用他们的登录页面进行了测试。整个站点的代码结构都是相同的。

在这里,我只是向您展示如何为元素分派事件的演示。

有2个文本框。1 用户名 2 密码。我只会尝试为用户名发送事件。您会注意到,它不会显示用户名的必需验证,但会显示密码的必需验证。

示例代码:

   Option Explicit

'It works with Excel 32 bit and Excel 64 bit
#If Win64 Then
  'For 64 bit systems
  Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As LongPtr)
#Else
  'For 32 bit systems
 ' Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If

Sub test()

Dim url As String
Dim browser As Object
Dim btn As Object
Dim txt As Object
Dim psw As Object

  url = "https://www.myhermes.co.uk/login.html#/" 'Please modify the URL here...

  Set browser = CreateObject("internetexplorer.application")
  browser.Visible = True
  browser.navigate url
  Do Until browser.readyState = 4: DoEvents: Loop
  'Stop
  Set txt = browser.document.getElementById("existingUser") ' Please modify the ID of the element here...
  txt.Focus
  txt.Value = "abc@xyz.com"
  Set psw = browser.document.getElementById("existingPassword")
  psw.Value = "12345"
  Call TriggerEvent(browser.document, txt, "change")

   Set btn = browser.document.getElementById("loginButton") ' This is the demo submit button. You can modify this code as per your own requirements...
  btn.Click

End Sub

Private Sub TriggerEvent(htmlDocument As Object, htmlElementWithEvent As Object, eventType As String)

  Dim theEvent As Object

  htmlElementWithEvent.Focus
  Set theEvent = htmlDocument.createEvent("HTMLEvents")
  theEvent.initEvent eventType, True, False
  htmlElementWithEvent.dispatchEvent theEvent
End Sub

输出:

在此处输入图像描述

您需要在输入值的页面上执行类似的操作来解决此问题。您可以根据需要修改代码示例。


推荐阅读