How to use VBA to input text into Google and click search

Viewed 3118

My ultimate goal is to automate using VBA to open a browser, and input username and password for a website, and then click login to further navigate to different pages and download files!

I want to begin with the simplest trial, however, of doing a Google search! I think the idea would be similar because both require to input something and click something.

I found in IE -> Tools(Alt+X) -> F12 Developer Tools can show html codes of website, and even more convenient, it seems I can select regions and get keywords that I'm interested in! Here are 2 screenshots of those regions, the first one is for the search bar, I found "input name = "q", and the second one is for the search button, where I found "input name = "btnK".

And here are my codes:

Sub test()

Set IE = CreateObject("InternetExplorer.Application")
my_url = "https://www.google.ca/?gws_rd=ssl"
IE.Visible = True
IE.navigate my_url

'For example, if I want to search "123"
IE.Document.getElementById("q").Value = "123"

'Click the "Search" button
IE.Document.getElementById("btnK").Click


End Sub

It returns error at IE.Document.getElementById("q").Value = "123",

Method 'Document' of object 'iwebbrowser2' failed.

Don't understand where has gone wrong. I'm really new to how to use VBA to control browsers... Please help, thank you all!

2 Answers

The name of an HTML element is not the same as the ID.

For example, "q" is not the ID of the search bar but it's name. It's ID is "lst-ib"

Adding code:

Sub test()

    Dim ie As Object

    Set ie = CreateObject("InternetExplorer.Application")
    my_url = "https://www.google.ca/?gws_rd=ssl"
    ie.Visible = True
    ie.navigate my_url

    Do While ie.Busy
        DoEvents
    Loop
    Wait 3

    'For example, if I want to search "123"
    ie.Document.getElementById("lst-ib").Value = "123"

    ' Pressing enter
    SendKeys "{ENTER}"

End Sub

Sub Wait(seconds As Integer)

    Application.Wait Now + timeValue("00:00:0" & CStr(seconds))

End Sub

Ensure you use the right wait syntax so page has loaded. You also don't need to loop to submit the form. Just submit direct with

.forms(0).submit

Code:

Option Explicit
Public Sub test()
    Const MY_URL = "https://www.google.ca/?gws_rd=ssl"
    With CreateObject("InternetExplorer.Application")
        .Visible = True
        .navigate MY_URL
        While .Busy Or .readyState < 4: DoEvents: Wend

        With .document
            .getElementById("lst-ib").Value = "123"
            .forms(0).submit
        End With
        'Other code
        '.Quit  '<== Uncomment me later
    End With
End Sub
Related