-1

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?

Pᴇʜ
  • 56,719
  • 10
  • 49
  • 73
7hcl5
  • 5
  • 2
  • 1
    You asked the same question already and you got the answer: [How to add message box VbCancel?](https://stackoverflow.com/questions/74107163/how-to-add-message-box-vbcancel): `If (StrPtr(query) = 0) Then Exit Sub` – Pᴇʜ Oct 18 '22 at 15:12

1 Answers1

0

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
Timothy Rylatt
  • 7,221
  • 2
  • 10
  • 14