I have found the Macro for MS Word (as below) from the website https://excelchamps.com/blog/vba-code-search-google-chrome/
Sub GoogleSearch()
Dim chromePath As String
Dim search_string As String
Dim query As String
query = InputBox("Please enter the keywords", "Google Search")
search_string = query
search_string = Replace(search_string, " ", " ")
chromePath = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Shell (chromePath & " -url http://www.google.com/search?hl=en&q=" & search_string)
End Sub
It is expected that: I press the Macro button, the InputBox pop-out, then I type keywords and it automatically opens Chrome to search those keywords.
If I press the Macro button mistakenly, then I press "Cancel" or "X" to close the Inputbox, Chrome will not automatically open.
I added if msgboxresult = "" then exit sub in the middle of the code. When I open the Inputbox and close it, Chrome doesn't open. But whatever I typed in the Inputbox, Chrome doesn't open and no search is conducted.
Does anyone know what codes should add to it in order to make it End Sub when I don't type anything and close the Inputbox?
CodePudding user response:
Whilst (StrPtr(query) = 0)
will indicate that the user pressed cancel it will not catch when the user has left the search term blank and clicked OK.
A better way of writing your routine is to ignore whether the user cancelled and check whether you have a search term to google. Simply checking that query
isn't a zero length string before proceeding to launch chrome will catch both eventualities.
Sub GoogleSearch()
Const chromePath As String = "C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"
Dim query As String
query = InputBox("Please enter the keywords", "Google Search")
If Not query = vbNullString Then
query = Replace(query, " ", " ")
Shell (chromePath & " -url http://www.google.com/search?hl=en&q=" & query)
End If
End Sub