首页 > 解决方案 > 单击网页按钮功能在excel宏中不起作用

问题描述

我正在尝试创建 Fedex 跟踪自动化,但无法单击“跟踪”按钮。有什么想法吗?

Sub Fedex()
    
    Dim IE As Object
    Dim doc As HTMLDocument
    
    Set IE = New InternetExplorerMedium
    IE.Visible = True
    IE.navigate "https://www.fedex.com/en-us/home.html"
    
    Do While IE.Busy Or IE.READYSTATE = 4
    Loop
    
    Application.Wait (Now + TimeValue("0:00:07"))
    
    Set searchbx = IE.document.getElementsByName("trackingnumber")(0)
    searchbx.Value = "Howdy!"

    IE.document.getElementById("btnSingleTrack").Click

End Sub

标签: excelvba

解决方案


编辑 - 通过 url 参数直接执行

您可以操纵您导航的网址。看下面的例子。将最后一个参数的值更改为YourTrackingNumberHere有效的跟踪号并手动测试:

https://www.fedex.com/apps/fedextrack/?action=track&cntry_code=us&locale=en_US&trackingnumber=YourTrackingNumberHere

使其以您的方式工作的第一个答案

搜索框有事件。您必须在设置跟踪号后触发更改事件。我以前从未见过,但是在触发更改事件后,您必须等待几秒钟才能使按钮单击起作用。

Sub Fedex()
  Dim ie As Object
  Dim searchBox As Object
  
  'Initialize Internet Explorer, set visibility,
  'call URL and wait until page is fully loaded
  Set ie = CreateObject("InternetExplorer.Application")
  ie.Visible = True
  ie.navigate "https://www.fedex.com/en-us/home.html"
  Do While ie.READYSTATE <> 4: DoEvents: Loop
  
  Set searchBox = ie.document.getElementsByName("trackingnumber")(0)
  searchBox.Value = "Howdy!"
  'Trigger the change event of the input box
  Call TriggerEvent(ie.document, searchBox, "change")
  'I don't know why, but you have to wait a few seconds
  'Otherwise the button click will not work
  'In my tests, I need 5 seconds to make it work in every case
  'You can make your own tests for your environment
  Application.Wait (Now + TimeValue("0:00:05"))
  
  ie.document.getElementById("btnSingleTrack").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

推荐阅读