使用 VBA EXCEL 填写 USPS 网络表单下拉列表

Fill USPS webform dropdown using VBA EXCEL

我正在尝试自动填写 USPS 网络表单,它适用于街道地址、城市和邮政编码,但我无法让它填写州下拉列表。有什么想法吗?

这是我目前拥有的代码:

Sub USPS()
Dim IE As Object
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True

IE.Navigate "https://tools.usps.com/go/ZipLookupAction!input.action?mode=1&refresh=true"
Do
DoEvents
Loop Until IE.READYSTATE = 4

Call IE.Document.getElementByID("tAddress").SetAttribute("value", "2 Peabody Terrace")
Call IE.Document.getElementByID("tCity").SetAttribute("value", "Cambridge")
Call IE.Document.getElementByID("sState").SetAttribute("value", "MA")
Call IE.Document.getElementByID("Zzip").SetAttribute("value", "02138")

Set AllHyperLinks = IE.Document.GetElementsByTagName("A")
    For Each hyper_link In AllHyperLinks
    If ID = "lookupZipFindBtn" Then
        hyper_link.Click
        Exit For
    End If
    Next
End Sub

非常感谢您的帮助!

对您的代码进行此更改:

'Call IE.Document.getElementByID("sState").SetAttribute("value", "MA")
With IE.Document.getElementByID("sState")
    For i = 0 To .Length - 1
        If .Item(i).Value = "MA" Then
            .Item(i).Selected = True
            Exit For
        End If
    Next
End With

这会起作用...但网页仍会显示 Select 元素未更改。这是一种错觉。我怀疑页面中有一些 JavaScript 干扰了该元素的显示。

但是,如果您在 VBEditor 的即时 Window 中执行此操作:

?IE.Document.getElementByID("sState").value

...您会看到控件的值确实已更改为 'MA'。

此外,如果您继续点击网页的“查找”按钮,您会看到 'MA' 实际上包含在 'You entered:' 下。

所以我上面的代码就是你问题的解决方案。

CSS select或:

您可以使用 css select 或 select 或者来执行此操作。

① 我用的第一个 select 是初始着陆页 select search by address:

#zip-lookup-app a > span

这表示 span 标签位于 a 标签内,位于 ID 为 zip-lookup-app 的元素内。 "#"表示id。

这与以下匹配,我想要第一个。

② 第二个select或:

#tState option[value='MA']

这表示 select option 标签具有属性 value,值为 'MA',在 ID 为 tState 的元素中。 "[]" 表示属性。


VBA:

因为我想要第一场比赛,所以我可以使用 documentquerySelector 方法来应用 CSS select 或者如下所示:

Option Explicit
Public Sub MakeStateSelection()
    Dim ie As New InternetExplorer, html As HTMLDocument
    With ie
        .Visible = True
        .navigate "https://tools.usps.com/go/ZipLookupAction!input.action?mode=1&refresh=true"

        While .Busy Or .READYSTATE < 4: DoEvents: Wend

        Set html = .document
        html.querySelector("#zip-lookup-app > div > div:nth-child(1) > div > ul > li:nth-child(1) > a > span").Click

        While .Busy Or .READYSTATE < 4: DoEvents: Wend

        html.querySelector("#tState option[value='MA']").Selected = True

       'other code
        Stop '<== Delete me

        '.Quit '<== Uncomment me
    End With
End Sub