PDA

View Full Version : Google Search VBA and Pull Data



senker
07-19-2017, 08:23 PM
Hi Everyone!


I'm trying to get code to search in Google then to pull the first search result title.


I can get the VBA to load the data in google and run the search but getting stuck on putting it back into excel.


the big picture is to take a list of addresses and get the name, phone number and email off those addresses if that helps.


Thanks!






'start a new subroutine called SearchBot
Option Explicit
Sub SearchBot()


'dimension (declare or set aside memory for) our variables
Dim objIE As InternetExplorer 'special object variable representing the IE browser
Dim aEle As HTMLLinkElement 'special object variable for an <a> (link) element
Dim y As Integer 'integer variable we'll use as a counter
Dim result As String 'string variable that will hold our result link




'initiating a new instance of Internet Explorer and asigning it to objIE
Set objIE = New InternetExplorer

'make IE browser visible (False would allow IE to run in the background)
objIE.Visible = True

'navigate IE to this web page (a pretty neat search engine really)
objIE.navigate "google"

'wait here a few seconds while the browser is busy
Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop


'in the search box put cell "A2" value, the word "in" and cell "C1" value
objIE.document.getElementById("lst-ib").Value = _
Sheets("Sheet1").Range("F6").Value

'wait here a few seconds while the browser is busy
Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop


SendKeys "{Enter}"

'click the 'go' button
'objIE.document.getElementById("gsr").Click

'wait again for the browser
Do While objIE.Busy = True Or objIE.readyState <> 4: DoEvents: Loop


'the first search result will go in row 6
y = 6

'for each <a> element in the collection of objects with class of 'result__a'...
For Each aEle In objIE.document.getElementsByClassName("r")(1)

'...get the text within the element and print it to the sheet in col D
Sheets("Sheet1").Range("H" & y).Value = aEle.innerText
Debug.Print aEle.innerText
Next
'close the browser
objIE.Quit

'exit our SearchBot subroutine
End Sub