Don't use SendKeys
for GUI automation. It's extremely, terribly, awfully unreliable. SendKeys
is like typing blindfold — you can't be sure you send keys to the correct object, because other windows can steal the input focus from your target at any time.
In your case, you can use Internet Explorer's scripting object - InternetExplorer.Application
. It lets you access the web page's DOM (Document Object Model), so you can enter data, click links and buttons, submit forms and navigate web pages programmatically.
Dim objIE
Set objIE = CreateObject("InternetExplorer.Application")
objIE.Visible = True
objIE.Navigate "https://twitter.com/search-home"
While objIE.Busy
WScript.Sleep 100
Wend
objIE.Document.getElementById("search-home-input").value = "haiku"
objIE.Document.getElementsByClassName("search-btn")(0).click
To connect to an already opened web page, you can use the following function instead of CreateObject("InternetExplorer.Application")
:
Set objIE = GetIE("Twitter / Search")
...
Function GetIE(Title)
Dim objShell, objIE
Set objShell = CreateObject("Shell.Application")
For Each objIE In objShell.Windows
If InStr(objIE.LocationName, Title) > 0 Then
Set GetIE = objIE
Exit Function
End If
Next
End Function
This code searches for a web page by its title. To search by URL instead of title, replace
If InStr(objIE.LocationName, Title) > 0 Then
with
If InStr(objIE.LocationURL, Title) > 0 Then