Click the button on the USPS Web Site to find 9 digit Zip Code

Viewed 307

USPS ZipCode Website & Excel VBA -- I have all of the code working to populate the site, but I can not click the "FIND" submit button with Excel-VBA code.

Here is the URL for the site and all of the button clicking code I have submitted

https://tools.usps.com/zip-code-lookup.htm?byaddress


'All of the different submit Code I have tried:

html.all.getElementById("zip-by-address").Click
html.all.getelementbytagname("zip-by-address").Click
html.document.querySelector("Find[type=submit]").Click

html.document.getElementsByClassName("btn btn-primary").Click
html.document.getElementById("zip-by-address").Click

For Each Element In ie.document.getElementsByName("zip-by-address")
    If Element.className = "btn-primary" Then
        Element.Click
    End If
Next

ie.document.querySelector("button[type=submit]").Click

For Each Element In ie.document.getElementsByTagName("zip-by-address")
    If InStr(Element.innerText, "Find") > 0 Then Element.Click
Next

ie.document.getElementByTagName("Find").FireEvent "onclick"

ie.document.getElementById("zip-by-address").FireEvent "onkeypress"
ie.document.getElementById("zip-by-address").FireEvent "onclick"

Set frm = ie.document.forms(0)
frm.submit
2 Answers

I had to complete the city and state fields as well. You don't need to select the by address option as it is already part of the url.

.querySelector("#zip-by-address").Click is equivalent to .getElementById("zip-by-address").Click but faster as modern browsers (cough IE cough) are optimized for selecting by css selectors.

Public Sub ClickFindButton()

    Dim ie As SHDocVw.InternetExplorer

    Set ie = New SHDocVw.InternetExplorer

    With ie

        .Visible = True
        .Navigate2 "https://tools.usps.com/zip-code-lookup.htm?byaddress" 'url is already by address so no need to click for it

        Do
            DoEvents
        Loop While .Busy Or .ReadyState <> READYSTATE_COMPLETE

        With .Document

            .querySelector("#tCompany").Value = "The New York Times Company"

            .querySelector("#tAddress").Value = "620 Eighth Avenue"

            .querySelector("#tCity").Value = "New York"

            .querySelector("[value=NY]").Selected = True

            .querySelector("#zip-by-address").Click

            Stop

        End With
        .Quit
    End With
End Sub

Search by Id

Example

ie.Document.getElementById("zip-by-address").Click

enter image description here

Related